1use crate::askpass_modal::AskPassModal;
2use crate::commit_modal::CommitModal;
3use crate::commit_tooltip::CommitTooltip;
4use crate::commit_view::CommitView;
5use crate::project_diff::{self, BranchDiff, Diff, ProjectDiff};
6use crate::remote_output::{self, RemoteAction, SuccessMessage};
7use crate::{branch_picker, picker_prompt, render_remote_button};
8use crate::{
9 file_history_view::FileHistoryView, git_panel_settings::GitPanelSettings, git_status_icon,
10 repository_selector::RepositorySelector,
11};
12use agent_settings::AgentSettings;
13use anyhow::Context as _;
14use askpass::AskPassDelegate;
15use cloud_llm_client::CompletionIntent;
16use collections::{BTreeMap, HashMap, HashSet};
17use db::kvp::KEY_VALUE_STORE;
18use editor::{
19 Direction, Editor, EditorElement, EditorMode, MultiBuffer, MultiBufferOffset,
20 actions::ExpandAllDiffHunks,
21};
22use editor::{EditorStyle, RewrapOptions};
23use futures::StreamExt as _;
24use git::commit::ParsedCommitMessage;
25use git::repository::{
26 Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,
27 PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,
28 UpstreamTrackingStatus, get_git_committer,
29};
30use git::stash::GitStash;
31use git::status::{DiffStat, StageStatus};
32use git::{Amend, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};
33use git::{
34 ExpandCommitEditor, GitHostingProviderRegistry, RestoreTrackedFiles, StageAll, StashAll,
35 StashApply, StashPop, TrashUntrackedFiles, UnstageAll,
36};
37use gpui::{
38 Action, AsyncApp, AsyncWindowContext, Bounds, ClickEvent, Corner, DismissEvent, Empty, Entity,
39 EventEmitter, FocusHandle, Focusable, KeyContext, MouseButton, MouseDownEvent, Point,
40 PromptLevel, ScrollStrategy, Subscription, Task, TextStyle, UniformListScrollHandle,
41 WeakEntity, actions, anchored, deferred, point, size, uniform_list,
42};
43use itertools::Itertools;
44use language::{Buffer, BufferEvent, File};
45use language_model::{
46 ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
47};
48use menu;
49use multi_buffer::ExcerptInfo;
50use notifications::status_toast::{StatusToast, ToastIcon};
51use panel::{PanelHeader, panel_button, panel_filled_button, panel_icon_button};
52use project::{
53 Fs, Project, ProjectPath,
54 buffer_store::BufferStoreEvent,
55 git_store::{GitStoreEvent, Repository, RepositoryEvent, RepositoryId, pending_op},
56 project_settings::{GitPathStyle, ProjectSettings},
57};
58use prompt_store::{BuiltInPrompt, PromptId, PromptStore, RULES_FILE_NAMES};
59use serde::{Deserialize, Serialize};
60use settings::{Settings, SettingsStore, StatusStyle};
61use smallvec::SmallVec;
62use std::future::Future;
63use std::ops::Range;
64use std::path::Path;
65use std::{sync::Arc, time::Duration, usize};
66use strum::{IntoEnumIterator, VariantNames};
67use theme::ThemeSettings;
68use time::OffsetDateTime;
69use ui::{
70 ButtonLike, Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, IndentGuideColors,
71 PopoverMenu, RenderedIndentGuide, ScrollAxes, Scrollbars, SplitButton, Tooltip, WithScrollbar,
72 prelude::*,
73};
74use util::paths::PathStyle;
75use util::{ResultExt, TryFutureExt, maybe, rel_path::RelPath};
76use workspace::SERIALIZATION_THROTTLE_TIME;
77use workspace::{
78 Workspace,
79 dock::{DockPosition, Panel, PanelEvent},
80 notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId, NotifyResultExt},
81};
82
83actions!(
84 git_panel,
85 [
86 /// Closes the git panel.
87 Close,
88 /// Toggles the git panel.
89 Toggle,
90 /// Toggles focus on the git panel.
91 ToggleFocus,
92 /// Opens the git panel menu.
93 OpenMenu,
94 /// Focuses on the commit message editor.
95 FocusEditor,
96 /// Focuses on the changes list.
97 FocusChanges,
98 /// Select next git panel menu item, and show it in the diff view
99 NextEntry,
100 /// Select previous git panel menu item, and show it in the diff view
101 PreviousEntry,
102 /// Select first git panel menu item, and show it in the diff view
103 FirstEntry,
104 /// Select last git panel menu item, and show it in the diff view
105 LastEntry,
106 /// Toggles automatic co-author suggestions.
107 ToggleFillCoAuthors,
108 /// Toggles sorting entries by path vs status.
109 ToggleSortByPath,
110 /// Toggles showing entries in tree vs flat view.
111 ToggleTreeView,
112 /// Expands the selected entry to show its children.
113 ExpandSelectedEntry,
114 /// Collapses the selected entry to hide its children.
115 CollapseSelectedEntry,
116 ]
117);
118
119actions!(
120 git_graph,
121 [
122 /// Opens the Git Graph Tab.
123 Open,
124 ]
125);
126
127/// Opens the Git Graph Tab at a specific commit.
128#[derive(Clone, PartialEq, serde::Deserialize, schemars::JsonSchema, gpui::Action)]
129#[action(namespace = git_graph)]
130pub struct OpenAtCommit {
131 pub sha: String,
132}
133
134fn prompt<T>(
135 msg: &str,
136 detail: Option<&str>,
137 window: &mut Window,
138 cx: &mut App,
139) -> Task<anyhow::Result<T>>
140where
141 T: IntoEnumIterator + VariantNames + 'static,
142{
143 let rx = window.prompt(PromptLevel::Info, msg, detail, T::VARIANTS, cx);
144 cx.spawn(async move |_| Ok(T::iter().nth(rx.await?).unwrap()))
145}
146
147#[derive(strum::EnumIter, strum::VariantNames)]
148#[strum(serialize_all = "title_case")]
149enum TrashCancel {
150 Trash,
151 Cancel,
152}
153
154struct GitMenuState {
155 has_tracked_changes: bool,
156 has_staged_changes: bool,
157 has_unstaged_changes: bool,
158 has_new_changes: bool,
159 sort_by_path: bool,
160 has_stash_items: bool,
161 tree_view: bool,
162}
163
164fn git_panel_context_menu(
165 focus_handle: FocusHandle,
166 state: GitMenuState,
167 window: &mut Window,
168 cx: &mut App,
169) -> Entity<ContextMenu> {
170 ContextMenu::build(window, cx, move |context_menu, _, _| {
171 context_menu
172 .context(focus_handle)
173 .action_disabled_when(
174 !state.has_unstaged_changes,
175 "Stage All",
176 StageAll.boxed_clone(),
177 )
178 .action_disabled_when(
179 !state.has_staged_changes,
180 "Unstage All",
181 UnstageAll.boxed_clone(),
182 )
183 .separator()
184 .action_disabled_when(
185 !(state.has_new_changes || state.has_tracked_changes),
186 "Stash All",
187 StashAll.boxed_clone(),
188 )
189 .action_disabled_when(!state.has_stash_items, "Stash Pop", StashPop.boxed_clone())
190 .action("View Stash", zed_actions::git::ViewStash.boxed_clone())
191 .separator()
192 .action("Open Diff", project_diff::Diff.boxed_clone())
193 .separator()
194 .action_disabled_when(
195 !state.has_tracked_changes,
196 "Discard Tracked Changes",
197 RestoreTrackedFiles.boxed_clone(),
198 )
199 .action_disabled_when(
200 !state.has_new_changes,
201 "Trash Untracked Files",
202 TrashUntrackedFiles.boxed_clone(),
203 )
204 .separator()
205 .entry(
206 if state.tree_view {
207 "Flat View"
208 } else {
209 "Tree View"
210 },
211 Some(Box::new(ToggleTreeView)),
212 move |window, cx| window.dispatch_action(Box::new(ToggleTreeView), cx),
213 )
214 .when(!state.tree_view, |this| {
215 this.entry(
216 if state.sort_by_path {
217 "Sort by Status"
218 } else {
219 "Sort by Path"
220 },
221 Some(Box::new(ToggleSortByPath)),
222 move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),
223 )
224 })
225 })
226}
227
228const GIT_PANEL_KEY: &str = "GitPanel";
229
230const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
231// TODO: We should revise this part. It seems the indentation width is not aligned with the one in project panel
232const TREE_INDENT: f32 = 16.0;
233
234pub fn register(workspace: &mut Workspace) {
235 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
236 workspace.toggle_panel_focus::<GitPanel>(window, cx);
237 });
238 workspace.register_action(|workspace, _: &Toggle, window, cx| {
239 if !workspace.toggle_panel_focus::<GitPanel>(window, cx) {
240 workspace.close_panel::<GitPanel>(window, cx);
241 }
242 });
243 workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
244 CommitModal::toggle(workspace, None, window, cx)
245 });
246 workspace.register_action(|workspace, _: &git::Init, window, cx| {
247 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
248 panel.update(cx, |panel, cx| panel.git_init(window, cx));
249 }
250 });
251}
252
253#[derive(Debug, Clone)]
254pub enum Event {
255 Focus,
256}
257
258#[derive(Serialize, Deserialize)]
259struct SerializedGitPanel {
260 width: Option<Pixels>,
261 #[serde(default)]
262 amend_pending: bool,
263 #[serde(default)]
264 signoff_enabled: bool,
265}
266
267#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
268enum Section {
269 Conflict,
270 Tracked,
271 New,
272}
273
274#[derive(Debug, PartialEq, Eq, Clone)]
275struct GitHeaderEntry {
276 header: Section,
277}
278
279impl GitHeaderEntry {
280 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
281 let this = &self.header;
282 let status = status_entry.status;
283 match this {
284 Section::Conflict => {
285 repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path)
286 }
287 Section::Tracked => !status.is_created(),
288 Section::New => status.is_created(),
289 }
290 }
291 pub fn title(&self) -> &'static str {
292 match self.header {
293 Section::Conflict => "Conflicts",
294 Section::Tracked => "Tracked",
295 Section::New => "Untracked",
296 }
297 }
298}
299
300#[derive(Debug, PartialEq, Eq, Clone)]
301enum GitListEntry {
302 Status(GitStatusEntry),
303 TreeStatus(GitTreeStatusEntry),
304 Directory(GitTreeDirEntry),
305 Header(GitHeaderEntry),
306}
307
308impl GitListEntry {
309 fn status_entry(&self) -> Option<&GitStatusEntry> {
310 match self {
311 GitListEntry::Status(entry) => Some(entry),
312 GitListEntry::TreeStatus(entry) => Some(&entry.entry),
313 _ => None,
314 }
315 }
316
317 fn directory_entry(&self) -> Option<&GitTreeDirEntry> {
318 match self {
319 GitListEntry::Directory(entry) => Some(entry),
320 _ => None,
321 }
322 }
323
324 /// Returns the tree indentation depth for this entry.
325 fn depth(&self) -> usize {
326 match self {
327 GitListEntry::Directory(dir) => dir.depth,
328 GitListEntry::TreeStatus(status) => status.depth,
329 _ => 0,
330 }
331 }
332}
333
334enum GitPanelViewMode {
335 Flat,
336 Tree(TreeViewState),
337}
338
339impl GitPanelViewMode {
340 fn from_settings(cx: &App) -> Self {
341 if GitPanelSettings::get_global(cx).tree_view {
342 GitPanelViewMode::Tree(TreeViewState::default())
343 } else {
344 GitPanelViewMode::Flat
345 }
346 }
347
348 fn tree_state(&self) -> Option<&TreeViewState> {
349 match self {
350 GitPanelViewMode::Tree(state) => Some(state),
351 GitPanelViewMode::Flat => None,
352 }
353 }
354
355 fn tree_state_mut(&mut self) -> Option<&mut TreeViewState> {
356 match self {
357 GitPanelViewMode::Tree(state) => Some(state),
358 GitPanelViewMode::Flat => None,
359 }
360 }
361}
362
363#[derive(Default)]
364struct TreeViewState {
365 // Maps visible index to actual entry index.
366 // Length equals the number of visible entries.
367 // This is needed because some entries (like collapsed directories) may be hidden.
368 logical_indices: Vec<usize>,
369 expanded_dirs: HashMap<TreeKey, bool>,
370 directory_descendants: HashMap<TreeKey, Vec<GitStatusEntry>>,
371}
372
373impl TreeViewState {
374 fn build_tree_entries(
375 &mut self,
376 section: Section,
377 mut entries: Vec<GitStatusEntry>,
378 seen_directories: &mut HashSet<TreeKey>,
379 ) -> Vec<(GitListEntry, bool)> {
380 if entries.is_empty() {
381 return Vec::new();
382 }
383
384 entries.sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
385
386 let mut root = TreeNode::default();
387 for entry in entries {
388 let components: Vec<&str> = entry.repo_path.components().collect();
389 if components.is_empty() {
390 root.files.push(entry);
391 continue;
392 }
393
394 let mut current = &mut root;
395 let mut current_path = String::new();
396
397 for (ix, component) in components.iter().enumerate() {
398 if ix == components.len() - 1 {
399 current.files.push(entry.clone());
400 } else {
401 if !current_path.is_empty() {
402 current_path.push('/');
403 }
404 current_path.push_str(component);
405 let dir_path = RepoPath::new(¤t_path)
406 .expect("repo path from status entry component");
407
408 let component = SharedString::from(component.to_string());
409
410 current = current
411 .children
412 .entry(component.clone())
413 .or_insert_with(|| TreeNode {
414 name: component,
415 path: Some(dir_path),
416 ..Default::default()
417 });
418 }
419 }
420 }
421
422 let (flattened, _) = self.flatten_tree(&root, section, 0, seen_directories);
423 flattened
424 }
425
426 fn flatten_tree(
427 &mut self,
428 node: &TreeNode,
429 section: Section,
430 depth: usize,
431 seen_directories: &mut HashSet<TreeKey>,
432 ) -> (Vec<(GitListEntry, bool)>, Vec<GitStatusEntry>) {
433 let mut all_statuses = Vec::new();
434 let mut flattened = Vec::new();
435
436 for child in node.children.values() {
437 let (terminal, name) = Self::compact_directory_chain(child);
438 let Some(path) = terminal.path.clone().or_else(|| child.path.clone()) else {
439 continue;
440 };
441 let (child_flattened, mut child_statuses) =
442 self.flatten_tree(terminal, section, depth + 1, seen_directories);
443 let key = TreeKey { section, path };
444 let expanded = *self.expanded_dirs.get(&key).unwrap_or(&true);
445 self.expanded_dirs.entry(key.clone()).or_insert(true);
446 seen_directories.insert(key.clone());
447
448 self.directory_descendants
449 .insert(key.clone(), child_statuses.clone());
450
451 flattened.push((
452 GitListEntry::Directory(GitTreeDirEntry {
453 key,
454 name,
455 depth,
456 expanded,
457 }),
458 true,
459 ));
460
461 if expanded {
462 flattened.extend(child_flattened);
463 } else {
464 flattened.extend(child_flattened.into_iter().map(|(child, _)| (child, false)));
465 }
466
467 all_statuses.append(&mut child_statuses);
468 }
469
470 for file in &node.files {
471 all_statuses.push(file.clone());
472 flattened.push((
473 GitListEntry::TreeStatus(GitTreeStatusEntry {
474 entry: file.clone(),
475 depth,
476 }),
477 true,
478 ));
479 }
480
481 (flattened, all_statuses)
482 }
483
484 fn compact_directory_chain(mut node: &TreeNode) -> (&TreeNode, SharedString) {
485 let mut parts = vec![node.name.clone()];
486 while node.files.is_empty() && node.children.len() == 1 {
487 let Some(child) = node.children.values().next() else {
488 continue;
489 };
490 if child.path.is_none() {
491 break;
492 }
493 parts.push(child.name.clone());
494 node = child;
495 }
496 let name = parts.join("/");
497 (node, SharedString::from(name))
498 }
499}
500
501#[derive(Debug, PartialEq, Eq, Clone)]
502struct GitTreeStatusEntry {
503 entry: GitStatusEntry,
504 depth: usize,
505}
506
507#[derive(Debug, PartialEq, Eq, Clone, Hash)]
508struct TreeKey {
509 section: Section,
510 path: RepoPath,
511}
512
513#[derive(Debug, PartialEq, Eq, Clone)]
514struct GitTreeDirEntry {
515 key: TreeKey,
516 name: SharedString,
517 depth: usize,
518 // staged_state: ToggleState,
519 expanded: bool,
520}
521
522#[derive(Default)]
523struct TreeNode {
524 name: SharedString,
525 path: Option<RepoPath>,
526 children: BTreeMap<SharedString, TreeNode>,
527 files: Vec<GitStatusEntry>,
528}
529
530#[derive(Debug, PartialEq, Eq, Clone)]
531pub struct GitStatusEntry {
532 pub(crate) repo_path: RepoPath,
533 pub(crate) status: FileStatus,
534 pub(crate) staging: StageStatus,
535}
536
537impl GitStatusEntry {
538 fn display_name(&self, path_style: PathStyle) -> String {
539 self.repo_path
540 .file_name()
541 .map(|name| name.to_owned())
542 .unwrap_or_else(|| self.repo_path.display(path_style).to_string())
543 }
544
545 fn parent_dir(&self, path_style: PathStyle) -> Option<String> {
546 self.repo_path
547 .parent()
548 .map(|parent| parent.display(path_style).to_string())
549 }
550}
551
552struct TruncatedPatch {
553 header: String,
554 hunks: Vec<String>,
555 hunks_to_keep: usize,
556}
557
558impl TruncatedPatch {
559 fn from_unified_diff(patch_str: &str) -> Option<Self> {
560 let lines: Vec<&str> = patch_str.lines().collect();
561 if lines.len() < 2 {
562 return None;
563 }
564 let header = format!("{}\n{}\n", lines[0], lines[1]);
565 let mut hunks = Vec::new();
566 let mut current_hunk = String::new();
567 for line in &lines[2..] {
568 if line.starts_with("@@") {
569 if !current_hunk.is_empty() {
570 hunks.push(current_hunk);
571 }
572 current_hunk = format!("{}\n", line);
573 } else if !current_hunk.is_empty() {
574 current_hunk.push_str(line);
575 current_hunk.push('\n');
576 }
577 }
578 if !current_hunk.is_empty() {
579 hunks.push(current_hunk);
580 }
581 if hunks.is_empty() {
582 return None;
583 }
584 let hunks_to_keep = hunks.len();
585 Some(TruncatedPatch {
586 header,
587 hunks,
588 hunks_to_keep,
589 })
590 }
591 fn calculate_size(&self) -> usize {
592 let mut size = self.header.len();
593 for (i, hunk) in self.hunks.iter().enumerate() {
594 if i < self.hunks_to_keep {
595 size += hunk.len();
596 }
597 }
598 size
599 }
600 fn to_string(&self) -> String {
601 let mut out = self.header.clone();
602 for (i, hunk) in self.hunks.iter().enumerate() {
603 if i < self.hunks_to_keep {
604 out.push_str(hunk);
605 }
606 }
607 let skipped_hunks = self.hunks.len() - self.hunks_to_keep;
608 if skipped_hunks > 0 {
609 out.push_str(&format!("[...skipped {} hunks...]\n", skipped_hunks));
610 }
611 out
612 }
613}
614
615pub struct GitPanel {
616 pub(crate) active_repository: Option<Entity<Repository>>,
617 pub(crate) commit_editor: Entity<Editor>,
618 conflicted_count: usize,
619 conflicted_staged_count: usize,
620 add_coauthors: bool,
621 generate_commit_message_task: Option<Task<Option<()>>>,
622 entries: Vec<GitListEntry>,
623 view_mode: GitPanelViewMode,
624 entries_indices: HashMap<RepoPath, usize>,
625 single_staged_entry: Option<GitStatusEntry>,
626 single_tracked_entry: Option<GitStatusEntry>,
627 focus_handle: FocusHandle,
628 fs: Arc<dyn Fs>,
629 new_count: usize,
630 entry_count: usize,
631 changes_count: usize,
632 new_staged_count: usize,
633 pending_commit: Option<Task<()>>,
634 amend_pending: bool,
635 original_commit_message: Option<String>,
636 signoff_enabled: bool,
637 pending_serialization: Task<()>,
638 pub(crate) project: Entity<Project>,
639 scroll_handle: UniformListScrollHandle,
640 max_width_item_index: Option<usize>,
641 selected_entry: Option<usize>,
642 marked_entries: Vec<usize>,
643 tracked_count: usize,
644 tracked_staged_count: usize,
645 update_visible_entries_task: Task<()>,
646 width: Option<Pixels>,
647 pub(crate) workspace: WeakEntity<Workspace>,
648 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
649 modal_open: bool,
650 show_placeholders: bool,
651 local_committer: Option<GitCommitter>,
652 local_committer_task: Option<Task<()>>,
653 bulk_staging: Option<BulkStaging>,
654 stash_entries: GitStash,
655 diff_stats: HashMap<RepoPath, DiffStat>,
656 diff_stats_task: Task<()>,
657 _settings_subscription: Subscription,
658}
659
660#[derive(Clone, Debug, PartialEq, Eq)]
661struct BulkStaging {
662 repo_id: RepositoryId,
663 anchor: RepoPath,
664}
665
666const MAX_PANEL_EDITOR_LINES: usize = 6;
667
668pub(crate) fn commit_message_editor(
669 commit_message_buffer: Entity<Buffer>,
670 placeholder: Option<SharedString>,
671 project: Entity<Project>,
672 in_panel: bool,
673 window: &mut Window,
674 cx: &mut Context<Editor>,
675) -> Editor {
676 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
677 let max_lines = if in_panel { MAX_PANEL_EDITOR_LINES } else { 18 };
678 let mut commit_editor = Editor::new(
679 EditorMode::AutoHeight {
680 min_lines: max_lines,
681 max_lines: Some(max_lines),
682 },
683 buffer,
684 None,
685 window,
686 cx,
687 );
688 commit_editor.set_collaboration_hub(Box::new(project));
689 commit_editor.set_use_autoclose(false);
690 commit_editor.set_show_gutter(false, cx);
691 commit_editor.set_use_modal_editing(true);
692 commit_editor.set_show_wrap_guides(false, cx);
693 commit_editor.set_show_indent_guides(false, cx);
694 let placeholder = placeholder.unwrap_or("Enter commit message".into());
695 commit_editor.set_placeholder_text(&placeholder, window, cx);
696 commit_editor
697}
698
699impl GitPanel {
700 fn new(
701 workspace: &mut Workspace,
702 window: &mut Window,
703 cx: &mut Context<Workspace>,
704 ) -> Entity<Self> {
705 let project = workspace.project().clone();
706 let app_state = workspace.app_state().clone();
707 let fs = app_state.fs.clone();
708 let git_store = project.read(cx).git_store().clone();
709 let active_repository = project.read(cx).active_repository(cx);
710
711 cx.new(|cx| {
712 let focus_handle = cx.focus_handle();
713 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
714
715 let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
716 let mut was_tree_view = GitPanelSettings::get_global(cx).tree_view;
717 let mut was_diff_stats = GitPanelSettings::get_global(cx).diff_stats;
718 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
719 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
720 let tree_view = GitPanelSettings::get_global(cx).tree_view;
721 let diff_stats = GitPanelSettings::get_global(cx).diff_stats;
722 if tree_view != was_tree_view {
723 this.view_mode = GitPanelViewMode::from_settings(cx);
724 }
725 if sort_by_path != was_sort_by_path || tree_view != was_tree_view {
726 this.bulk_staging.take();
727 this.update_visible_entries(window, cx);
728 }
729 if diff_stats != was_diff_stats {
730 if diff_stats {
731 this.fetch_diff_stats(cx);
732 } else {
733 this.diff_stats.clear();
734 this.diff_stats_task = Task::ready(());
735 cx.notify();
736 }
737 }
738 was_sort_by_path = sort_by_path;
739 was_tree_view = tree_view;
740 was_diff_stats = diff_stats;
741 })
742 .detach();
743
744 // just to let us render a placeholder editor.
745 // Once the active git repo is set, this buffer will be replaced.
746 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
747 let commit_editor = cx.new(|cx| {
748 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
749 });
750
751 commit_editor.update(cx, |editor, cx| {
752 editor.clear(window, cx);
753 });
754
755 let scroll_handle = UniformListScrollHandle::new();
756
757 let mut was_ai_enabled = AgentSettings::get_global(cx).enabled(cx);
758 let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {
759 let is_ai_enabled = AgentSettings::get_global(cx).enabled(cx);
760 if was_ai_enabled != is_ai_enabled {
761 was_ai_enabled = is_ai_enabled;
762 cx.notify();
763 }
764 });
765
766 cx.subscribe_in(
767 &git_store,
768 window,
769 move |this, _git_store, event, window, cx| match event {
770 GitStoreEvent::RepositoryUpdated(
771 _,
772 RepositoryEvent::StatusesChanged | RepositoryEvent::BranchChanged,
773 true,
774 )
775 | GitStoreEvent::RepositoryAdded
776 | GitStoreEvent::RepositoryRemoved(_)
777 | GitStoreEvent::ActiveRepositoryChanged(_) => {
778 this.schedule_update(window, cx);
779 }
780 GitStoreEvent::IndexWriteError(error) => {
781 this.workspace
782 .update(cx, |workspace, cx| {
783 workspace.show_error(error, cx);
784 })
785 .ok();
786 }
787 GitStoreEvent::RepositoryUpdated(_, _, _) => {}
788 GitStoreEvent::JobsUpdated | GitStoreEvent::ConflictsUpdated => {}
789 },
790 )
791 .detach();
792
793 let buffer_store = project.read(cx).buffer_store().clone();
794
795 for buffer in project.read(cx).opened_buffers(cx) {
796 cx.subscribe(&buffer, |this, _buffer, event, cx| {
797 if matches!(event, BufferEvent::Saved) {
798 if GitPanelSettings::get_global(cx).diff_stats {
799 this.fetch_diff_stats(cx);
800 }
801 }
802 })
803 .detach();
804 }
805
806 cx.subscribe(&buffer_store, |_this, _store, event, cx| {
807 if let BufferStoreEvent::BufferAdded(buffer) = event {
808 cx.subscribe(buffer, |this, _buffer, event, cx| {
809 if matches!(event, BufferEvent::Saved) {
810 if GitPanelSettings::get_global(cx).diff_stats {
811 this.fetch_diff_stats(cx);
812 }
813 }
814 })
815 .detach();
816 }
817 })
818 .detach();
819
820 let mut this = Self {
821 active_repository,
822 commit_editor,
823 conflicted_count: 0,
824 conflicted_staged_count: 0,
825 add_coauthors: true,
826 generate_commit_message_task: None,
827 entries: Vec::new(),
828 view_mode: GitPanelViewMode::from_settings(cx),
829 entries_indices: HashMap::default(),
830 focus_handle: cx.focus_handle(),
831 fs,
832 new_count: 0,
833 new_staged_count: 0,
834 changes_count: 0,
835 pending_commit: None,
836 amend_pending: false,
837 original_commit_message: None,
838 signoff_enabled: false,
839 pending_serialization: Task::ready(()),
840 single_staged_entry: None,
841 single_tracked_entry: None,
842 project,
843 scroll_handle,
844 max_width_item_index: None,
845 selected_entry: None,
846 marked_entries: Vec::new(),
847 tracked_count: 0,
848 tracked_staged_count: 0,
849 update_visible_entries_task: Task::ready(()),
850 width: None,
851 show_placeholders: false,
852 local_committer: None,
853 local_committer_task: None,
854 context_menu: None,
855 workspace: workspace.weak_handle(),
856 modal_open: false,
857 entry_count: 0,
858 bulk_staging: None,
859 stash_entries: Default::default(),
860 diff_stats: HashMap::default(),
861 diff_stats_task: Task::ready(()),
862 _settings_subscription,
863 };
864
865 this.schedule_update(window, cx);
866 this
867 })
868 }
869
870 pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
871 self.entries_indices.get(path).copied()
872 }
873
874 pub fn select_entry_by_path(
875 &mut self,
876 path: ProjectPath,
877 window: &mut Window,
878 cx: &mut Context<Self>,
879 ) {
880 let Some(git_repo) = self.active_repository.as_ref() else {
881 return;
882 };
883
884 let (repo_path, section) = {
885 let repo = git_repo.read(cx);
886 let Some(repo_path) = repo.project_path_to_repo_path(&path, cx) else {
887 return;
888 };
889
890 let section = repo
891 .status_for_path(&repo_path)
892 .map(|status| status.status)
893 .map(|status| {
894 if repo.had_conflict_on_last_merge_head_change(&repo_path) {
895 Section::Conflict
896 } else if status.is_created() {
897 Section::New
898 } else {
899 Section::Tracked
900 }
901 });
902
903 (repo_path, section)
904 };
905
906 let mut needs_rebuild = false;
907 if let (Some(section), Some(tree_state)) = (section, self.view_mode.tree_state_mut()) {
908 let mut current_dir = repo_path.parent();
909 while let Some(dir) = current_dir {
910 let key = TreeKey {
911 section,
912 path: RepoPath::from_rel_path(dir),
913 };
914
915 if tree_state.expanded_dirs.get(&key) == Some(&false) {
916 tree_state.expanded_dirs.insert(key, true);
917 needs_rebuild = true;
918 }
919
920 current_dir = dir.parent();
921 }
922 }
923
924 if needs_rebuild {
925 self.update_visible_entries(window, cx);
926 }
927
928 let Some(ix) = self.entry_by_path(&repo_path) else {
929 return;
930 };
931
932 self.selected_entry = Some(ix);
933 self.scroll_to_selected_entry(cx);
934 }
935
936 fn serialization_key(workspace: &Workspace) -> Option<String> {
937 workspace
938 .database_id()
939 .map(|id| i64::from(id).to_string())
940 .or(workspace.session_id())
941 .map(|id| format!("{}-{:?}", GIT_PANEL_KEY, id))
942 }
943
944 fn serialize(&mut self, cx: &mut Context<Self>) {
945 let width = self.width;
946 let amend_pending = self.amend_pending;
947 let signoff_enabled = self.signoff_enabled;
948
949 self.pending_serialization = cx.spawn(async move |git_panel, cx| {
950 cx.background_executor()
951 .timer(SERIALIZATION_THROTTLE_TIME)
952 .await;
953 let Some(serialization_key) = git_panel
954 .update(cx, |git_panel, cx| {
955 git_panel
956 .workspace
957 .read_with(cx, |workspace, _| Self::serialization_key(workspace))
958 .ok()
959 .flatten()
960 })
961 .ok()
962 .flatten()
963 else {
964 return;
965 };
966 cx.background_spawn(
967 async move {
968 KEY_VALUE_STORE
969 .write_kvp(
970 serialization_key,
971 serde_json::to_string(&SerializedGitPanel {
972 width,
973 amend_pending,
974 signoff_enabled,
975 })?,
976 )
977 .await?;
978 anyhow::Ok(())
979 }
980 .log_err(),
981 )
982 .await;
983 });
984 }
985
986 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
987 self.modal_open = open;
988 cx.notify();
989 }
990
991 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
992 let mut dispatch_context = KeyContext::new_with_defaults();
993 dispatch_context.add("GitPanel");
994
995 if window
996 .focused(cx)
997 .is_some_and(|focused| self.focus_handle == focused)
998 {
999 dispatch_context.add("menu");
1000 dispatch_context.add("ChangesList");
1001 }
1002
1003 if self.commit_editor.read(cx).is_focused(window) {
1004 dispatch_context.add("CommitEditor");
1005 }
1006
1007 dispatch_context
1008 }
1009
1010 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
1011 cx.emit(PanelEvent::Close);
1012 }
1013
1014 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1015 if !self.focus_handle.contains_focused(window, cx) {
1016 cx.emit(Event::Focus);
1017 }
1018 }
1019
1020 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
1021 let Some(selected_entry) = self.selected_entry else {
1022 cx.notify();
1023 return;
1024 };
1025
1026 let visible_index = match &self.view_mode {
1027 GitPanelViewMode::Flat => Some(selected_entry),
1028 GitPanelViewMode::Tree(state) => state
1029 .logical_indices
1030 .iter()
1031 .position(|&ix| ix == selected_entry),
1032 };
1033
1034 if let Some(visible_index) = visible_index {
1035 self.scroll_handle
1036 .scroll_to_item(visible_index, ScrollStrategy::Center);
1037 }
1038
1039 cx.notify();
1040 }
1041
1042 fn expand_selected_entry(
1043 &mut self,
1044 _: &ExpandSelectedEntry,
1045 window: &mut Window,
1046 cx: &mut Context<Self>,
1047 ) {
1048 let Some(entry) = self.get_selected_entry().cloned() else {
1049 return;
1050 };
1051
1052 if let GitListEntry::Directory(dir_entry) = entry {
1053 if dir_entry.expanded {
1054 self.select_next(&menu::SelectNext, window, cx);
1055 } else {
1056 self.toggle_directory(&dir_entry.key, window, cx);
1057 }
1058 } else {
1059 self.select_next(&menu::SelectNext, window, cx);
1060 }
1061 }
1062
1063 fn collapse_selected_entry(
1064 &mut self,
1065 _: &CollapseSelectedEntry,
1066 window: &mut Window,
1067 cx: &mut Context<Self>,
1068 ) {
1069 let Some(entry) = self.get_selected_entry().cloned() else {
1070 return;
1071 };
1072
1073 if let GitListEntry::Directory(dir_entry) = entry {
1074 if dir_entry.expanded {
1075 self.toggle_directory(&dir_entry.key, window, cx);
1076 } else {
1077 self.select_previous(&menu::SelectPrevious, window, cx);
1078 }
1079 } else {
1080 self.select_previous(&menu::SelectPrevious, window, cx);
1081 }
1082 }
1083
1084 fn select_first(
1085 &mut self,
1086 _: &menu::SelectFirst,
1087 _window: &mut Window,
1088 cx: &mut Context<Self>,
1089 ) {
1090 let first_entry = match &self.view_mode {
1091 GitPanelViewMode::Flat => self
1092 .entries
1093 .iter()
1094 .position(|entry| entry.status_entry().is_some()),
1095 GitPanelViewMode::Tree(state) => {
1096 let index = self.entries.iter().position(|entry| {
1097 entry.status_entry().is_some() || entry.directory_entry().is_some()
1098 });
1099
1100 index.map(|index| state.logical_indices[index])
1101 }
1102 };
1103
1104 if let Some(first_entry) = first_entry {
1105 self.selected_entry = Some(first_entry);
1106 self.scroll_to_selected_entry(cx);
1107 }
1108 }
1109
1110 fn select_previous(
1111 &mut self,
1112 _: &menu::SelectPrevious,
1113 _window: &mut Window,
1114 cx: &mut Context<Self>,
1115 ) {
1116 let item_count = self.entries.len();
1117 if item_count == 0 {
1118 return;
1119 }
1120
1121 let Some(selected_entry) = self.selected_entry else {
1122 return;
1123 };
1124
1125 let new_index = match &self.view_mode {
1126 GitPanelViewMode::Flat => selected_entry.saturating_sub(1),
1127 GitPanelViewMode::Tree(state) => {
1128 let Some(current_logical_index) = state
1129 .logical_indices
1130 .iter()
1131 .position(|&i| i == selected_entry)
1132 else {
1133 return;
1134 };
1135
1136 state.logical_indices[current_logical_index.saturating_sub(1)]
1137 }
1138 };
1139
1140 if selected_entry == 0 && new_index == 0 {
1141 return;
1142 }
1143
1144 if matches!(
1145 self.entries.get(new_index.saturating_sub(1)),
1146 Some(GitListEntry::Header(..))
1147 ) && new_index == 0
1148 {
1149 return;
1150 }
1151
1152 if matches!(self.entries.get(new_index), Some(GitListEntry::Header(..))) {
1153 self.selected_entry = Some(new_index.saturating_sub(1));
1154 } else {
1155 self.selected_entry = Some(new_index);
1156 }
1157
1158 self.scroll_to_selected_entry(cx);
1159 }
1160
1161 fn select_next(&mut self, _: &menu::SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
1162 let item_count = self.entries.len();
1163 if item_count == 0 {
1164 return;
1165 }
1166
1167 let Some(selected_entry) = self.selected_entry else {
1168 return;
1169 };
1170
1171 let new_index = match &self.view_mode {
1172 GitPanelViewMode::Flat => {
1173 if selected_entry >= item_count.saturating_sub(1) {
1174 return;
1175 }
1176
1177 selected_entry.saturating_add(1)
1178 }
1179 GitPanelViewMode::Tree(state) => {
1180 let Some(current_logical_index) = state
1181 .logical_indices
1182 .iter()
1183 .position(|&i| i == selected_entry)
1184 else {
1185 return;
1186 };
1187
1188 let Some(new_index) = state
1189 .logical_indices
1190 .get(current_logical_index.saturating_add(1))
1191 .copied()
1192 else {
1193 return;
1194 };
1195
1196 new_index
1197 }
1198 };
1199
1200 if matches!(self.entries.get(new_index), Some(GitListEntry::Header(..))) {
1201 self.selected_entry = Some(new_index.saturating_add(1));
1202 } else {
1203 self.selected_entry = Some(new_index);
1204 }
1205
1206 self.scroll_to_selected_entry(cx);
1207 }
1208
1209 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
1210 if self.entries.last().is_some() {
1211 self.selected_entry = Some(self.entries.len() - 1);
1212 self.scroll_to_selected_entry(cx);
1213 }
1214 }
1215
1216 /// Show diff view at selected entry, only if the diff view is open
1217 fn move_diff_to_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1218 maybe!({
1219 let workspace = self.workspace.upgrade()?;
1220
1221 if let Some(project_diff) = workspace.read(cx).item_of_type::<ProjectDiff>(cx) {
1222 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
1223
1224 project_diff.update(cx, |project_diff, cx| {
1225 project_diff.move_to_entry(entry.clone(), window, cx);
1226 });
1227 }
1228
1229 Some(())
1230 });
1231 }
1232
1233 fn first_entry(&mut self, _: &FirstEntry, window: &mut Window, cx: &mut Context<Self>) {
1234 self.select_first(&menu::SelectFirst, window, cx);
1235 self.move_diff_to_entry(window, cx);
1236 }
1237
1238 fn last_entry(&mut self, _: &LastEntry, window: &mut Window, cx: &mut Context<Self>) {
1239 self.select_last(&menu::SelectLast, window, cx);
1240 self.move_diff_to_entry(window, cx);
1241 }
1242
1243 fn next_entry(&mut self, _: &NextEntry, window: &mut Window, cx: &mut Context<Self>) {
1244 self.select_next(&menu::SelectNext, window, cx);
1245 self.move_diff_to_entry(window, cx);
1246 }
1247
1248 fn previous_entry(&mut self, _: &PreviousEntry, window: &mut Window, cx: &mut Context<Self>) {
1249 self.select_previous(&menu::SelectPrevious, window, cx);
1250 self.move_diff_to_entry(window, cx);
1251 }
1252
1253 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
1254 self.commit_editor.update(cx, |editor, cx| {
1255 window.focus(&editor.focus_handle(cx), cx);
1256 });
1257 cx.notify();
1258 }
1259
1260 fn select_first_entry_if_none(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1261 let have_entries = self
1262 .active_repository
1263 .as_ref()
1264 .is_some_and(|active_repository| active_repository.read(cx).status_summary().count > 0);
1265 if have_entries && self.selected_entry.is_none() {
1266 self.select_first(&menu::SelectFirst, window, cx);
1267 }
1268 }
1269
1270 fn focus_changes_list(
1271 &mut self,
1272 _: &FocusChanges,
1273 window: &mut Window,
1274 cx: &mut Context<Self>,
1275 ) {
1276 self.focus_handle.focus(window, cx);
1277 self.select_first_entry_if_none(window, cx);
1278 }
1279
1280 fn get_selected_entry(&self) -> Option<&GitListEntry> {
1281 self.selected_entry.and_then(|i| self.entries.get(i))
1282 }
1283
1284 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
1285 maybe!({
1286 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
1287 let workspace = self.workspace.upgrade()?;
1288 let git_repo = self.active_repository.as_ref()?;
1289
1290 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx)
1291 && let Some(project_path) = project_diff.read(cx).active_path(cx)
1292 && Some(&entry.repo_path)
1293 == git_repo
1294 .read(cx)
1295 .project_path_to_repo_path(&project_path, cx)
1296 .as_ref()
1297 {
1298 project_diff.focus_handle(cx).focus(window, cx);
1299 project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
1300 return None;
1301 };
1302
1303 self.workspace
1304 .update(cx, |workspace, cx| {
1305 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
1306 })
1307 .ok();
1308 self.focus_handle.focus(window, cx);
1309
1310 Some(())
1311 });
1312 }
1313
1314 fn file_history(&mut self, _: &git::FileHistory, window: &mut Window, cx: &mut Context<Self>) {
1315 maybe!({
1316 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
1317 let active_repo = self.active_repository.as_ref()?;
1318 let repo_path = entry.repo_path.clone();
1319 let git_store = self.project.read(cx).git_store();
1320
1321 FileHistoryView::open(
1322 repo_path,
1323 git_store.downgrade(),
1324 active_repo.downgrade(),
1325 self.workspace.clone(),
1326 window,
1327 cx,
1328 );
1329
1330 Some(())
1331 });
1332 }
1333
1334 fn open_file(
1335 &mut self,
1336 _: &menu::SecondaryConfirm,
1337 window: &mut Window,
1338 cx: &mut Context<Self>,
1339 ) {
1340 maybe!({
1341 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
1342 let active_repo = self.active_repository.as_ref()?;
1343 let path = active_repo
1344 .read(cx)
1345 .repo_path_to_project_path(&entry.repo_path, cx)?;
1346 if entry.status.is_deleted() {
1347 return None;
1348 }
1349
1350 let open_task = self
1351 .workspace
1352 .update(cx, |workspace, cx| {
1353 workspace.open_path_preview(path, None, false, false, true, window, cx)
1354 })
1355 .ok()?;
1356
1357 let workspace = self.workspace.clone();
1358 cx.spawn_in(window, async move |_, mut cx| {
1359 let item = open_task
1360 .await
1361 .notify_workspace_async_err(workspace, &mut cx)
1362 .ok_or_else(|| anyhow::anyhow!("Failed to open file"))?;
1363 if let Some(active_editor) = item.downcast::<Editor>() {
1364 if let Some(diff_task) =
1365 active_editor.update(cx, |editor, _cx| editor.wait_for_diff_to_load())
1366 {
1367 diff_task.await;
1368 }
1369
1370 cx.update(|window, cx| {
1371 active_editor.update(cx, |editor, cx| {
1372 editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
1373
1374 let snapshot = editor.snapshot(window, cx);
1375 editor.go_to_hunk_before_or_after_position(
1376 &snapshot,
1377 language::Point::new(0, 0),
1378 Direction::Next,
1379 window,
1380 cx,
1381 );
1382 })
1383 })
1384 .log_err();
1385 }
1386
1387 anyhow::Ok(())
1388 })
1389 .detach();
1390
1391 Some(())
1392 });
1393 }
1394
1395 fn revert_selected(
1396 &mut self,
1397 action: &git::RestoreFile,
1398 window: &mut Window,
1399 cx: &mut Context<Self>,
1400 ) {
1401 let path_style = self.project.read(cx).path_style(cx);
1402 maybe!({
1403 let list_entry = self.entries.get(self.selected_entry?)?.clone();
1404 let entry = list_entry.status_entry()?.to_owned();
1405 let skip_prompt = action.skip_prompt || entry.status.is_created();
1406
1407 let prompt = if skip_prompt {
1408 Task::ready(Ok(0))
1409 } else {
1410 let prompt = window.prompt(
1411 PromptLevel::Warning,
1412 &format!(
1413 "Are you sure you want to discard changes to {}?",
1414 entry
1415 .repo_path
1416 .file_name()
1417 .unwrap_or(entry.repo_path.display(path_style).as_ref()),
1418 ),
1419 None,
1420 &["Discard Changes", "Cancel"],
1421 cx,
1422 );
1423 cx.background_spawn(prompt)
1424 };
1425
1426 let this = cx.weak_entity();
1427 window
1428 .spawn(cx, async move |cx| {
1429 if prompt.await? != 0 {
1430 return anyhow::Ok(());
1431 }
1432
1433 this.update_in(cx, |this, window, cx| {
1434 this.revert_entry(&entry, window, cx);
1435 })?;
1436
1437 Ok(())
1438 })
1439 .detach();
1440 Some(())
1441 });
1442 }
1443
1444 fn add_to_gitignore(
1445 &mut self,
1446 _: &git::AddToGitignore,
1447 _window: &mut Window,
1448 cx: &mut Context<Self>,
1449 ) {
1450 maybe!({
1451 let list_entry = self.entries.get(self.selected_entry?)?.clone();
1452 let entry = list_entry.status_entry()?.to_owned();
1453
1454 if !entry.status.is_created() {
1455 return Some(());
1456 }
1457
1458 let project = self.project.downgrade();
1459 let repo_path = entry.repo_path;
1460 let active_repository = self.active_repository.as_ref()?.downgrade();
1461
1462 cx.spawn(async move |_, cx| {
1463 let file_path_str = repo_path.as_ref().display(PathStyle::Posix);
1464
1465 let repo_root = active_repository.read_with(cx, |repository, _| {
1466 repository.snapshot().work_directory_abs_path
1467 })?;
1468
1469 let gitignore_abs_path = repo_root.join(".gitignore");
1470
1471 let buffer: Entity<Buffer> = project
1472 .update(cx, |project, cx| {
1473 project.open_local_buffer(gitignore_abs_path, cx)
1474 })?
1475 .await?;
1476
1477 let mut should_save = false;
1478 buffer.update(cx, |buffer, cx| {
1479 let existing_content = buffer.text();
1480
1481 if existing_content
1482 .lines()
1483 .any(|line: &str| line.trim() == file_path_str)
1484 {
1485 return;
1486 }
1487
1488 let insert_position = existing_content.len();
1489 let new_entry = if existing_content.is_empty() {
1490 format!("{}\n", file_path_str)
1491 } else if existing_content.ends_with('\n') {
1492 format!("{}\n", file_path_str)
1493 } else {
1494 format!("\n{}\n", file_path_str)
1495 };
1496
1497 buffer.edit([(insert_position..insert_position, new_entry)], None, cx);
1498 should_save = true;
1499 });
1500
1501 if should_save {
1502 project
1503 .update(cx, |project, cx| project.save_buffer(buffer, cx))?
1504 .await?;
1505 }
1506
1507 anyhow::Ok(())
1508 })
1509 .detach_and_log_err(cx);
1510
1511 Some(())
1512 });
1513 }
1514
1515 fn revert_entry(
1516 &mut self,
1517 entry: &GitStatusEntry,
1518 window: &mut Window,
1519 cx: &mut Context<Self>,
1520 ) {
1521 maybe!({
1522 let active_repo = self.active_repository.clone()?;
1523 let path = active_repo
1524 .read(cx)
1525 .repo_path_to_project_path(&entry.repo_path, cx)?;
1526 let workspace = self.workspace.clone();
1527
1528 if entry.status.staging().has_staged() {
1529 self.change_file_stage(false, vec![entry.clone()], cx);
1530 }
1531 let filename = path.path.file_name()?.to_string();
1532
1533 if !entry.status.is_created() {
1534 self.perform_checkout(vec![entry.clone()], window, cx);
1535 } else {
1536 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
1537 cx.spawn_in(window, async move |_, cx| {
1538 match prompt.await? {
1539 TrashCancel::Trash => {}
1540 TrashCancel::Cancel => return Ok(()),
1541 }
1542 let task = workspace.update(cx, |workspace, cx| {
1543 workspace
1544 .project()
1545 .update(cx, |project, cx| project.delete_file(path, true, cx))
1546 })?;
1547 if let Some(task) = task {
1548 task.await?;
1549 }
1550 Ok(())
1551 })
1552 .detach_and_prompt_err(
1553 "Failed to trash file",
1554 window,
1555 cx,
1556 |e, _, _| Some(format!("{e}")),
1557 );
1558 }
1559 Some(())
1560 });
1561 }
1562
1563 fn perform_checkout(
1564 &mut self,
1565 entries: Vec<GitStatusEntry>,
1566 window: &mut Window,
1567 cx: &mut Context<Self>,
1568 ) {
1569 let workspace = self.workspace.clone();
1570 let Some(active_repository) = self.active_repository.clone() else {
1571 return;
1572 };
1573
1574 let task = cx.spawn_in(window, async move |this, cx| {
1575 let tasks: Vec<_> = workspace.update(cx, |workspace, cx| {
1576 workspace.project().update(cx, |project, cx| {
1577 entries
1578 .iter()
1579 .filter_map(|entry| {
1580 let path = active_repository
1581 .read(cx)
1582 .repo_path_to_project_path(&entry.repo_path, cx)?;
1583 Some(project.open_buffer(path, cx))
1584 })
1585 .collect()
1586 })
1587 })?;
1588
1589 let buffers = futures::future::join_all(tasks).await;
1590
1591 this.update_in(cx, |this, window, cx| {
1592 let task = active_repository.update(cx, |repo, cx| {
1593 repo.checkout_files(
1594 "HEAD",
1595 entries
1596 .into_iter()
1597 .map(|entries| entries.repo_path)
1598 .collect(),
1599 cx,
1600 )
1601 });
1602 this.update_visible_entries(window, cx);
1603 cx.notify();
1604 task
1605 })?
1606 .await?;
1607
1608 let tasks: Vec<_> = cx.update(|_, cx| {
1609 buffers
1610 .iter()
1611 .filter_map(|buffer| {
1612 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
1613 buffer.is_dirty().then(|| buffer.reload(cx))
1614 })
1615 })
1616 .collect()
1617 })?;
1618
1619 futures::future::join_all(tasks).await;
1620
1621 Ok(())
1622 });
1623
1624 cx.spawn_in(window, async move |this, cx| {
1625 let result = task.await;
1626
1627 this.update_in(cx, |this, window, cx| {
1628 if let Err(err) = result {
1629 this.update_visible_entries(window, cx);
1630 this.show_error_toast("checkout", err, cx);
1631 }
1632 })
1633 .ok();
1634 })
1635 .detach();
1636 }
1637
1638 fn restore_tracked_files(
1639 &mut self,
1640 _: &RestoreTrackedFiles,
1641 window: &mut Window,
1642 cx: &mut Context<Self>,
1643 ) {
1644 let entries = self
1645 .entries
1646 .iter()
1647 .filter_map(|entry| entry.status_entry().cloned())
1648 .filter(|status_entry| !status_entry.status.is_created())
1649 .collect::<Vec<_>>();
1650
1651 match entries.len() {
1652 0 => return,
1653 1 => return self.revert_entry(&entries[0], window, cx),
1654 _ => {}
1655 }
1656 let mut details = entries
1657 .iter()
1658 .filter_map(|entry| entry.repo_path.as_ref().file_name())
1659 .map(|filename| filename.to_string())
1660 .take(5)
1661 .join("\n");
1662 if entries.len() > 5 {
1663 details.push_str(&format!("\nand {} more…", entries.len() - 5))
1664 }
1665
1666 #[derive(strum::EnumIter, strum::VariantNames)]
1667 #[strum(serialize_all = "title_case")]
1668 enum RestoreCancel {
1669 RestoreTrackedFiles,
1670 Cancel,
1671 }
1672 let prompt = prompt(
1673 "Discard changes to these files?",
1674 Some(&details),
1675 window,
1676 cx,
1677 );
1678 cx.spawn_in(window, async move |this, cx| {
1679 if let Ok(RestoreCancel::RestoreTrackedFiles) = prompt.await {
1680 this.update_in(cx, |this, window, cx| {
1681 this.perform_checkout(entries, window, cx);
1682 })
1683 .ok();
1684 }
1685 })
1686 .detach();
1687 }
1688
1689 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1690 let workspace = self.workspace.clone();
1691 let Some(active_repo) = self.active_repository.clone() else {
1692 return;
1693 };
1694 let to_delete = self
1695 .entries
1696 .iter()
1697 .filter_map(|entry| entry.status_entry())
1698 .filter(|status_entry| status_entry.status.is_created())
1699 .cloned()
1700 .collect::<Vec<_>>();
1701
1702 match to_delete.len() {
1703 0 => return,
1704 1 => return self.revert_entry(&to_delete[0], window, cx),
1705 _ => {}
1706 };
1707
1708 let mut details = to_delete
1709 .iter()
1710 .map(|entry| {
1711 entry
1712 .repo_path
1713 .as_ref()
1714 .file_name()
1715 .map(|f| f.to_string())
1716 .unwrap_or_default()
1717 })
1718 .take(5)
1719 .join("\n");
1720
1721 if to_delete.len() > 5 {
1722 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1723 }
1724
1725 let prompt = prompt("Trash these files?", Some(&details), window, cx);
1726 cx.spawn_in(window, async move |this, cx| {
1727 match prompt.await? {
1728 TrashCancel::Trash => {}
1729 TrashCancel::Cancel => return Ok(()),
1730 }
1731 let tasks = workspace.update(cx, |workspace, cx| {
1732 to_delete
1733 .iter()
1734 .filter_map(|entry| {
1735 workspace.project().update(cx, |project, cx| {
1736 let project_path = active_repo
1737 .read(cx)
1738 .repo_path_to_project_path(&entry.repo_path, cx)?;
1739 project.delete_file(project_path, true, cx)
1740 })
1741 })
1742 .collect::<Vec<_>>()
1743 })?;
1744 let to_unstage = to_delete
1745 .into_iter()
1746 .filter(|entry| !entry.status.staging().is_fully_unstaged())
1747 .collect();
1748 this.update(cx, |this, cx| this.change_file_stage(false, to_unstage, cx))?;
1749 for task in tasks {
1750 task.await?;
1751 }
1752 Ok(())
1753 })
1754 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1755 Some(format!("{e}"))
1756 });
1757 }
1758
1759 fn change_all_files_stage(&mut self, stage: bool, cx: &mut Context<Self>) {
1760 let Some(active_repository) = self.active_repository.clone() else {
1761 return;
1762 };
1763 cx.spawn({
1764 async move |this, cx| {
1765 let result = this
1766 .update(cx, |this, cx| {
1767 let task = active_repository.update(cx, |repo, cx| {
1768 if stage {
1769 repo.stage_all(cx)
1770 } else {
1771 repo.unstage_all(cx)
1772 }
1773 });
1774 this.update_counts(active_repository.read(cx));
1775 cx.notify();
1776 task
1777 })?
1778 .await;
1779
1780 this.update(cx, |this, cx| {
1781 if let Err(err) = result {
1782 this.show_error_toast(if stage { "add" } else { "reset" }, err, cx);
1783 }
1784 cx.notify()
1785 })
1786 }
1787 })
1788 .detach();
1789 }
1790
1791 fn stage_status_for_entry(entry: &GitStatusEntry, repo: &Repository) -> StageStatus {
1792 // Checking for current staged/unstaged file status is a chained operation:
1793 // 1. first, we check for any pending operation recorded in repository
1794 // 2. if there are no pending ops either running or finished, we then ask the repository
1795 // for the most up-to-date file status read from disk - we do this since `entry` arg to this function `render_entry`
1796 // is likely to be staled, and may lead to weird artifacts in the form of subsecond auto-uncheck/check on
1797 // the checkbox's state (or flickering) which is undesirable.
1798 // 3. finally, if there is no info about this `entry` in the repo, we fall back to whatever status is encoded
1799 // in `entry` arg.
1800 repo.pending_ops_for_path(&entry.repo_path)
1801 .map(|ops| {
1802 if ops.staging() || ops.staged() {
1803 StageStatus::Staged
1804 } else {
1805 StageStatus::Unstaged
1806 }
1807 })
1808 .or_else(|| {
1809 repo.status_for_path(&entry.repo_path)
1810 .map(|status| status.status.staging())
1811 })
1812 .unwrap_or(entry.staging)
1813 }
1814
1815 fn stage_status_for_directory(
1816 &self,
1817 entry: &GitTreeDirEntry,
1818 repo: &Repository,
1819 ) -> StageStatus {
1820 let GitPanelViewMode::Tree(tree_state) = &self.view_mode else {
1821 util::debug_panic!("We should never render a directory entry while in flat view mode");
1822 return StageStatus::Unstaged;
1823 };
1824
1825 let Some(descendants) = tree_state.directory_descendants.get(&entry.key) else {
1826 return StageStatus::Unstaged;
1827 };
1828
1829 let show_placeholders = self.show_placeholders && !self.has_staged_changes();
1830 let mut fully_staged_count = 0usize;
1831 let mut any_staged_or_partially_staged = false;
1832
1833 for descendant in descendants {
1834 if show_placeholders && !descendant.status.is_created() {
1835 fully_staged_count += 1;
1836 any_staged_or_partially_staged = true;
1837 } else {
1838 match GitPanel::stage_status_for_entry(descendant, repo) {
1839 StageStatus::Staged => {
1840 fully_staged_count += 1;
1841 any_staged_or_partially_staged = true;
1842 }
1843 StageStatus::PartiallyStaged => {
1844 any_staged_or_partially_staged = true;
1845 }
1846 StageStatus::Unstaged => {}
1847 }
1848 }
1849 }
1850
1851 if descendants.is_empty() {
1852 StageStatus::Unstaged
1853 } else if fully_staged_count == descendants.len() {
1854 StageStatus::Staged
1855 } else if any_staged_or_partially_staged {
1856 StageStatus::PartiallyStaged
1857 } else {
1858 StageStatus::Unstaged
1859 }
1860 }
1861
1862 pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1863 self.change_all_files_stage(true, cx);
1864 }
1865
1866 pub fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1867 self.change_all_files_stage(false, cx);
1868 }
1869
1870 fn toggle_staged_for_entry(
1871 &mut self,
1872 entry: &GitListEntry,
1873 _window: &mut Window,
1874 cx: &mut Context<Self>,
1875 ) {
1876 let Some(active_repository) = self.active_repository.clone() else {
1877 return;
1878 };
1879 let mut set_anchor: Option<RepoPath> = None;
1880 let mut clear_anchor = None;
1881
1882 let (stage, repo_paths) = {
1883 let repo = active_repository.read(cx);
1884 match entry {
1885 GitListEntry::Status(status_entry) => {
1886 let repo_paths = vec![status_entry.clone()];
1887 let stage = match GitPanel::stage_status_for_entry(status_entry, &repo) {
1888 StageStatus::Staged => {
1889 if let Some(op) = self.bulk_staging.clone()
1890 && op.anchor == status_entry.repo_path
1891 {
1892 clear_anchor = Some(op.anchor);
1893 }
1894 false
1895 }
1896 StageStatus::Unstaged | StageStatus::PartiallyStaged => {
1897 set_anchor = Some(status_entry.repo_path.clone());
1898 true
1899 }
1900 };
1901 (stage, repo_paths)
1902 }
1903 GitListEntry::TreeStatus(status_entry) => {
1904 let repo_paths = vec![status_entry.entry.clone()];
1905 let stage = match GitPanel::stage_status_for_entry(&status_entry.entry, &repo) {
1906 StageStatus::Staged => {
1907 if let Some(op) = self.bulk_staging.clone()
1908 && op.anchor == status_entry.entry.repo_path
1909 {
1910 clear_anchor = Some(op.anchor);
1911 }
1912 false
1913 }
1914 StageStatus::Unstaged | StageStatus::PartiallyStaged => {
1915 set_anchor = Some(status_entry.entry.repo_path.clone());
1916 true
1917 }
1918 };
1919 (stage, repo_paths)
1920 }
1921 GitListEntry::Header(section) => {
1922 let goal_staged_state = !self.header_state(section.header).selected();
1923 let entries = self
1924 .entries
1925 .iter()
1926 .filter_map(|entry| entry.status_entry())
1927 .filter(|status_entry| {
1928 section.contains(status_entry, &repo)
1929 && GitPanel::stage_status_for_entry(status_entry, &repo).as_bool()
1930 != Some(goal_staged_state)
1931 })
1932 .cloned()
1933 .collect::<Vec<_>>();
1934
1935 (goal_staged_state, entries)
1936 }
1937 GitListEntry::Directory(entry) => {
1938 let goal_staged_state = match self.stage_status_for_directory(entry, repo) {
1939 StageStatus::Staged => StageStatus::Unstaged,
1940 StageStatus::Unstaged | StageStatus::PartiallyStaged => StageStatus::Staged,
1941 };
1942 let goal_stage = goal_staged_state == StageStatus::Staged;
1943
1944 let entries = self
1945 .view_mode
1946 .tree_state()
1947 .and_then(|state| state.directory_descendants.get(&entry.key))
1948 .cloned()
1949 .unwrap_or_default()
1950 .into_iter()
1951 .filter(|status_entry| {
1952 GitPanel::stage_status_for_entry(status_entry, &repo)
1953 != goal_staged_state
1954 })
1955 .collect::<Vec<_>>();
1956 (goal_stage, entries)
1957 }
1958 }
1959 };
1960 if let Some(anchor) = clear_anchor {
1961 if let Some(op) = self.bulk_staging.clone()
1962 && op.anchor == anchor
1963 {
1964 self.bulk_staging = None;
1965 }
1966 }
1967 if let Some(anchor) = set_anchor {
1968 self.set_bulk_staging_anchor(anchor, cx);
1969 }
1970
1971 self.change_file_stage(stage, repo_paths, cx);
1972 }
1973
1974 fn change_file_stage(
1975 &mut self,
1976 stage: bool,
1977 entries: Vec<GitStatusEntry>,
1978 cx: &mut Context<Self>,
1979 ) {
1980 let Some(active_repository) = self.active_repository.clone() else {
1981 return;
1982 };
1983 cx.spawn({
1984 async move |this, cx| {
1985 let result = this
1986 .update(cx, |this, cx| {
1987 let task = active_repository.update(cx, |repo, cx| {
1988 let repo_paths = entries
1989 .iter()
1990 .map(|entry| entry.repo_path.clone())
1991 .collect();
1992 if stage {
1993 repo.stage_entries(repo_paths, cx)
1994 } else {
1995 repo.unstage_entries(repo_paths, cx)
1996 }
1997 });
1998 this.update_counts(active_repository.read(cx));
1999 cx.notify();
2000 task
2001 })?
2002 .await;
2003
2004 this.update(cx, |this, cx| {
2005 if let Err(err) = result {
2006 this.show_error_toast(if stage { "add" } else { "reset" }, err, cx);
2007 }
2008 cx.notify();
2009 })
2010 }
2011 })
2012 .detach();
2013 }
2014
2015 pub fn total_staged_count(&self) -> usize {
2016 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
2017 }
2018
2019 pub fn stash_pop(&mut self, _: &StashPop, _window: &mut Window, cx: &mut Context<Self>) {
2020 let Some(active_repository) = self.active_repository.clone() else {
2021 return;
2022 };
2023
2024 cx.spawn({
2025 async move |this, cx| {
2026 let stash_task = active_repository
2027 .update(cx, |repo, cx| repo.stash_pop(None, cx))
2028 .await;
2029 this.update(cx, |this, cx| {
2030 stash_task
2031 .map_err(|e| {
2032 this.show_error_toast("stash pop", e, cx);
2033 })
2034 .ok();
2035 cx.notify();
2036 })
2037 }
2038 })
2039 .detach();
2040 }
2041
2042 pub fn stash_apply(&mut self, _: &StashApply, _window: &mut Window, cx: &mut Context<Self>) {
2043 let Some(active_repository) = self.active_repository.clone() else {
2044 return;
2045 };
2046
2047 cx.spawn({
2048 async move |this, cx| {
2049 let stash_task = active_repository
2050 .update(cx, |repo, cx| repo.stash_apply(None, cx))
2051 .await;
2052 this.update(cx, |this, cx| {
2053 stash_task
2054 .map_err(|e| {
2055 this.show_error_toast("stash apply", e, cx);
2056 })
2057 .ok();
2058 cx.notify();
2059 })
2060 }
2061 })
2062 .detach();
2063 }
2064
2065 pub fn stash_all(&mut self, _: &StashAll, _window: &mut Window, cx: &mut Context<Self>) {
2066 let Some(active_repository) = self.active_repository.clone() else {
2067 return;
2068 };
2069
2070 cx.spawn({
2071 async move |this, cx| {
2072 let stash_task = active_repository
2073 .update(cx, |repo, cx| repo.stash_all(cx))
2074 .await;
2075 this.update(cx, |this, cx| {
2076 stash_task
2077 .map_err(|e| {
2078 this.show_error_toast("stash", e, cx);
2079 })
2080 .ok();
2081 cx.notify();
2082 })
2083 }
2084 })
2085 .detach();
2086 }
2087
2088 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
2089 self.commit_editor
2090 .read(cx)
2091 .buffer()
2092 .read(cx)
2093 .as_singleton()
2094 .unwrap()
2095 }
2096
2097 fn toggle_staged_for_selected(
2098 &mut self,
2099 _: &git::ToggleStaged,
2100 window: &mut Window,
2101 cx: &mut Context<Self>,
2102 ) {
2103 if let Some(selected_entry) = self.get_selected_entry().cloned() {
2104 self.toggle_staged_for_entry(&selected_entry, window, cx);
2105 }
2106 }
2107
2108 fn stage_range(&mut self, _: &git::StageRange, _window: &mut Window, cx: &mut Context<Self>) {
2109 let Some(index) = self.selected_entry else {
2110 return;
2111 };
2112 self.stage_bulk(index, cx);
2113 }
2114
2115 fn stage_selected(&mut self, _: &git::StageFile, _window: &mut Window, cx: &mut Context<Self>) {
2116 let Some(selected_entry) = self.get_selected_entry() else {
2117 return;
2118 };
2119 let Some(status_entry) = selected_entry.status_entry() else {
2120 return;
2121 };
2122 if status_entry.staging != StageStatus::Staged {
2123 self.change_file_stage(true, vec![status_entry.clone()], cx);
2124 }
2125 }
2126
2127 fn unstage_selected(
2128 &mut self,
2129 _: &git::UnstageFile,
2130 _window: &mut Window,
2131 cx: &mut Context<Self>,
2132 ) {
2133 let Some(selected_entry) = self.get_selected_entry() else {
2134 return;
2135 };
2136 let Some(status_entry) = selected_entry.status_entry() else {
2137 return;
2138 };
2139 if status_entry.staging != StageStatus::Unstaged {
2140 self.change_file_stage(false, vec![status_entry.clone()], cx);
2141 }
2142 }
2143
2144 fn on_commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
2145 if self.commit(&self.commit_editor.focus_handle(cx), window, cx) {
2146 telemetry::event!("Git Committed", source = "Git Panel");
2147 }
2148 }
2149
2150 /// Commits staged changes with the current commit message.
2151 ///
2152 /// Returns `true` if the commit was executed, `false` otherwise.
2153 pub(crate) fn commit(
2154 &mut self,
2155 commit_editor_focus_handle: &FocusHandle,
2156 window: &mut Window,
2157 cx: &mut Context<Self>,
2158 ) -> bool {
2159 if self.amend_pending {
2160 return false;
2161 }
2162
2163 if commit_editor_focus_handle.contains_focused(window, cx) {
2164 self.commit_changes(
2165 CommitOptions {
2166 amend: false,
2167 signoff: self.signoff_enabled,
2168 },
2169 window,
2170 cx,
2171 );
2172 true
2173 } else {
2174 cx.propagate();
2175 false
2176 }
2177 }
2178
2179 fn on_amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
2180 if self.amend(&self.commit_editor.focus_handle(cx), window, cx) {
2181 telemetry::event!("Git Amended", source = "Git Panel");
2182 }
2183 }
2184
2185 /// Amends the most recent commit with staged changes and/or an updated commit message.
2186 ///
2187 /// Uses a two-stage workflow where the first invocation loads the commit
2188 /// message for editing, second invocation performs the amend. Returns
2189 /// `true` if the amend was executed, `false` otherwise.
2190 pub(crate) fn amend(
2191 &mut self,
2192 commit_editor_focus_handle: &FocusHandle,
2193 window: &mut Window,
2194 cx: &mut Context<Self>,
2195 ) -> bool {
2196 if commit_editor_focus_handle.contains_focused(window, cx) {
2197 if self.head_commit(cx).is_some() {
2198 if !self.amend_pending {
2199 self.set_amend_pending(true, cx);
2200 self.load_last_commit_message(cx);
2201
2202 return false;
2203 } else {
2204 self.commit_changes(
2205 CommitOptions {
2206 amend: true,
2207 signoff: self.signoff_enabled,
2208 },
2209 window,
2210 cx,
2211 );
2212
2213 return true;
2214 }
2215 }
2216 return false;
2217 } else {
2218 cx.propagate();
2219 return false;
2220 }
2221 }
2222 pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
2223 self.active_repository
2224 .as_ref()
2225 .and_then(|repo| repo.read(cx).head_commit.as_ref())
2226 .cloned()
2227 }
2228
2229 pub fn load_last_commit_message(&mut self, cx: &mut Context<Self>) {
2230 let Some(head_commit) = self.head_commit(cx) else {
2231 return;
2232 };
2233
2234 let recent_sha = head_commit.sha.to_string();
2235 let detail_task = self.load_commit_details(recent_sha, cx);
2236 cx.spawn(async move |this, cx| {
2237 if let Ok(message) = detail_task.await.map(|detail| detail.message) {
2238 this.update(cx, |this, cx| {
2239 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2240 let start = buffer.anchor_before(0);
2241 let end = buffer.anchor_after(buffer.len());
2242 buffer.edit([(start..end, message)], None, cx);
2243 });
2244 })
2245 .log_err();
2246 }
2247 })
2248 .detach();
2249 }
2250
2251 fn custom_or_suggested_commit_message(
2252 &self,
2253 window: &mut Window,
2254 cx: &mut Context<Self>,
2255 ) -> Option<String> {
2256 let git_commit_language = self
2257 .commit_editor
2258 .read(cx)
2259 .language_at(MultiBufferOffset(0), cx);
2260 let message = self.commit_editor.read(cx).text(cx);
2261 if message.is_empty() {
2262 return self
2263 .suggest_commit_message(cx)
2264 .filter(|message| !message.trim().is_empty());
2265 } else if message.trim().is_empty() {
2266 return None;
2267 }
2268 let buffer = cx.new(|cx| {
2269 let mut buffer = Buffer::local(message, cx);
2270 buffer.set_language(git_commit_language, cx);
2271 buffer
2272 });
2273 let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
2274 let wrapped_message = editor.update(cx, |editor, cx| {
2275 editor.select_all(&Default::default(), window, cx);
2276 editor.rewrap_impl(
2277 RewrapOptions {
2278 override_language_settings: false,
2279 preserve_existing_whitespace: true,
2280 },
2281 cx,
2282 );
2283 editor.text(cx)
2284 });
2285 if wrapped_message.trim().is_empty() {
2286 return None;
2287 }
2288 Some(wrapped_message)
2289 }
2290
2291 fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
2292 let text = self.commit_editor.read(cx).text(cx);
2293 if !text.trim().is_empty() {
2294 true
2295 } else if text.is_empty() {
2296 self.suggest_commit_message(cx)
2297 .is_some_and(|text| !text.trim().is_empty())
2298 } else {
2299 false
2300 }
2301 }
2302
2303 pub(crate) fn commit_changes(
2304 &mut self,
2305 options: CommitOptions,
2306 window: &mut Window,
2307 cx: &mut Context<Self>,
2308 ) {
2309 let Some(active_repository) = self.active_repository.clone() else {
2310 return;
2311 };
2312 let error_spawn = |message, window: &mut Window, cx: &mut App| {
2313 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
2314 cx.spawn(async move |_| {
2315 prompt.await.ok();
2316 })
2317 .detach();
2318 };
2319
2320 if self.has_unstaged_conflicts() {
2321 error_spawn(
2322 "There are still conflicts. You must stage these before committing",
2323 window,
2324 cx,
2325 );
2326 return;
2327 }
2328
2329 let askpass = self.askpass_delegate("git commit", window, cx);
2330 let commit_message = self.custom_or_suggested_commit_message(window, cx);
2331
2332 let Some(mut message) = commit_message else {
2333 self.commit_editor
2334 .read(cx)
2335 .focus_handle(cx)
2336 .focus(window, cx);
2337 return;
2338 };
2339
2340 if self.add_coauthors {
2341 self.fill_co_authors(&mut message, cx);
2342 }
2343
2344 let task = if self.has_staged_changes() {
2345 // Repository serializes all git operations, so we can just send a commit immediately
2346 let commit_task = active_repository.update(cx, |repo, cx| {
2347 repo.commit(message.into(), None, options, askpass, cx)
2348 });
2349 cx.background_spawn(async move { commit_task.await? })
2350 } else {
2351 let changed_files = self
2352 .entries
2353 .iter()
2354 .filter_map(|entry| entry.status_entry())
2355 .filter(|status_entry| !status_entry.status.is_created())
2356 .map(|status_entry| status_entry.repo_path.clone())
2357 .collect::<Vec<_>>();
2358
2359 if changed_files.is_empty() && !options.amend {
2360 error_spawn("No changes to commit", window, cx);
2361 return;
2362 }
2363
2364 let stage_task =
2365 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
2366 cx.spawn(async move |_, cx| {
2367 stage_task.await?;
2368 let commit_task = active_repository.update(cx, |repo, cx| {
2369 repo.commit(message.into(), None, options, askpass, cx)
2370 });
2371 commit_task.await?
2372 })
2373 };
2374 let task = cx.spawn_in(window, async move |this, cx| {
2375 let result = task.await;
2376 this.update_in(cx, |this, window, cx| {
2377 this.pending_commit.take();
2378
2379 match result {
2380 Ok(()) => {
2381 if options.amend {
2382 this.set_amend_pending(false, cx);
2383 } else {
2384 this.commit_editor
2385 .update(cx, |editor, cx| editor.clear(window, cx));
2386 this.original_commit_message = None;
2387 }
2388 }
2389 Err(e) => this.show_error_toast("commit", e, cx),
2390 }
2391 })
2392 .ok();
2393 });
2394
2395 self.pending_commit = Some(task);
2396 }
2397
2398 pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2399 let Some(repo) = self.active_repository.clone() else {
2400 return;
2401 };
2402 telemetry::event!("Git Uncommitted");
2403
2404 let confirmation = self.check_for_pushed_commits(window, cx);
2405 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
2406
2407 let task = cx.spawn_in(window, async move |this, cx| {
2408 let result = maybe!(async {
2409 if let Ok(true) = confirmation.await {
2410 let prior_head = prior_head.await?;
2411
2412 repo.update(cx, |repo, cx| {
2413 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
2414 })
2415 .await??;
2416
2417 Ok(Some(prior_head))
2418 } else {
2419 Ok(None)
2420 }
2421 })
2422 .await;
2423
2424 this.update_in(cx, |this, window, cx| {
2425 this.pending_commit.take();
2426 match result {
2427 Ok(None) => {}
2428 Ok(Some(prior_commit)) => {
2429 this.commit_editor.update(cx, |editor, cx| {
2430 editor.set_text(prior_commit.message, window, cx)
2431 });
2432 }
2433 Err(e) => this.show_error_toast("reset", e, cx),
2434 }
2435 })
2436 .ok();
2437 });
2438
2439 self.pending_commit = Some(task);
2440 }
2441
2442 fn check_for_pushed_commits(
2443 &mut self,
2444 window: &mut Window,
2445 cx: &mut Context<Self>,
2446 ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
2447 let repo = self.active_repository.clone();
2448 let mut cx = window.to_async(cx);
2449
2450 async move {
2451 let repo = repo.context("No active repository")?;
2452
2453 let pushed_to: Vec<SharedString> = repo
2454 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())
2455 .await??;
2456
2457 if pushed_to.is_empty() {
2458 Ok(true)
2459 } else {
2460 #[derive(strum::EnumIter, strum::VariantNames)]
2461 #[strum(serialize_all = "title_case")]
2462 enum CancelUncommit {
2463 Uncommit,
2464 Cancel,
2465 }
2466 let detail = format!(
2467 "This commit was already pushed to {}.",
2468 pushed_to.into_iter().join(", ")
2469 );
2470 let result = cx
2471 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
2472 .await?;
2473
2474 match result {
2475 CancelUncommit::Cancel => Ok(false),
2476 CancelUncommit::Uncommit => Ok(true),
2477 }
2478 }
2479 }
2480 }
2481
2482 /// Suggests a commit message based on the changed files and their statuses
2483 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
2484 if let Some(merge_message) = self
2485 .active_repository
2486 .as_ref()
2487 .and_then(|repo| repo.read(cx).merge.message.as_ref())
2488 {
2489 return Some(merge_message.to_string());
2490 }
2491
2492 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
2493 Some(staged_entry)
2494 } else if self.total_staged_count() == 0
2495 && let Some(single_tracked_entry) = &self.single_tracked_entry
2496 {
2497 Some(single_tracked_entry)
2498 } else {
2499 None
2500 }?;
2501
2502 let action_text = if git_status_entry.status.is_deleted() {
2503 Some("Delete")
2504 } else if git_status_entry.status.is_created() {
2505 Some("Create")
2506 } else if git_status_entry.status.is_modified() {
2507 Some("Update")
2508 } else {
2509 None
2510 }?;
2511
2512 let file_name = git_status_entry
2513 .repo_path
2514 .file_name()
2515 .unwrap_or_default()
2516 .to_string();
2517
2518 Some(format!("{} {}", action_text, file_name))
2519 }
2520
2521 fn generate_commit_message_action(
2522 &mut self,
2523 _: &git::GenerateCommitMessage,
2524 _window: &mut Window,
2525 cx: &mut Context<Self>,
2526 ) {
2527 self.generate_commit_message(cx);
2528 }
2529
2530 fn split_patch(patch: &str) -> Vec<String> {
2531 let mut result = Vec::new();
2532 let mut current_patch = String::new();
2533
2534 for line in patch.lines() {
2535 if line.starts_with("---") && !current_patch.is_empty() {
2536 result.push(current_patch.trim_end_matches('\n').into());
2537 current_patch = String::new();
2538 }
2539 current_patch.push_str(line);
2540 current_patch.push('\n');
2541 }
2542
2543 if !current_patch.is_empty() {
2544 result.push(current_patch.trim_end_matches('\n').into());
2545 }
2546
2547 result
2548 }
2549 fn truncate_iteratively(patch: &str, max_bytes: usize) -> String {
2550 let mut current_size = patch.len();
2551 if current_size <= max_bytes {
2552 return patch.to_string();
2553 }
2554 let file_patches = Self::split_patch(patch);
2555 let mut file_infos: Vec<TruncatedPatch> = file_patches
2556 .iter()
2557 .filter_map(|patch| TruncatedPatch::from_unified_diff(patch))
2558 .collect();
2559
2560 if file_infos.is_empty() {
2561 return patch.to_string();
2562 }
2563
2564 current_size = file_infos.iter().map(|f| f.calculate_size()).sum::<usize>();
2565 while current_size > max_bytes {
2566 let file_idx = file_infos
2567 .iter()
2568 .enumerate()
2569 .filter(|(_, f)| f.hunks_to_keep > 1)
2570 .max_by_key(|(_, f)| f.hunks_to_keep)
2571 .map(|(idx, _)| idx);
2572 match file_idx {
2573 Some(idx) => {
2574 let file = &mut file_infos[idx];
2575 let size_before = file.calculate_size();
2576 file.hunks_to_keep -= 1;
2577 let size_after = file.calculate_size();
2578 let saved = size_before.saturating_sub(size_after);
2579 current_size = current_size.saturating_sub(saved);
2580 }
2581 None => {
2582 break;
2583 }
2584 }
2585 }
2586
2587 file_infos
2588 .iter()
2589 .map(|info| info.to_string())
2590 .collect::<Vec<_>>()
2591 .join("\n")
2592 }
2593
2594 pub fn compress_commit_diff(diff_text: &str, max_bytes: usize) -> String {
2595 if diff_text.len() <= max_bytes {
2596 return diff_text.to_string();
2597 }
2598
2599 let mut compressed = diff_text
2600 .lines()
2601 .map(|line| {
2602 if line.len() > 256 {
2603 format!("{}...[truncated]\n", &line[..line.floor_char_boundary(256)])
2604 } else {
2605 format!("{}\n", line)
2606 }
2607 })
2608 .collect::<Vec<_>>()
2609 .join("");
2610
2611 if compressed.len() <= max_bytes {
2612 return compressed;
2613 }
2614
2615 compressed = Self::truncate_iteratively(&compressed, max_bytes);
2616
2617 compressed
2618 }
2619
2620 async fn load_project_rules(
2621 project: &Entity<Project>,
2622 repo_work_dir: &Arc<Path>,
2623 cx: &mut AsyncApp,
2624 ) -> Option<String> {
2625 let rules_path = cx.update(|cx| {
2626 for worktree in project.read(cx).worktrees(cx) {
2627 let worktree_abs_path = worktree.read(cx).abs_path();
2628 if !worktree_abs_path.starts_with(&repo_work_dir) {
2629 continue;
2630 }
2631
2632 let worktree_snapshot = worktree.read(cx).snapshot();
2633 for rules_name in RULES_FILE_NAMES {
2634 if let Ok(rel_path) = RelPath::unix(rules_name) {
2635 if let Some(entry) = worktree_snapshot.entry_for_path(rel_path) {
2636 if entry.is_file() {
2637 return Some(ProjectPath {
2638 worktree_id: worktree.read(cx).id(),
2639 path: entry.path.clone(),
2640 });
2641 }
2642 }
2643 }
2644 }
2645 }
2646 None
2647 })?;
2648
2649 let buffer = project
2650 .update(cx, |project, cx| project.open_buffer(rules_path, cx))
2651 .await
2652 .ok()?;
2653
2654 let content = buffer
2655 .read_with(cx, |buffer, _| buffer.text())
2656 .trim()
2657 .to_string();
2658
2659 if content.is_empty() {
2660 None
2661 } else {
2662 Some(content)
2663 }
2664 }
2665
2666 async fn load_commit_message_prompt(cx: &mut AsyncApp) -> String {
2667 let load = async {
2668 let store = cx.update(|cx| PromptStore::global(cx)).await.ok()?;
2669 store
2670 .update(cx, |s, cx| {
2671 s.load(PromptId::BuiltIn(BuiltInPrompt::CommitMessage), cx)
2672 })
2673 .await
2674 .ok()
2675 };
2676 load.await
2677 .unwrap_or_else(|| BuiltInPrompt::CommitMessage.default_content().to_string())
2678 }
2679
2680 /// Generates a commit message using an LLM.
2681 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
2682 if !self.can_commit() || !AgentSettings::get_global(cx).enabled(cx) {
2683 return;
2684 }
2685
2686 let Some(ConfiguredModel { provider, model }) =
2687 LanguageModelRegistry::read_global(cx).commit_message_model()
2688 else {
2689 return;
2690 };
2691
2692 let Some(repo) = self.active_repository.as_ref() else {
2693 return;
2694 };
2695
2696 telemetry::event!("Git Commit Message Generated");
2697
2698 let diff = repo.update(cx, |repo, cx| {
2699 if self.has_staged_changes() {
2700 repo.diff(DiffType::HeadToIndex, cx)
2701 } else {
2702 repo.diff(DiffType::HeadToWorktree, cx)
2703 }
2704 });
2705
2706 let temperature = AgentSettings::temperature_for_model(&model, cx);
2707 let project = self.project.clone();
2708 let repo_work_dir = repo.read(cx).work_directory_abs_path.clone();
2709
2710 self.generate_commit_message_task = Some(cx.spawn(async move |this, mut cx| {
2711 async move {
2712 let _defer = cx.on_drop(&this, |this, _cx| {
2713 this.generate_commit_message_task.take();
2714 });
2715
2716 if let Some(task) = cx.update(|cx| {
2717 if !provider.is_authenticated(cx) {
2718 Some(provider.authenticate(cx))
2719 } else {
2720 None
2721 }
2722 }) {
2723 task.await.log_err();
2724 }
2725
2726 let mut diff_text = match diff.await {
2727 Ok(result) => match result {
2728 Ok(text) => text,
2729 Err(e) => {
2730 Self::show_commit_message_error(&this, &e, cx);
2731 return anyhow::Ok(());
2732 }
2733 },
2734 Err(e) => {
2735 Self::show_commit_message_error(&this, &e, cx);
2736 return anyhow::Ok(());
2737 }
2738 };
2739
2740 const MAX_DIFF_BYTES: usize = 20_000;
2741 diff_text = Self::compress_commit_diff(&diff_text, MAX_DIFF_BYTES);
2742
2743 let rules_content = Self::load_project_rules(&project, &repo_work_dir, &mut cx).await;
2744
2745 let prompt = Self::load_commit_message_prompt(&mut cx).await;
2746
2747 let subject = this.update(cx, |this, cx| {
2748 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
2749 })?;
2750
2751 let text_empty = subject.trim().is_empty();
2752
2753 let rules_section = match &rules_content {
2754 Some(rules) => format!(
2755 "\n\nThe user has provided the following project rules that you should follow when writing the commit message:\n\
2756 <project_rules>\n{rules}\n</project_rules>\n"
2757 ),
2758 None => String::new(),
2759 };
2760
2761 let subject_section = if text_empty {
2762 String::new()
2763 } else {
2764 format!("\nHere is the user's subject line:\n{subject}")
2765 };
2766
2767 let content = format!(
2768 "{prompt}{rules_section}{subject_section}\nHere are the changes in this commit:\n{diff_text}"
2769 );
2770
2771 let request = LanguageModelRequest {
2772 thread_id: None,
2773 prompt_id: None,
2774 intent: Some(CompletionIntent::GenerateGitCommitMessage),
2775 messages: vec![LanguageModelRequestMessage {
2776 role: Role::User,
2777 content: vec![content.into()],
2778 cache: false,
2779 reasoning_details: None,
2780 }],
2781 tools: Vec::new(),
2782 tool_choice: None,
2783 stop: Vec::new(),
2784 temperature,
2785 thinking_allowed: false,
2786 thinking_effort: None,
2787 speed: None,
2788 };
2789
2790 let stream = model.stream_completion_text(request, cx);
2791 match stream.await {
2792 Ok(mut messages) => {
2793 if !text_empty {
2794 this.update(cx, |this, cx| {
2795 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2796 let insert_position = buffer.anchor_before(buffer.len());
2797 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
2798 });
2799 })?;
2800 }
2801
2802 while let Some(message) = messages.stream.next().await {
2803 match message {
2804 Ok(text) => {
2805 this.update(cx, |this, cx| {
2806 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2807 let insert_position = buffer.anchor_before(buffer.len());
2808 buffer.edit([(insert_position..insert_position, text)], None, cx);
2809 });
2810 })?;
2811 }
2812 Err(e) => {
2813 Self::show_commit_message_error(&this, &e, cx);
2814 break;
2815 }
2816 }
2817 }
2818 }
2819 Err(e) => {
2820 Self::show_commit_message_error(&this, &e, cx);
2821 }
2822 }
2823
2824 anyhow::Ok(())
2825 }
2826 .log_err().await
2827 }));
2828 }
2829
2830 fn get_fetch_options(
2831 &self,
2832 window: &mut Window,
2833 cx: &mut Context<Self>,
2834 ) -> Task<Option<FetchOptions>> {
2835 let repo = self.active_repository.clone();
2836 let workspace = self.workspace.clone();
2837
2838 cx.spawn_in(window, async move |_, cx| {
2839 let repo = repo?;
2840 let remotes = repo
2841 .update(cx, |repo, _| repo.get_remotes(None, false))
2842 .await
2843 .ok()?
2844 .log_err()?;
2845
2846 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2847 if remotes.len() > 1 {
2848 remotes.push(FetchOptions::All);
2849 }
2850 let selection = cx
2851 .update(|window, cx| {
2852 picker_prompt::prompt(
2853 "Pick which remote to fetch",
2854 remotes.iter().map(|r| r.name()).collect(),
2855 workspace,
2856 window,
2857 cx,
2858 )
2859 })
2860 .ok()?
2861 .await?;
2862 remotes.get(selection).cloned()
2863 })
2864 }
2865
2866 pub(crate) fn fetch(
2867 &mut self,
2868 is_fetch_all: bool,
2869 window: &mut Window,
2870 cx: &mut Context<Self>,
2871 ) {
2872 if !self.can_push_and_pull(cx) {
2873 return;
2874 }
2875
2876 let Some(repo) = self.active_repository.clone() else {
2877 return;
2878 };
2879 telemetry::event!("Git Fetched");
2880 let askpass = self.askpass_delegate("git fetch", window, cx);
2881 let this = cx.weak_entity();
2882
2883 let fetch_options = if is_fetch_all {
2884 Task::ready(Some(FetchOptions::All))
2885 } else {
2886 self.get_fetch_options(window, cx)
2887 };
2888
2889 window
2890 .spawn(cx, async move |cx| {
2891 let Some(fetch_options) = fetch_options.await else {
2892 return Ok(());
2893 };
2894 let fetch = repo.update(cx, |repo, cx| {
2895 repo.fetch(fetch_options.clone(), askpass, cx)
2896 });
2897
2898 let remote_message = fetch.await?;
2899 this.update(cx, |this, cx| {
2900 let action = match fetch_options {
2901 FetchOptions::All => RemoteAction::Fetch(None),
2902 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2903 };
2904 match remote_message {
2905 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2906 Err(e) => {
2907 log::error!("Error while fetching {:?}", e);
2908 this.show_error_toast(action.name(), e, cx)
2909 }
2910 }
2911
2912 anyhow::Ok(())
2913 })
2914 .ok();
2915 anyhow::Ok(())
2916 })
2917 .detach_and_log_err(cx);
2918 }
2919
2920 pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2921 let workspace = self.workspace.clone();
2922
2923 crate::clone::clone_and_open(
2924 repo.into(),
2925 workspace,
2926 window,
2927 cx,
2928 Arc::new(|_workspace: &mut workspace::Workspace, _window, _cx| {}),
2929 );
2930 }
2931
2932 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2933 let worktrees = self
2934 .project
2935 .read(cx)
2936 .visible_worktrees(cx)
2937 .collect::<Vec<_>>();
2938
2939 let worktree = if worktrees.len() == 1 {
2940 Task::ready(Some(worktrees.first().unwrap().clone()))
2941 } else if worktrees.is_empty() {
2942 let result = window.prompt(
2943 PromptLevel::Warning,
2944 "Unable to initialize a git repository",
2945 Some("Open a directory first"),
2946 &["Ok"],
2947 cx,
2948 );
2949 cx.background_executor()
2950 .spawn(async move {
2951 result.await.ok();
2952 })
2953 .detach();
2954 return;
2955 } else {
2956 let worktree_directories = worktrees
2957 .iter()
2958 .map(|worktree| worktree.read(cx).abs_path())
2959 .map(|worktree_abs_path| {
2960 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2961 Path::new("~")
2962 .join(path)
2963 .to_string_lossy()
2964 .to_string()
2965 .into()
2966 } else {
2967 worktree_abs_path.to_string_lossy().into_owned().into()
2968 }
2969 })
2970 .collect_vec();
2971 let prompt = picker_prompt::prompt(
2972 "Where would you like to initialize this git repository?",
2973 worktree_directories,
2974 self.workspace.clone(),
2975 window,
2976 cx,
2977 );
2978
2979 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2980 };
2981
2982 cx.spawn_in(window, async move |this, cx| {
2983 let worktree = match worktree.await {
2984 Some(worktree) => worktree,
2985 None => {
2986 return;
2987 }
2988 };
2989
2990 let Ok(result) = this.update(cx, |this, cx| {
2991 let fallback_branch_name = GitPanelSettings::get_global(cx)
2992 .fallback_branch_name
2993 .clone();
2994 this.project.read(cx).git_init(
2995 worktree.read(cx).abs_path(),
2996 fallback_branch_name,
2997 cx,
2998 )
2999 }) else {
3000 return;
3001 };
3002
3003 let result = result.await;
3004
3005 this.update_in(cx, |this, _, cx| match result {
3006 Ok(()) => {}
3007 Err(e) => this.show_error_toast("init", e, cx),
3008 })
3009 .ok();
3010 })
3011 .detach();
3012 }
3013
3014 pub(crate) fn pull(&mut self, rebase: bool, window: &mut Window, cx: &mut Context<Self>) {
3015 if !self.can_push_and_pull(cx) {
3016 return;
3017 }
3018 let Some(repo) = self.active_repository.clone() else {
3019 return;
3020 };
3021 let Some(branch) = repo.read(cx).branch.as_ref() else {
3022 return;
3023 };
3024 telemetry::event!("Git Pulled");
3025 let branch = branch.clone();
3026 let remote = self.get_remote(false, false, window, cx);
3027 cx.spawn_in(window, async move |this, cx| {
3028 let remote = match remote.await {
3029 Ok(Some(remote)) => remote,
3030 Ok(None) => {
3031 return Ok(());
3032 }
3033 Err(e) => {
3034 log::error!("Failed to get current remote: {}", e);
3035 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
3036 .ok();
3037 return Ok(());
3038 }
3039 };
3040
3041 let askpass = this.update_in(cx, |this, window, cx| {
3042 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
3043 })?;
3044
3045 let branch_name = branch
3046 .upstream
3047 .is_none()
3048 .then(|| branch.name().to_owned().into());
3049
3050 let pull = repo.update(cx, |repo, cx| {
3051 repo.pull(branch_name, remote.name.clone(), rebase, askpass, cx)
3052 });
3053
3054 let remote_message = pull.await?;
3055
3056 let action = RemoteAction::Pull(remote);
3057 this.update(cx, |this, cx| match remote_message {
3058 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3059 Err(e) => {
3060 log::error!("Error while pulling {:?}", e);
3061 this.show_error_toast(action.name(), e, cx)
3062 }
3063 })
3064 .ok();
3065
3066 anyhow::Ok(())
3067 })
3068 .detach_and_log_err(cx);
3069 }
3070
3071 pub(crate) fn push(
3072 &mut self,
3073 force_push: bool,
3074 select_remote: bool,
3075 window: &mut Window,
3076 cx: &mut Context<Self>,
3077 ) {
3078 if !self.can_push_and_pull(cx) {
3079 return;
3080 }
3081 let Some(repo) = self.active_repository.clone() else {
3082 return;
3083 };
3084 let Some(branch) = repo.read(cx).branch.as_ref() else {
3085 return;
3086 };
3087 telemetry::event!("Git Pushed");
3088 let branch = branch.clone();
3089
3090 let options = if force_push {
3091 Some(PushOptions::Force)
3092 } else {
3093 match branch.upstream {
3094 Some(Upstream {
3095 tracking: UpstreamTracking::Gone,
3096 ..
3097 })
3098 | None => Some(PushOptions::SetUpstream),
3099 _ => None,
3100 }
3101 };
3102 let remote = self.get_remote(select_remote, true, window, cx);
3103
3104 cx.spawn_in(window, async move |this, cx| {
3105 let remote = match remote.await {
3106 Ok(Some(remote)) => remote,
3107 Ok(None) => {
3108 return Ok(());
3109 }
3110 Err(e) => {
3111 log::error!("Failed to get current remote: {}", e);
3112 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
3113 .ok();
3114 return Ok(());
3115 }
3116 };
3117
3118 let askpass_delegate = this.update_in(cx, |this, window, cx| {
3119 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
3120 })?;
3121
3122 let push = repo.update(cx, |repo, cx| {
3123 repo.push(
3124 branch.name().to_owned().into(),
3125 branch
3126 .upstream
3127 .as_ref()
3128 .filter(|u| matches!(u.tracking, UpstreamTracking::Tracked(_)))
3129 .and_then(|u| u.branch_name())
3130 .unwrap_or_else(|| branch.name())
3131 .to_owned()
3132 .into(),
3133 remote.name.clone(),
3134 options,
3135 askpass_delegate,
3136 cx,
3137 )
3138 });
3139
3140 let remote_output = push.await?;
3141
3142 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
3143 this.update(cx, |this, cx| match remote_output {
3144 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3145 Err(e) => {
3146 log::error!("Error while pushing {:?}", e);
3147 this.show_error_toast(action.name(), e, cx)
3148 }
3149 })?;
3150
3151 anyhow::Ok(())
3152 })
3153 .detach_and_log_err(cx);
3154 }
3155
3156 pub fn create_pull_request(&self, window: &mut Window, cx: &mut Context<Self>) {
3157 let result = (|| -> anyhow::Result<()> {
3158 let repo = self
3159 .active_repository
3160 .clone()
3161 .ok_or_else(|| anyhow::anyhow!("No active repository"))?;
3162
3163 let (branch, remote_origin, remote_upstream) = {
3164 let repository = repo.read(cx);
3165 (
3166 repository.branch.clone(),
3167 repository.remote_origin_url.clone(),
3168 repository.remote_upstream_url.clone(),
3169 )
3170 };
3171
3172 let branch = branch.ok_or_else(|| anyhow::anyhow!("No active branch"))?;
3173 let source_branch = branch
3174 .upstream
3175 .as_ref()
3176 .filter(|upstream| matches!(upstream.tracking, UpstreamTracking::Tracked(_)))
3177 .and_then(|upstream| upstream.branch_name())
3178 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3179 let source_branch = source_branch.to_string();
3180
3181 let remote_url = branch
3182 .upstream
3183 .as_ref()
3184 .and_then(|upstream| match upstream.remote_name() {
3185 Some("upstream") => remote_upstream.as_deref(),
3186 Some(_) => remote_origin.as_deref(),
3187 None => None,
3188 })
3189 .or(remote_origin.as_deref())
3190 .or(remote_upstream.as_deref())
3191 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3192 let remote_url = remote_url.to_string();
3193
3194 let provider_registry = GitHostingProviderRegistry::global(cx);
3195 let Some((provider, parsed_remote)) =
3196 git::parse_git_remote_url(provider_registry, &remote_url)
3197 else {
3198 return Err(anyhow::anyhow!("Unsupported remote URL: {}", remote_url));
3199 };
3200
3201 let Some(url) = provider.build_create_pull_request_url(&parsed_remote, &source_branch)
3202 else {
3203 return Err(anyhow::anyhow!("Unable to construct pull request URL"));
3204 };
3205
3206 cx.open_url(url.as_str());
3207 Ok(())
3208 })();
3209
3210 if let Err(err) = result {
3211 log::error!("Error while creating pull request {:?}", err);
3212 cx.defer_in(window, |panel, _window, cx| {
3213 panel.show_error_toast("create pull request", err, cx);
3214 });
3215 }
3216 }
3217
3218 fn askpass_delegate(
3219 &self,
3220 operation: impl Into<SharedString>,
3221 window: &mut Window,
3222 cx: &mut Context<Self>,
3223 ) -> AskPassDelegate {
3224 let workspace = self.workspace.clone();
3225 let operation = operation.into();
3226 let window = window.window_handle();
3227 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
3228 window
3229 .update(cx, |_, window, cx| {
3230 workspace.update(cx, |workspace, cx| {
3231 workspace.toggle_modal(window, cx, |window, cx| {
3232 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
3233 });
3234 })
3235 })
3236 .ok();
3237 })
3238 }
3239
3240 fn can_push_and_pull(&self, cx: &App) -> bool {
3241 !self.project.read(cx).is_via_collab()
3242 }
3243
3244 fn get_remote(
3245 &mut self,
3246 always_select: bool,
3247 is_push: bool,
3248 window: &mut Window,
3249 cx: &mut Context<Self>,
3250 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
3251 let repo = self.active_repository.clone();
3252 let workspace = self.workspace.clone();
3253 let mut cx = window.to_async(cx);
3254
3255 async move {
3256 let repo = repo.context("No active repository")?;
3257 let current_remotes: Vec<Remote> = repo
3258 .update(&mut cx, |repo, _| {
3259 let current_branch = if always_select {
3260 None
3261 } else {
3262 let current_branch = repo.branch.as_ref().context("No active branch")?;
3263 Some(current_branch.name().to_string())
3264 };
3265 anyhow::Ok(repo.get_remotes(current_branch, is_push))
3266 })?
3267 .await??;
3268
3269 let current_remotes: Vec<_> = current_remotes
3270 .into_iter()
3271 .map(|remotes| remotes.name)
3272 .collect();
3273 let selection = cx
3274 .update(|window, cx| {
3275 picker_prompt::prompt(
3276 "Pick which remote to push to",
3277 current_remotes.clone(),
3278 workspace,
3279 window,
3280 cx,
3281 )
3282 })?
3283 .await;
3284
3285 Ok(selection.map(|selection| Remote {
3286 name: current_remotes[selection].clone(),
3287 }))
3288 }
3289 }
3290
3291 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
3292 if self.local_committer_task.is_none() {
3293 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
3294 let committer = get_git_committer(cx).await;
3295 this.update(cx, |this, cx| {
3296 this.local_committer = Some(committer);
3297 cx.notify()
3298 })
3299 .ok();
3300 }));
3301 }
3302 }
3303
3304 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
3305 let mut new_co_authors = Vec::new();
3306 let project = self.project.read(cx);
3307
3308 let Some(room) =
3309 call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
3310 else {
3311 return Vec::default();
3312 };
3313
3314 let room = room.read(cx);
3315
3316 for (peer_id, collaborator) in project.collaborators() {
3317 if collaborator.is_host {
3318 continue;
3319 }
3320
3321 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
3322 continue;
3323 };
3324 if !participant.can_write() {
3325 continue;
3326 }
3327 if let Some(email) = &collaborator.committer_email {
3328 let name = collaborator
3329 .committer_name
3330 .clone()
3331 .or_else(|| participant.user.name.clone())
3332 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
3333 new_co_authors.push((name.clone(), email.clone()))
3334 }
3335 }
3336 if !project.is_local()
3337 && !project.is_read_only(cx)
3338 && let Some(local_committer) = self.local_committer(room, cx)
3339 {
3340 new_co_authors.push(local_committer);
3341 }
3342 new_co_authors
3343 }
3344
3345 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
3346 let user = room.local_participant_user(cx)?;
3347 let committer = self.local_committer.as_ref()?;
3348 let email = committer.email.clone()?;
3349 let name = committer
3350 .name
3351 .clone()
3352 .or_else(|| user.name.clone())
3353 .unwrap_or_else(|| user.github_login.clone().to_string());
3354 Some((name, email))
3355 }
3356
3357 fn toggle_fill_co_authors(
3358 &mut self,
3359 _: &ToggleFillCoAuthors,
3360 _: &mut Window,
3361 cx: &mut Context<Self>,
3362 ) {
3363 self.add_coauthors = !self.add_coauthors;
3364 cx.notify();
3365 }
3366
3367 fn toggle_sort_by_path(
3368 &mut self,
3369 _: &ToggleSortByPath,
3370 _: &mut Window,
3371 cx: &mut Context<Self>,
3372 ) {
3373 let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
3374 if let Some(workspace) = self.workspace.upgrade() {
3375 let workspace = workspace.read(cx);
3376 let fs = workspace.app_state().fs.clone();
3377 cx.update_global::<SettingsStore, _>(|store, _cx| {
3378 store.update_settings_file(fs, move |settings, _cx| {
3379 settings.git_panel.get_or_insert_default().sort_by_path =
3380 Some(!current_setting);
3381 });
3382 });
3383 }
3384 }
3385
3386 fn toggle_tree_view(&mut self, _: &ToggleTreeView, _: &mut Window, cx: &mut Context<Self>) {
3387 let current_setting = GitPanelSettings::get_global(cx).tree_view;
3388 if let Some(workspace) = self.workspace.upgrade() {
3389 let workspace = workspace.read(cx);
3390 let fs = workspace.app_state().fs.clone();
3391 cx.update_global::<SettingsStore, _>(|store, _cx| {
3392 store.update_settings_file(fs, move |settings, _cx| {
3393 settings.git_panel.get_or_insert_default().tree_view = Some(!current_setting);
3394 });
3395 })
3396 }
3397 }
3398
3399 fn toggle_directory(&mut self, key: &TreeKey, window: &mut Window, cx: &mut Context<Self>) {
3400 if let Some(state) = self.view_mode.tree_state_mut() {
3401 let expanded = state.expanded_dirs.entry(key.clone()).or_insert(true);
3402 *expanded = !*expanded;
3403 self.update_visible_entries(window, cx);
3404 } else {
3405 util::debug_panic!("Attempted to toggle directory in flat Git Panel state");
3406 }
3407 }
3408
3409 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
3410 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
3411
3412 let existing_text = message.to_ascii_lowercase();
3413 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
3414 let mut ends_with_co_authors = false;
3415 let existing_co_authors = existing_text
3416 .lines()
3417 .filter_map(|line| {
3418 let line = line.trim();
3419 if line.starts_with(&lowercase_co_author_prefix) {
3420 ends_with_co_authors = true;
3421 Some(line)
3422 } else {
3423 ends_with_co_authors = false;
3424 None
3425 }
3426 })
3427 .collect::<HashSet<_>>();
3428
3429 let new_co_authors = self
3430 .potential_co_authors(cx)
3431 .into_iter()
3432 .filter(|(_, email)| {
3433 !existing_co_authors
3434 .iter()
3435 .any(|existing| existing.contains(email.as_str()))
3436 })
3437 .collect::<Vec<_>>();
3438
3439 if new_co_authors.is_empty() {
3440 return;
3441 }
3442
3443 if !ends_with_co_authors {
3444 message.push('\n');
3445 }
3446 for (name, email) in new_co_authors {
3447 message.push('\n');
3448 message.push_str(CO_AUTHOR_PREFIX);
3449 message.push_str(&name);
3450 message.push_str(" <");
3451 message.push_str(&email);
3452 message.push('>');
3453 }
3454 message.push('\n');
3455 }
3456
3457 fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3458 let handle = cx.entity().downgrade();
3459 self.reopen_commit_buffer(window, cx);
3460 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
3461 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
3462 if let Some(git_panel) = handle.upgrade() {
3463 git_panel
3464 .update_in(cx, |git_panel, window, cx| {
3465 git_panel.update_visible_entries(window, cx);
3466 })
3467 .ok();
3468 }
3469 });
3470 }
3471
3472 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3473 let Some(active_repo) = self.active_repository.as_ref() else {
3474 return;
3475 };
3476 let load_buffer = active_repo.update(cx, |active_repo, cx| {
3477 let project = self.project.read(cx);
3478 active_repo.open_commit_buffer(
3479 Some(project.languages().clone()),
3480 project.buffer_store().clone(),
3481 cx,
3482 )
3483 });
3484
3485 cx.spawn_in(window, async move |git_panel, cx| {
3486 let buffer = load_buffer.await?;
3487 git_panel.update_in(cx, |git_panel, window, cx| {
3488 if git_panel
3489 .commit_editor
3490 .read(cx)
3491 .buffer()
3492 .read(cx)
3493 .as_singleton()
3494 .as_ref()
3495 != Some(&buffer)
3496 {
3497 git_panel.commit_editor = cx.new(|cx| {
3498 commit_message_editor(
3499 buffer,
3500 git_panel.suggest_commit_message(cx).map(SharedString::from),
3501 git_panel.project.clone(),
3502 true,
3503 window,
3504 cx,
3505 )
3506 });
3507 }
3508 })
3509 })
3510 .detach_and_log_err(cx);
3511 }
3512
3513 fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3514 let path_style = self.project.read(cx).path_style(cx);
3515 let bulk_staging = self.bulk_staging.take();
3516 let last_staged_path_prev_index = bulk_staging
3517 .as_ref()
3518 .and_then(|op| self.entry_by_path(&op.anchor));
3519
3520 self.active_repository = self.project.read(cx).active_repository(cx);
3521 self.entries.clear();
3522 self.entries_indices.clear();
3523 self.single_staged_entry.take();
3524 self.single_tracked_entry.take();
3525 self.conflicted_count = 0;
3526 self.conflicted_staged_count = 0;
3527 self.changes_count = 0;
3528 self.new_count = 0;
3529 self.tracked_count = 0;
3530 self.new_staged_count = 0;
3531 self.tracked_staged_count = 0;
3532 self.entry_count = 0;
3533 self.max_width_item_index = None;
3534
3535 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
3536 let is_tree_view = matches!(self.view_mode, GitPanelViewMode::Tree(_));
3537 let group_by_status = is_tree_view || !sort_by_path;
3538
3539 let mut changed_entries = Vec::new();
3540 let mut new_entries = Vec::new();
3541 let mut conflict_entries = Vec::new();
3542 let mut single_staged_entry = None;
3543 let mut staged_count = 0;
3544 let mut seen_directories = HashSet::default();
3545 let mut max_width_estimate = 0usize;
3546 let mut max_width_item_index = None;
3547
3548 let Some(repo) = self.active_repository.as_ref() else {
3549 // Just clear entries if no repository is active.
3550 cx.notify();
3551 return;
3552 };
3553
3554 let repo = repo.read(cx);
3555
3556 self.stash_entries = repo.cached_stash();
3557
3558 for entry in repo.cached_status() {
3559 self.changes_count += 1;
3560 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
3561 let is_new = entry.status.is_created();
3562 let staging = entry.status.staging();
3563
3564 if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
3565 && pending
3566 .ops
3567 .iter()
3568 .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
3569 {
3570 continue;
3571 }
3572
3573 let entry = GitStatusEntry {
3574 repo_path: entry.repo_path.clone(),
3575 status: entry.status,
3576 staging,
3577 };
3578
3579 if staging.has_staged() {
3580 staged_count += 1;
3581 single_staged_entry = Some(entry.clone());
3582 }
3583
3584 if group_by_status && is_conflict {
3585 conflict_entries.push(entry);
3586 } else if group_by_status && is_new {
3587 new_entries.push(entry);
3588 } else {
3589 changed_entries.push(entry);
3590 }
3591 }
3592
3593 if conflict_entries.is_empty() {
3594 if staged_count == 1
3595 && let Some(entry) = single_staged_entry.as_ref()
3596 {
3597 if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
3598 if ops.staged() {
3599 self.single_staged_entry = single_staged_entry;
3600 }
3601 } else {
3602 self.single_staged_entry = single_staged_entry;
3603 }
3604 } else if repo.pending_ops_summary().item_summary.staging_count == 1
3605 && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
3606 {
3607 self.single_staged_entry =
3608 repo.status_for_path(&ops.repo_path)
3609 .map(|status| GitStatusEntry {
3610 repo_path: ops.repo_path.clone(),
3611 status: status.status,
3612 staging: StageStatus::Staged,
3613 });
3614 }
3615 }
3616
3617 if conflict_entries.is_empty() && changed_entries.len() == 1 {
3618 self.single_tracked_entry = changed_entries.first().cloned();
3619 }
3620
3621 let mut push_entry =
3622 |this: &mut Self,
3623 entry: GitListEntry,
3624 is_visible: bool,
3625 logical_indices: Option<&mut Vec<usize>>| {
3626 if let Some(estimate) =
3627 this.width_estimate_for_list_entry(is_tree_view, &entry, path_style)
3628 {
3629 if estimate > max_width_estimate {
3630 max_width_estimate = estimate;
3631 max_width_item_index = Some(this.entries.len());
3632 }
3633 }
3634
3635 if let Some(repo_path) = entry.status_entry().map(|status| status.repo_path.clone())
3636 {
3637 this.entries_indices.insert(repo_path, this.entries.len());
3638 }
3639
3640 if let (Some(indices), true) = (logical_indices, is_visible) {
3641 indices.push(this.entries.len());
3642 }
3643
3644 this.entries.push(entry);
3645 };
3646
3647 macro_rules! take_section_entries {
3648 () => {
3649 [
3650 (Section::Conflict, std::mem::take(&mut conflict_entries)),
3651 (Section::Tracked, std::mem::take(&mut changed_entries)),
3652 (Section::New, std::mem::take(&mut new_entries)),
3653 ]
3654 };
3655 }
3656
3657 match &mut self.view_mode {
3658 GitPanelViewMode::Tree(tree_state) => {
3659 tree_state.logical_indices.clear();
3660 tree_state.directory_descendants.clear();
3661
3662 // This is just to get around the borrow checker
3663 // because push_entry mutably borrows self
3664 let mut tree_state = std::mem::take(tree_state);
3665
3666 for (section, entries) in take_section_entries!() {
3667 if entries.is_empty() {
3668 continue;
3669 }
3670
3671 push_entry(
3672 self,
3673 GitListEntry::Header(GitHeaderEntry { header: section }),
3674 true,
3675 Some(&mut tree_state.logical_indices),
3676 );
3677
3678 for (entry, is_visible) in
3679 tree_state.build_tree_entries(section, entries, &mut seen_directories)
3680 {
3681 push_entry(
3682 self,
3683 entry,
3684 is_visible,
3685 Some(&mut tree_state.logical_indices),
3686 );
3687 }
3688 }
3689
3690 tree_state
3691 .expanded_dirs
3692 .retain(|key, _| seen_directories.contains(key));
3693 self.view_mode = GitPanelViewMode::Tree(tree_state);
3694 }
3695 GitPanelViewMode::Flat => {
3696 for (section, entries) in take_section_entries!() {
3697 if entries.is_empty() {
3698 continue;
3699 }
3700
3701 if section != Section::Tracked || !sort_by_path {
3702 push_entry(
3703 self,
3704 GitListEntry::Header(GitHeaderEntry { header: section }),
3705 true,
3706 None,
3707 );
3708 }
3709
3710 for entry in entries {
3711 push_entry(self, GitListEntry::Status(entry), true, None);
3712 }
3713 }
3714 }
3715 }
3716
3717 self.max_width_item_index = max_width_item_index;
3718
3719 self.update_counts(repo);
3720
3721 let bulk_staging_anchor_new_index = bulk_staging
3722 .as_ref()
3723 .filter(|op| op.repo_id == repo.id)
3724 .and_then(|op| self.entry_by_path(&op.anchor));
3725 if bulk_staging_anchor_new_index == last_staged_path_prev_index
3726 && let Some(index) = bulk_staging_anchor_new_index
3727 && let Some(entry) = self.entries.get(index)
3728 && let Some(entry) = entry.status_entry()
3729 && GitPanel::stage_status_for_entry(entry, &repo)
3730 .as_bool()
3731 .unwrap_or(false)
3732 {
3733 self.bulk_staging = bulk_staging;
3734 }
3735
3736 self.select_first_entry_if_none(window, cx);
3737
3738 let suggested_commit_message = self.suggest_commit_message(cx);
3739 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
3740
3741 self.commit_editor.update(cx, |editor, cx| {
3742 editor.set_placeholder_text(&placeholder_text, window, cx)
3743 });
3744
3745 if GitPanelSettings::get_global(cx).diff_stats {
3746 self.fetch_diff_stats(cx);
3747 }
3748
3749 cx.notify();
3750 }
3751
3752 fn fetch_diff_stats(&mut self, cx: &mut Context<Self>) {
3753 let Some(repo) = self.active_repository.clone() else {
3754 self.diff_stats.clear();
3755 return;
3756 };
3757
3758 let unstaged_rx = repo.update(cx, |repo, cx| repo.diff_stat(DiffType::HeadToWorktree, cx));
3759 let staged_rx = repo.update(cx, |repo, cx| repo.diff_stat(DiffType::HeadToIndex, cx));
3760
3761 self.diff_stats_task = cx.spawn(async move |this, cx| {
3762 let (unstaged_result, staged_result) =
3763 futures::future::join(unstaged_rx, staged_rx).await;
3764
3765 let mut combined = match unstaged_result {
3766 Ok(Ok(stats)) => stats,
3767 Ok(Err(err)) => {
3768 log::warn!("Failed to fetch unstaged diff stats: {err:?}");
3769 HashMap::default()
3770 }
3771 Err(_) => HashMap::default(),
3772 };
3773
3774 let staged = match staged_result {
3775 Ok(Ok(stats)) => Some(stats),
3776 Ok(Err(err)) => {
3777 log::warn!("Failed to fetch staged diff stats: {err:?}");
3778 None
3779 }
3780 Err(_) => None,
3781 };
3782
3783 if let Some(staged) = staged {
3784 for (path, stat) in staged {
3785 let entry = combined.entry(path).or_default();
3786 entry.added += stat.added;
3787 entry.deleted += stat.deleted;
3788 }
3789 }
3790
3791 this.update(cx, |this, cx| {
3792 this.diff_stats = combined;
3793 cx.notify();
3794 })
3795 .ok();
3796 });
3797 }
3798
3799 fn header_state(&self, header_type: Section) -> ToggleState {
3800 let (staged_count, count) = match header_type {
3801 Section::New => (self.new_staged_count, self.new_count),
3802 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
3803 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
3804 };
3805 if staged_count == 0 {
3806 ToggleState::Unselected
3807 } else if count == staged_count {
3808 ToggleState::Selected
3809 } else {
3810 ToggleState::Indeterminate
3811 }
3812 }
3813
3814 fn update_counts(&mut self, repo: &Repository) {
3815 self.show_placeholders = false;
3816 self.conflicted_count = 0;
3817 self.conflicted_staged_count = 0;
3818 self.new_count = 0;
3819 self.tracked_count = 0;
3820 self.new_staged_count = 0;
3821 self.tracked_staged_count = 0;
3822 self.entry_count = 0;
3823
3824 for status_entry in self.entries.iter().filter_map(|entry| entry.status_entry()) {
3825 self.entry_count += 1;
3826 let is_staging_or_staged = GitPanel::stage_status_for_entry(status_entry, repo)
3827 .as_bool()
3828 .unwrap_or(true);
3829
3830 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
3831 self.conflicted_count += 1;
3832 if is_staging_or_staged {
3833 self.conflicted_staged_count += 1;
3834 }
3835 } else if status_entry.status.is_created() {
3836 self.new_count += 1;
3837 if is_staging_or_staged {
3838 self.new_staged_count += 1;
3839 }
3840 } else {
3841 self.tracked_count += 1;
3842 if is_staging_or_staged {
3843 self.tracked_staged_count += 1;
3844 }
3845 }
3846 }
3847 }
3848
3849 pub(crate) fn has_staged_changes(&self) -> bool {
3850 self.tracked_staged_count > 0
3851 || self.new_staged_count > 0
3852 || self.conflicted_staged_count > 0
3853 }
3854
3855 pub(crate) fn has_unstaged_changes(&self) -> bool {
3856 self.tracked_count > self.tracked_staged_count
3857 || self.new_count > self.new_staged_count
3858 || self.conflicted_count > self.conflicted_staged_count
3859 }
3860
3861 fn has_tracked_changes(&self) -> bool {
3862 self.tracked_count > 0
3863 }
3864
3865 pub fn has_unstaged_conflicts(&self) -> bool {
3866 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3867 }
3868
3869 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3870 let Some(workspace) = self.workspace.upgrade() else {
3871 return;
3872 };
3873 show_error_toast(workspace, action, e, cx)
3874 }
3875
3876 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3877 where
3878 E: std::fmt::Debug + std::fmt::Display,
3879 {
3880 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3881 let _ = workspace.update(cx, |workspace, cx| {
3882 struct CommitMessageError;
3883 let notification_id = NotificationId::unique::<CommitMessageError>();
3884 workspace.show_notification(notification_id, cx, |cx| {
3885 cx.new(|cx| {
3886 ErrorMessagePrompt::new(
3887 format!("Failed to generate commit message: {err}"),
3888 cx,
3889 )
3890 })
3891 });
3892 });
3893 }
3894 }
3895
3896 fn show_remote_output(
3897 &mut self,
3898 action: RemoteAction,
3899 info: RemoteCommandOutput,
3900 cx: &mut Context<Self>,
3901 ) {
3902 let Some(workspace) = self.workspace.upgrade() else {
3903 return;
3904 };
3905
3906 workspace.update(cx, |workspace, cx| {
3907 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3908 let workspace_weak = cx.weak_entity();
3909 let operation = action.name();
3910
3911 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3912 use remote_output::SuccessStyle::*;
3913 match style {
3914 Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3915 ToastWithLog { output } => this
3916 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3917 .action("View Log", move |window, cx| {
3918 let output = output.clone();
3919 let output =
3920 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3921 workspace_weak
3922 .update(cx, move |workspace, cx| {
3923 open_output(operation, workspace, &output, window, cx)
3924 })
3925 .ok();
3926 }),
3927 PushPrLink { text, link } => this
3928 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3929 .action(text, move |_, cx| cx.open_url(&link)),
3930 }
3931 .dismiss_button(true)
3932 });
3933 workspace.toggle_status_toast(status_toast, cx)
3934 });
3935 }
3936
3937 pub fn can_commit(&self) -> bool {
3938 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3939 }
3940
3941 pub fn can_stage_all(&self) -> bool {
3942 self.has_unstaged_changes()
3943 }
3944
3945 pub fn can_unstage_all(&self) -> bool {
3946 self.has_staged_changes()
3947 }
3948
3949 /// Computes tree indentation depths for visible entries in the given range.
3950 /// Used by indent guides to render vertical connector lines in tree view.
3951 fn compute_visible_depths(&self, range: Range<usize>) -> SmallVec<[usize; 64]> {
3952 let GitPanelViewMode::Tree(state) = &self.view_mode else {
3953 return SmallVec::new();
3954 };
3955
3956 range
3957 .map(|ix| {
3958 state
3959 .logical_indices
3960 .get(ix)
3961 .and_then(|&entry_ix| self.entries.get(entry_ix))
3962 .map_or(0, |entry| entry.depth())
3963 })
3964 .collect()
3965 }
3966
3967 fn status_width_estimate(
3968 tree_view: bool,
3969 entry: &GitStatusEntry,
3970 path_style: PathStyle,
3971 depth: usize,
3972 ) -> usize {
3973 if tree_view {
3974 Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3975 } else {
3976 Self::item_width_estimate(
3977 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3978 entry.display_name(path_style).len(),
3979 0,
3980 )
3981 }
3982 }
3983
3984 fn width_estimate_for_list_entry(
3985 &self,
3986 tree_view: bool,
3987 entry: &GitListEntry,
3988 path_style: PathStyle,
3989 ) -> Option<usize> {
3990 match entry {
3991 GitListEntry::Status(status) => Some(Self::status_width_estimate(
3992 tree_view, status, path_style, 0,
3993 )),
3994 GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3995 tree_view,
3996 &status.entry,
3997 path_style,
3998 status.depth,
3999 )),
4000 GitListEntry::Directory(dir) => {
4001 Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
4002 }
4003 GitListEntry::Header(_) => None,
4004 }
4005 }
4006
4007 fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
4008 path + file_name + depth * 2
4009 }
4010
4011 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
4012 let focus_handle = self.focus_handle.clone();
4013 let has_tracked_changes = self.has_tracked_changes();
4014 let has_staged_changes = self.has_staged_changes();
4015 let has_unstaged_changes = self.has_unstaged_changes();
4016 let has_new_changes = self.new_count > 0;
4017 let has_stash_items = self.stash_entries.entries.len() > 0;
4018
4019 PopoverMenu::new(id.into())
4020 .trigger(
4021 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
4022 .icon_size(IconSize::Small)
4023 .icon_color(Color::Muted),
4024 )
4025 .menu(move |window, cx| {
4026 Some(git_panel_context_menu(
4027 focus_handle.clone(),
4028 GitMenuState {
4029 has_tracked_changes,
4030 has_staged_changes,
4031 has_unstaged_changes,
4032 has_new_changes,
4033 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4034 has_stash_items,
4035 tree_view: GitPanelSettings::get_global(cx).tree_view,
4036 },
4037 window,
4038 cx,
4039 ))
4040 })
4041 .anchor(Corner::TopRight)
4042 }
4043
4044 pub(crate) fn render_generate_commit_message_button(
4045 &self,
4046 cx: &Context<Self>,
4047 ) -> Option<AnyElement> {
4048 if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
4049 return None;
4050 }
4051
4052 if self.generate_commit_message_task.is_some() {
4053 return Some(
4054 h_flex()
4055 .gap_1()
4056 .child(
4057 Icon::new(IconName::ArrowCircle)
4058 .size(IconSize::XSmall)
4059 .color(Color::Info)
4060 .with_rotate_animation(2),
4061 )
4062 .child(
4063 Label::new("Generating Commit…")
4064 .size(LabelSize::Small)
4065 .color(Color::Muted),
4066 )
4067 .into_any_element(),
4068 );
4069 }
4070
4071 let model_registry = LanguageModelRegistry::read_global(cx);
4072 let has_commit_model_configuration_error = model_registry
4073 .configuration_error(model_registry.commit_message_model(), cx)
4074 .is_some();
4075 let can_commit = self.can_commit();
4076
4077 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4078
4079 Some(
4080 IconButton::new("generate-commit-message", IconName::AiEdit)
4081 .shape(ui::IconButtonShape::Square)
4082 .icon_color(if has_commit_model_configuration_error {
4083 Color::Disabled
4084 } else {
4085 Color::Muted
4086 })
4087 .tooltip(move |_window, cx| {
4088 if !can_commit {
4089 Tooltip::simple("No Changes to Commit", cx)
4090 } else if has_commit_model_configuration_error {
4091 Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
4092 } else {
4093 Tooltip::for_action_in(
4094 "Generate Commit Message",
4095 &git::GenerateCommitMessage,
4096 &editor_focus_handle,
4097 cx,
4098 )
4099 }
4100 })
4101 .disabled(!can_commit || has_commit_model_configuration_error)
4102 .on_click(cx.listener(move |this, _event, _window, cx| {
4103 this.generate_commit_message(cx);
4104 }))
4105 .into_any_element(),
4106 )
4107 }
4108
4109 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
4110 let potential_co_authors = self.potential_co_authors(cx);
4111
4112 let (tooltip_label, icon) = if self.add_coauthors {
4113 ("Remove co-authored-by", IconName::Person)
4114 } else {
4115 ("Add co-authored-by", IconName::UserCheck)
4116 };
4117
4118 if potential_co_authors.is_empty() {
4119 None
4120 } else {
4121 Some(
4122 IconButton::new("co-authors", icon)
4123 .shape(ui::IconButtonShape::Square)
4124 .icon_color(Color::Disabled)
4125 .selected_icon_color(Color::Selected)
4126 .toggle_state(self.add_coauthors)
4127 .tooltip(move |_, cx| {
4128 let title = format!(
4129 "{}:{}{}",
4130 tooltip_label,
4131 if potential_co_authors.len() == 1 {
4132 ""
4133 } else {
4134 "\n"
4135 },
4136 potential_co_authors
4137 .iter()
4138 .map(|(name, email)| format!(" {} <{}>", name, email))
4139 .join("\n")
4140 );
4141 Tooltip::simple(title, cx)
4142 })
4143 .on_click(cx.listener(|this, _, _, cx| {
4144 this.add_coauthors = !this.add_coauthors;
4145 cx.notify();
4146 }))
4147 .into_any_element(),
4148 )
4149 }
4150 }
4151
4152 fn render_git_commit_menu(
4153 &self,
4154 id: impl Into<ElementId>,
4155 keybinding_target: Option<FocusHandle>,
4156 cx: &mut Context<Self>,
4157 ) -> impl IntoElement {
4158 PopoverMenu::new(id.into())
4159 .trigger(
4160 ui::ButtonLike::new_rounded_right("commit-split-button-right")
4161 .layer(ui::ElevationIndex::ModalSurface)
4162 .size(ButtonSize::None)
4163 .child(
4164 h_flex()
4165 .px_1()
4166 .h_full()
4167 .justify_center()
4168 .border_l_1()
4169 .border_color(cx.theme().colors().border)
4170 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4171 ),
4172 )
4173 .menu({
4174 let git_panel = cx.entity();
4175 let has_previous_commit = self.head_commit(cx).is_some();
4176 let amend = self.amend_pending();
4177 let signoff = self.signoff_enabled;
4178
4179 move |window, cx| {
4180 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4181 context_menu
4182 .when_some(keybinding_target.clone(), |el, keybinding_target| {
4183 el.context(keybinding_target)
4184 })
4185 .when(has_previous_commit, |this| {
4186 this.toggleable_entry(
4187 "Amend",
4188 amend,
4189 IconPosition::Start,
4190 Some(Box::new(Amend)),
4191 {
4192 let git_panel = git_panel.downgrade();
4193 move |_, cx| {
4194 git_panel
4195 .update(cx, |git_panel, cx| {
4196 git_panel.toggle_amend_pending(cx);
4197 })
4198 .ok();
4199 }
4200 },
4201 )
4202 })
4203 .toggleable_entry(
4204 "Signoff",
4205 signoff,
4206 IconPosition::Start,
4207 Some(Box::new(Signoff)),
4208 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4209 )
4210 }))
4211 }
4212 })
4213 .anchor(Corner::TopRight)
4214 }
4215
4216 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4217 if self.has_unstaged_conflicts() {
4218 (false, "You must resolve conflicts before committing")
4219 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4220 (false, "No changes to commit")
4221 } else if self.pending_commit.is_some() {
4222 (false, "Commit in progress")
4223 } else if !self.has_commit_message(cx) {
4224 (false, "No commit message")
4225 } else if !self.has_write_access(cx) {
4226 (false, "You do not have write access to this project")
4227 } else {
4228 (true, self.commit_button_title())
4229 }
4230 }
4231
4232 pub fn commit_button_title(&self) -> &'static str {
4233 if self.amend_pending {
4234 if self.has_staged_changes() {
4235 "Amend"
4236 } else if self.has_tracked_changes() {
4237 "Amend Tracked"
4238 } else {
4239 "Amend"
4240 }
4241 } else if self.has_staged_changes() {
4242 "Commit"
4243 } else {
4244 "Commit Tracked"
4245 }
4246 }
4247
4248 fn expand_commit_editor(
4249 &mut self,
4250 _: &git::ExpandCommitEditor,
4251 window: &mut Window,
4252 cx: &mut Context<Self>,
4253 ) {
4254 let workspace = self.workspace.clone();
4255 window.defer(cx, move |window, cx| {
4256 workspace
4257 .update(cx, |workspace, cx| {
4258 CommitModal::toggle(workspace, None, window, cx)
4259 })
4260 .ok();
4261 })
4262 }
4263
4264 fn render_panel_header(
4265 &self,
4266 window: &mut Window,
4267 cx: &mut Context<Self>,
4268 ) -> Option<impl IntoElement> {
4269 self.active_repository.as_ref()?;
4270
4271 let (text, action, stage, tooltip) =
4272 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4273 ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4274 } else {
4275 ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4276 };
4277
4278 let change_string = match self.changes_count {
4279 0 => "No Changes".to_string(),
4280 1 => "1 Change".to_string(),
4281 count => format!("{} Changes", count),
4282 };
4283
4284 Some(
4285 self.panel_header_container(window, cx)
4286 .px_2()
4287 .justify_between()
4288 .child(
4289 panel_button(change_string)
4290 .color(Color::Muted)
4291 .tooltip(Tooltip::for_action_title_in(
4292 "Open Diff",
4293 &Diff,
4294 &self.focus_handle,
4295 ))
4296 .on_click(|_, _, cx| {
4297 cx.defer(|cx| {
4298 cx.dispatch_action(&Diff);
4299 })
4300 }),
4301 )
4302 .child(
4303 h_flex()
4304 .gap_1()
4305 .child(self.render_overflow_menu("overflow_menu"))
4306 .child(
4307 panel_filled_button(text)
4308 .tooltip(Tooltip::for_action_title_in(
4309 tooltip,
4310 action.as_ref(),
4311 &self.focus_handle,
4312 ))
4313 .disabled(self.entry_count == 0)
4314 .on_click({
4315 let git_panel = cx.weak_entity();
4316 move |_, _, cx| {
4317 git_panel
4318 .update(cx, |git_panel, cx| {
4319 git_panel.change_all_files_stage(stage, cx);
4320 })
4321 .ok();
4322 }
4323 }),
4324 ),
4325 ),
4326 )
4327 }
4328
4329 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4330 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4331 if !self.can_push_and_pull(cx) {
4332 return None;
4333 }
4334 Some(
4335 h_flex()
4336 .gap_1()
4337 .flex_shrink_0()
4338 .when_some(branch, |this, branch| {
4339 let focus_handle = Some(self.focus_handle(cx));
4340
4341 this.children(render_remote_button(
4342 "remote-button",
4343 &branch,
4344 focus_handle,
4345 true,
4346 ))
4347 })
4348 .into_any_element(),
4349 )
4350 }
4351
4352 pub fn render_footer(
4353 &self,
4354 window: &mut Window,
4355 cx: &mut Context<Self>,
4356 ) -> Option<impl IntoElement> {
4357 let active_repository = self.active_repository.clone()?;
4358 let panel_editor_style = panel_editor_style(true, window, cx);
4359 let enable_coauthors = self.render_co_authors(cx);
4360
4361 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4362 let expand_tooltip_focus_handle = editor_focus_handle;
4363
4364 let branch = active_repository.read(cx).branch.clone();
4365 let head_commit = active_repository.read(cx).head_commit.clone();
4366
4367 let footer_size = px(32.);
4368 let gap = px(9.0);
4369 let max_height = panel_editor_style
4370 .text
4371 .line_height_in_pixels(window.rem_size())
4372 * MAX_PANEL_EDITOR_LINES
4373 + gap;
4374
4375 let git_panel = cx.entity();
4376 let display_name = SharedString::from(Arc::from(
4377 active_repository
4378 .read(cx)
4379 .display_name()
4380 .trim_end_matches("/"),
4381 ));
4382 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4383 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4384 });
4385
4386 let footer = v_flex()
4387 .child(PanelRepoFooter::new(
4388 display_name,
4389 branch,
4390 head_commit,
4391 Some(git_panel),
4392 ))
4393 .child(
4394 panel_editor_container(window, cx)
4395 .id("commit-editor-container")
4396 .relative()
4397 .w_full()
4398 .h(max_height + footer_size)
4399 .border_t_1()
4400 .border_color(cx.theme().colors().border)
4401 .cursor_text()
4402 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4403 window.focus(&this.commit_editor.focus_handle(cx), cx);
4404 }))
4405 .child(
4406 h_flex()
4407 .id("commit-footer")
4408 .border_t_1()
4409 .when(editor_is_long, |el| {
4410 el.border_color(cx.theme().colors().border_variant)
4411 })
4412 .absolute()
4413 .bottom_0()
4414 .left_0()
4415 .w_full()
4416 .px_2()
4417 .h(footer_size)
4418 .flex_none()
4419 .justify_between()
4420 .child(
4421 self.render_generate_commit_message_button(cx)
4422 .unwrap_or_else(|| div().into_any_element()),
4423 )
4424 .child(
4425 h_flex()
4426 .gap_0p5()
4427 .children(enable_coauthors)
4428 .child(self.render_commit_button(cx)),
4429 ),
4430 )
4431 .child(
4432 div()
4433 .pr_2p5()
4434 .on_action(|&zed_actions::editor::MoveUp, _, cx| {
4435 cx.stop_propagation();
4436 })
4437 .on_action(|&zed_actions::editor::MoveDown, _, cx| {
4438 cx.stop_propagation();
4439 })
4440 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4441 )
4442 .child(
4443 h_flex()
4444 .absolute()
4445 .top_2()
4446 .right_2()
4447 .opacity(0.5)
4448 .hover(|this| this.opacity(1.0))
4449 .child(
4450 panel_icon_button("expand-commit-editor", IconName::Maximize)
4451 .icon_size(IconSize::Small)
4452 .size(ui::ButtonSize::Default)
4453 .tooltip(move |_window, cx| {
4454 Tooltip::for_action_in(
4455 "Open Commit Modal",
4456 &git::ExpandCommitEditor,
4457 &expand_tooltip_focus_handle,
4458 cx,
4459 )
4460 })
4461 .on_click(cx.listener({
4462 move |_, _, window, cx| {
4463 window.dispatch_action(
4464 git::ExpandCommitEditor.boxed_clone(),
4465 cx,
4466 )
4467 }
4468 })),
4469 ),
4470 ),
4471 );
4472
4473 Some(footer)
4474 }
4475
4476 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4477 let (can_commit, tooltip) = self.configure_commit_button(cx);
4478 let title = self.commit_button_title();
4479 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4480 let amend = self.amend_pending();
4481 let signoff = self.signoff_enabled;
4482
4483 let label_color = if self.pending_commit.is_some() {
4484 Color::Disabled
4485 } else {
4486 Color::Default
4487 };
4488
4489 div()
4490 .id("commit-wrapper")
4491 .on_hover(cx.listener(move |this, hovered, _, cx| {
4492 this.show_placeholders =
4493 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4494 cx.notify()
4495 }))
4496 .child(SplitButton::new(
4497 ButtonLike::new_rounded_left(ElementId::Name(
4498 format!("split-button-left-{}", title).into(),
4499 ))
4500 .layer(ElevationIndex::ModalSurface)
4501 .size(ButtonSize::Compact)
4502 .child(
4503 Label::new(title)
4504 .size(LabelSize::Small)
4505 .color(label_color)
4506 .mr_0p5(),
4507 )
4508 .on_click({
4509 let git_panel = cx.weak_entity();
4510 move |_, window, cx| {
4511 telemetry::event!("Git Committed", source = "Git Panel");
4512 git_panel
4513 .update(cx, |git_panel, cx| {
4514 git_panel.commit_changes(
4515 CommitOptions { amend, signoff },
4516 window,
4517 cx,
4518 );
4519 })
4520 .ok();
4521 }
4522 })
4523 .disabled(!can_commit || self.modal_open)
4524 .tooltip({
4525 let handle = commit_tooltip_focus_handle.clone();
4526 move |_window, cx| {
4527 if can_commit {
4528 Tooltip::with_meta_in(
4529 tooltip,
4530 Some(if amend { &git::Amend } else { &git::Commit }),
4531 format!(
4532 "git commit{}{}",
4533 if amend { " --amend" } else { "" },
4534 if signoff { " --signoff" } else { "" }
4535 ),
4536 &handle.clone(),
4537 cx,
4538 )
4539 } else {
4540 Tooltip::simple(tooltip, cx)
4541 }
4542 }
4543 }),
4544 self.render_git_commit_menu(
4545 ElementId::Name(format!("split-button-right-{}", title).into()),
4546 Some(commit_tooltip_focus_handle),
4547 cx,
4548 )
4549 .into_any_element(),
4550 ))
4551 }
4552
4553 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4554 h_flex()
4555 .py_1p5()
4556 .px_2()
4557 .gap_1p5()
4558 .justify_between()
4559 .border_t_1()
4560 .border_color(cx.theme().colors().border.opacity(0.8))
4561 .child(
4562 div()
4563 .flex_grow()
4564 .overflow_hidden()
4565 .max_w(relative(0.85))
4566 .child(
4567 Label::new("This will update your most recent commit.")
4568 .size(LabelSize::Small)
4569 .truncate(),
4570 ),
4571 )
4572 .child(
4573 panel_button("Cancel")
4574 .size(ButtonSize::Default)
4575 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4576 )
4577 }
4578
4579 fn render_previous_commit(
4580 &self,
4581 window: &mut Window,
4582 cx: &mut Context<Self>,
4583 ) -> Option<impl IntoElement> {
4584 let active_repository = self.active_repository.as_ref()?;
4585 let branch = active_repository.read(cx).branch.as_ref()?;
4586 let commit = branch.most_recent_commit.as_ref()?.clone();
4587 let workspace = self.workspace.clone();
4588 let this = cx.entity();
4589
4590 Some(
4591 h_flex()
4592 .p_1p5()
4593 .gap_1p5()
4594 .justify_between()
4595 .border_t_1()
4596 .border_color(cx.theme().colors().border.opacity(0.8))
4597 .child(
4598 div()
4599 .id("commit-msg-hover")
4600 .cursor_pointer()
4601 .px_1()
4602 .rounded_sm()
4603 .line_clamp(1)
4604 .hover(|s| s.bg(cx.theme().colors().element_hover))
4605 .child(
4606 Label::new(commit.subject.clone())
4607 .size(LabelSize::Small)
4608 .truncate(),
4609 )
4610 .on_click({
4611 let commit = commit.clone();
4612 let repo = active_repository.downgrade();
4613 move |_, window, cx| {
4614 CommitView::open(
4615 commit.sha.to_string(),
4616 repo.clone(),
4617 workspace.clone(),
4618 None,
4619 None,
4620 window,
4621 cx,
4622 );
4623 }
4624 })
4625 .hoverable_tooltip({
4626 let repo = active_repository.clone();
4627 move |window, cx| {
4628 GitPanelMessageTooltip::new(
4629 this.clone(),
4630 commit.sha.clone(),
4631 repo.clone(),
4632 window,
4633 cx,
4634 )
4635 .into()
4636 }
4637 }),
4638 )
4639 .child(
4640 h_flex()
4641 .gap_0p5()
4642 .when(commit.has_parent, |this| {
4643 let has_unstaged = self.has_unstaged_changes();
4644 this.child(
4645 panel_icon_button("undo", IconName::Undo)
4646 .icon_size(IconSize::Small)
4647 .tooltip(move |_window, cx| {
4648 Tooltip::with_meta(
4649 "Uncommit",
4650 Some(&git::Uncommit),
4651 if has_unstaged {
4652 "git reset HEAD^ --soft"
4653 } else {
4654 "git reset HEAD^"
4655 },
4656 cx,
4657 )
4658 })
4659 .on_click(
4660 cx.listener(|this, _, window, cx| {
4661 this.uncommit(window, cx)
4662 }),
4663 ),
4664 )
4665 })
4666 .when(window.is_action_available(&Open, cx), |this| {
4667 this.child(
4668 panel_icon_button("git-graph-button", IconName::GitGraph)
4669 .icon_size(IconSize::Small)
4670 .tooltip(|_window, cx| {
4671 Tooltip::for_action("Open Git Graph", &Open, cx)
4672 })
4673 .on_click(|_, window, cx| {
4674 window.dispatch_action(Open.boxed_clone(), cx)
4675 }),
4676 )
4677 }),
4678 ),
4679 )
4680 }
4681
4682 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4683 let has_repo = self.active_repository.is_some();
4684 let has_no_repo = self.active_repository.is_none();
4685 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4686
4687 let should_show_branch_diff =
4688 has_repo && self.changes_count == 0 && !self.is_on_main_branch(cx);
4689
4690 let label = if has_repo {
4691 "No changes to commit"
4692 } else {
4693 "No Git repositories"
4694 };
4695
4696 v_flex()
4697 .gap_1p5()
4698 .flex_1()
4699 .items_center()
4700 .justify_center()
4701 .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4702 .when(has_no_repo && worktree_count > 0, |this| {
4703 this.child(
4704 panel_filled_button("Initialize Repository")
4705 .tooltip(Tooltip::for_action_title_in(
4706 "git init",
4707 &git::Init,
4708 &self.focus_handle,
4709 ))
4710 .on_click(move |_, _, cx| {
4711 cx.defer(move |cx| {
4712 cx.dispatch_action(&git::Init);
4713 })
4714 }),
4715 )
4716 })
4717 .when(should_show_branch_diff, |this| {
4718 this.child(
4719 panel_filled_button("View Branch Diff")
4720 .tooltip(move |_, cx| {
4721 Tooltip::with_meta(
4722 "Branch Diff",
4723 Some(&BranchDiff),
4724 "Show diff between working directory and default branch",
4725 cx,
4726 )
4727 })
4728 .on_click(move |_, _, cx| {
4729 cx.defer(move |cx| {
4730 cx.dispatch_action(&BranchDiff);
4731 })
4732 }),
4733 )
4734 })
4735 }
4736
4737 fn is_on_main_branch(&self, cx: &Context<Self>) -> bool {
4738 let Some(repo) = self.active_repository.as_ref() else {
4739 return false;
4740 };
4741
4742 let Some(branch) = repo.read(cx).branch.as_ref() else {
4743 return false;
4744 };
4745
4746 let branch_name = branch.name();
4747 matches!(branch_name, "main" | "master")
4748 }
4749
4750 fn render_buffer_header_controls(
4751 &self,
4752 entity: &Entity<Self>,
4753 file: &Arc<dyn File>,
4754 _: &Window,
4755 cx: &App,
4756 ) -> Option<AnyElement> {
4757 let repo = self.active_repository.as_ref()?.read(cx);
4758 let project_path = (file.worktree_id(cx), file.path().clone()).into();
4759 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4760 let ix = self.entry_by_path(&repo_path)?;
4761 let entry = self.entries.get(ix)?;
4762
4763 let is_staging_or_staged = repo
4764 .pending_ops_for_path(&repo_path)
4765 .map(|ops| ops.staging() || ops.staged())
4766 .or_else(|| {
4767 repo.status_for_path(&repo_path)
4768 .and_then(|status| status.status.staging().as_bool())
4769 })
4770 .or_else(|| {
4771 entry
4772 .status_entry()
4773 .and_then(|entry| entry.staging.as_bool())
4774 });
4775
4776 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4777 .disabled(!self.has_write_access(cx))
4778 .fill()
4779 .elevation(ElevationIndex::Surface)
4780 .on_click({
4781 let entry = entry.clone();
4782 let git_panel = entity.downgrade();
4783 move |_, window, cx| {
4784 git_panel
4785 .update(cx, |this, cx| {
4786 this.toggle_staged_for_entry(&entry, window, cx);
4787 cx.stop_propagation();
4788 })
4789 .ok();
4790 }
4791 });
4792 Some(
4793 h_flex()
4794 .id("start-slot")
4795 .text_lg()
4796 .child(checkbox)
4797 .on_mouse_down(MouseButton::Left, |_, _, cx| {
4798 // prevent the list item active state triggering when toggling checkbox
4799 cx.stop_propagation();
4800 })
4801 .into_any_element(),
4802 )
4803 }
4804
4805 fn render_entries(
4806 &self,
4807 has_write_access: bool,
4808 repo: Entity<Repository>,
4809 window: &mut Window,
4810 cx: &mut Context<Self>,
4811 ) -> impl IntoElement {
4812 let (is_tree_view, entry_count) = match &self.view_mode {
4813 GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4814 GitPanelViewMode::Flat => (false, self.entries.len()),
4815 };
4816 let repo = repo.downgrade();
4817
4818 v_flex()
4819 .flex_1()
4820 .size_full()
4821 .overflow_hidden()
4822 .relative()
4823 .child(
4824 h_flex()
4825 .flex_1()
4826 .size_full()
4827 .relative()
4828 .overflow_hidden()
4829 .child(
4830 uniform_list(
4831 "entries",
4832 entry_count,
4833 cx.processor(move |this, range: Range<usize>, window, cx| {
4834 let Some(repo) = repo.upgrade() else {
4835 return Vec::new();
4836 };
4837 let repo = repo.read(cx);
4838
4839 let mut items = Vec::with_capacity(range.end - range.start);
4840
4841 for ix in range.into_iter().map(|ix| match &this.view_mode {
4842 GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4843 GitPanelViewMode::Flat => ix,
4844 }) {
4845 match &this.entries.get(ix) {
4846 Some(GitListEntry::Status(entry)) => {
4847 items.push(this.render_status_entry(
4848 ix,
4849 entry,
4850 0,
4851 has_write_access,
4852 repo,
4853 window,
4854 cx,
4855 ));
4856 }
4857 Some(GitListEntry::TreeStatus(entry)) => {
4858 items.push(this.render_status_entry(
4859 ix,
4860 &entry.entry,
4861 entry.depth,
4862 has_write_access,
4863 repo,
4864 window,
4865 cx,
4866 ));
4867 }
4868 Some(GitListEntry::Directory(entry)) => {
4869 items.push(this.render_directory_entry(
4870 ix,
4871 entry,
4872 has_write_access,
4873 window,
4874 cx,
4875 ));
4876 }
4877 Some(GitListEntry::Header(header)) => {
4878 items.push(this.render_list_header(
4879 ix,
4880 header,
4881 has_write_access,
4882 window,
4883 cx,
4884 ));
4885 }
4886 None => {}
4887 }
4888 }
4889
4890 items
4891 }),
4892 )
4893 .when(is_tree_view, |list| {
4894 let indent_size = px(TREE_INDENT);
4895 list.with_decoration(
4896 ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4897 .with_compute_indents_fn(
4898 cx.entity(),
4899 |this, range, _window, _cx| {
4900 this.compute_visible_depths(range)
4901 },
4902 )
4903 .with_render_fn(cx.entity(), |_, params, _, _| {
4904 // Magic number to align the tree item is 3 here
4905 // because we're using 12px as the left-side padding
4906 // and 3 makes the alignment work with the bounding box of the icon
4907 let left_offset = px(TREE_INDENT + 3_f32);
4908 let indent_size = params.indent_size;
4909 let item_height = params.item_height;
4910
4911 params
4912 .indent_guides
4913 .into_iter()
4914 .map(|layout| {
4915 let bounds = Bounds::new(
4916 point(
4917 layout.offset.x * indent_size + left_offset,
4918 layout.offset.y * item_height,
4919 ),
4920 size(px(1.), layout.length * item_height),
4921 );
4922 RenderedIndentGuide {
4923 bounds,
4924 layout,
4925 is_active: false,
4926 hitbox: None,
4927 }
4928 })
4929 .collect()
4930 }),
4931 )
4932 })
4933 .size_full()
4934 .flex_grow()
4935 .with_width_from_item(self.max_width_item_index)
4936 .track_scroll(&self.scroll_handle),
4937 )
4938 .on_mouse_down(
4939 MouseButton::Right,
4940 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4941 this.deploy_panel_context_menu(event.position, window, cx)
4942 }),
4943 )
4944 .custom_scrollbars(
4945 Scrollbars::for_settings::<GitPanelSettings>()
4946 .tracked_scroll_handle(&self.scroll_handle)
4947 .with_track_along(
4948 ScrollAxes::Horizontal,
4949 cx.theme().colors().panel_background,
4950 ),
4951 window,
4952 cx,
4953 ),
4954 )
4955 }
4956
4957 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4958 Label::new(label.into()).color(color)
4959 }
4960
4961 fn list_item_height(&self) -> Rems {
4962 rems(1.75)
4963 }
4964
4965 fn render_list_header(
4966 &self,
4967 ix: usize,
4968 header: &GitHeaderEntry,
4969 _: bool,
4970 _: &Window,
4971 _: &Context<Self>,
4972 ) -> AnyElement {
4973 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4974
4975 h_flex()
4976 .id(id)
4977 .h(self.list_item_height())
4978 .w_full()
4979 .items_end()
4980 .px_3()
4981 .pb_1()
4982 .child(
4983 Label::new(header.title())
4984 .color(Color::Muted)
4985 .size(LabelSize::Small)
4986 .line_height_style(LineHeightStyle::UiLabel)
4987 .single_line(),
4988 )
4989 .into_any_element()
4990 }
4991
4992 pub fn load_commit_details(
4993 &self,
4994 sha: String,
4995 cx: &mut Context<Self>,
4996 ) -> Task<anyhow::Result<CommitDetails>> {
4997 let Some(repo) = self.active_repository.clone() else {
4998 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4999 };
5000 repo.update(cx, |repo, cx| {
5001 let show = repo.show(sha);
5002 cx.spawn(async move |_, _| show.await?)
5003 })
5004 }
5005
5006 fn deploy_entry_context_menu(
5007 &mut self,
5008 position: Point<Pixels>,
5009 ix: usize,
5010 window: &mut Window,
5011 cx: &mut Context<Self>,
5012 ) {
5013 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
5014 return;
5015 };
5016 let stage_title = if entry.status.staging().is_fully_staged() {
5017 "Unstage File"
5018 } else {
5019 "Stage File"
5020 };
5021 let restore_title = if entry.status.is_created() {
5022 "Trash File"
5023 } else {
5024 "Discard Changes"
5025 };
5026 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
5027 let is_created = entry.status.is_created();
5028 context_menu
5029 .context(self.focus_handle.clone())
5030 .action(stage_title, ToggleStaged.boxed_clone())
5031 .action(restore_title, git::RestoreFile::default().boxed_clone())
5032 .action_disabled_when(
5033 !is_created,
5034 "Add to .gitignore",
5035 git::AddToGitignore.boxed_clone(),
5036 )
5037 .separator()
5038 .action("Open Diff", menu::Confirm.boxed_clone())
5039 .action("Open File", menu::SecondaryConfirm.boxed_clone())
5040 .separator()
5041 .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
5042 });
5043 self.selected_entry = Some(ix);
5044 self.set_context_menu(context_menu, position, window, cx);
5045 }
5046
5047 fn deploy_panel_context_menu(
5048 &mut self,
5049 position: Point<Pixels>,
5050 window: &mut Window,
5051 cx: &mut Context<Self>,
5052 ) {
5053 let context_menu = git_panel_context_menu(
5054 self.focus_handle.clone(),
5055 GitMenuState {
5056 has_tracked_changes: self.has_tracked_changes(),
5057 has_staged_changes: self.has_staged_changes(),
5058 has_unstaged_changes: self.has_unstaged_changes(),
5059 has_new_changes: self.new_count > 0,
5060 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
5061 has_stash_items: self.stash_entries.entries.len() > 0,
5062 tree_view: GitPanelSettings::get_global(cx).tree_view,
5063 },
5064 window,
5065 cx,
5066 );
5067 self.set_context_menu(context_menu, position, window, cx);
5068 }
5069
5070 fn set_context_menu(
5071 &mut self,
5072 context_menu: Entity<ContextMenu>,
5073 position: Point<Pixels>,
5074 window: &Window,
5075 cx: &mut Context<Self>,
5076 ) {
5077 let subscription = cx.subscribe_in(
5078 &context_menu,
5079 window,
5080 |this, _, _: &DismissEvent, window, cx| {
5081 if this.context_menu.as_ref().is_some_and(|context_menu| {
5082 context_menu.0.focus_handle(cx).contains_focused(window, cx)
5083 }) {
5084 cx.focus_self(window);
5085 }
5086 this.context_menu.take();
5087 cx.notify();
5088 },
5089 );
5090 self.context_menu = Some((context_menu, position, subscription));
5091 cx.notify();
5092 }
5093
5094 fn render_status_entry(
5095 &self,
5096 ix: usize,
5097 entry: &GitStatusEntry,
5098 depth: usize,
5099 has_write_access: bool,
5100 repo: &Repository,
5101 window: &Window,
5102 cx: &Context<Self>,
5103 ) -> AnyElement {
5104 let tree_view = GitPanelSettings::get_global(cx).tree_view;
5105 let path_style = self.project.read(cx).path_style(cx);
5106 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
5107 let display_name = entry.display_name(path_style);
5108
5109 let selected = self.selected_entry == Some(ix);
5110 let marked = self.marked_entries.contains(&ix);
5111 let status_style = GitPanelSettings::get_global(cx).status_style;
5112 let status = entry.status;
5113
5114 let has_conflict = status.is_conflicted();
5115 let is_modified = status.is_modified();
5116 let is_deleted = status.is_deleted();
5117 let is_created = status.is_created();
5118
5119 let label_color = if status_style == StatusStyle::LabelColor {
5120 if has_conflict {
5121 Color::VersionControlConflict
5122 } else if is_created {
5123 Color::VersionControlAdded
5124 } else if is_modified {
5125 Color::VersionControlModified
5126 } else if is_deleted {
5127 // We don't want a bunch of red labels in the list
5128 Color::Disabled
5129 } else {
5130 Color::VersionControlAdded
5131 }
5132 } else {
5133 Color::Default
5134 };
5135
5136 let path_color = if status.is_deleted() {
5137 Color::Disabled
5138 } else {
5139 Color::Muted
5140 };
5141
5142 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
5143 let checkbox_wrapper_id: ElementId =
5144 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
5145 let checkbox_id: ElementId =
5146 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5147
5148 let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5149 let mut is_staged: ToggleState = match stage_status {
5150 StageStatus::Staged => ToggleState::Selected,
5151 StageStatus::Unstaged => ToggleState::Unselected,
5152 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5153 };
5154 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5155 is_staged = ToggleState::Selected;
5156 }
5157
5158 let handle = cx.weak_entity();
5159
5160 let selected_bg_alpha = 0.08;
5161 let marked_bg_alpha = 0.12;
5162 let state_opacity_step = 0.04;
5163
5164 let info_color = cx.theme().status().info;
5165
5166 let base_bg = match (selected, marked) {
5167 (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5168 (true, false) => info_color.alpha(selected_bg_alpha),
5169 (false, true) => info_color.alpha(marked_bg_alpha),
5170 _ => cx.theme().colors().ghost_element_background,
5171 };
5172
5173 let (hover_bg, active_bg) = if selected {
5174 (
5175 info_color.alpha(selected_bg_alpha + state_opacity_step),
5176 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5177 )
5178 } else {
5179 (
5180 cx.theme().colors().ghost_element_hover,
5181 cx.theme().colors().ghost_element_active,
5182 )
5183 };
5184
5185 let name_row = h_flex()
5186 .min_w_0()
5187 .flex_1()
5188 .gap_1()
5189 .child(git_status_icon(status))
5190 .map(|this| {
5191 if tree_view {
5192 this.pl(px(depth as f32 * TREE_INDENT)).child(
5193 self.entry_label(display_name, label_color)
5194 .when(status.is_deleted(), Label::strikethrough)
5195 .truncate(),
5196 )
5197 } else {
5198 this.child(self.path_formatted(
5199 entry.parent_dir(path_style),
5200 path_color,
5201 display_name,
5202 label_color,
5203 path_style,
5204 git_path_style,
5205 status.is_deleted(),
5206 ))
5207 }
5208 });
5209
5210 let id_for_diff_stat = id.clone();
5211
5212 h_flex()
5213 .id(id)
5214 .h(self.list_item_height())
5215 .w_full()
5216 .pl_3()
5217 .pr_1()
5218 .gap_1p5()
5219 .border_1()
5220 .border_r_2()
5221 .when(selected && self.focus_handle.is_focused(window), |el| {
5222 el.border_color(cx.theme().colors().panel_focused_border)
5223 })
5224 .bg(base_bg)
5225 .hover(|s| s.bg(hover_bg))
5226 .active(|s| s.bg(active_bg))
5227 .child(name_row)
5228 .when(GitPanelSettings::get_global(cx).diff_stats, |el| {
5229 el.when_some(
5230 self.diff_stats.get(&entry.repo_path).copied(),
5231 move |this, stat| {
5232 let id = format!("diff-stat-{}", id_for_diff_stat);
5233 this.child(ui::DiffStat::new(
5234 id,
5235 stat.added as usize,
5236 stat.deleted as usize,
5237 ))
5238 },
5239 )
5240 })
5241 .child(
5242 div()
5243 .id(checkbox_wrapper_id)
5244 .flex_none()
5245 .occlude()
5246 .cursor_pointer()
5247 .child(
5248 Checkbox::new(checkbox_id, is_staged)
5249 .disabled(!has_write_access)
5250 .fill()
5251 .elevation(ElevationIndex::Surface)
5252 .on_click_ext({
5253 let entry = entry.clone();
5254 let this = cx.weak_entity();
5255 move |_, click, window, cx| {
5256 this.update(cx, |this, cx| {
5257 if !has_write_access {
5258 return;
5259 }
5260 if click.modifiers().shift {
5261 this.stage_bulk(ix, cx);
5262 } else {
5263 let list_entry =
5264 if GitPanelSettings::get_global(cx).tree_view {
5265 GitListEntry::TreeStatus(GitTreeStatusEntry {
5266 entry: entry.clone(),
5267 depth,
5268 })
5269 } else {
5270 GitListEntry::Status(entry.clone())
5271 };
5272 this.toggle_staged_for_entry(&list_entry, window, cx);
5273 }
5274 cx.stop_propagation();
5275 })
5276 .ok();
5277 }
5278 })
5279 .tooltip(move |_window, cx| {
5280 let action = match stage_status {
5281 StageStatus::Staged => "Unstage",
5282 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5283 };
5284 let tooltip_name = action.to_string();
5285
5286 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5287 }),
5288 ),
5289 )
5290 .on_click({
5291 cx.listener(move |this, event: &ClickEvent, window, cx| {
5292 this.selected_entry = Some(ix);
5293 cx.notify();
5294 if event.click_count() > 1 || event.modifiers().secondary() {
5295 this.open_file(&Default::default(), window, cx)
5296 } else {
5297 this.open_diff(&Default::default(), window, cx);
5298 this.focus_handle.focus(window, cx);
5299 }
5300 })
5301 })
5302 .on_mouse_down(
5303 MouseButton::Right,
5304 move |event: &MouseDownEvent, window, cx| {
5305 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5306 if event.button != MouseButton::Right {
5307 return;
5308 }
5309
5310 let Some(this) = handle.upgrade() else {
5311 return;
5312 };
5313 this.update(cx, |this, cx| {
5314 this.deploy_entry_context_menu(event.position, ix, window, cx);
5315 });
5316 cx.stop_propagation();
5317 },
5318 )
5319 .into_any_element()
5320 }
5321
5322 fn render_directory_entry(
5323 &self,
5324 ix: usize,
5325 entry: &GitTreeDirEntry,
5326 has_write_access: bool,
5327 window: &Window,
5328 cx: &Context<Self>,
5329 ) -> AnyElement {
5330 // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5331 let selected = self.selected_entry == Some(ix);
5332 let label_color = Color::Muted;
5333
5334 let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5335 let checkbox_id: ElementId =
5336 ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5337 let checkbox_wrapper_id: ElementId =
5338 ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5339
5340 let selected_bg_alpha = 0.08;
5341 let state_opacity_step = 0.04;
5342
5343 let info_color = cx.theme().status().info;
5344 let colors = cx.theme().colors();
5345
5346 let (base_bg, hover_bg, active_bg) = if selected {
5347 (
5348 info_color.alpha(selected_bg_alpha),
5349 info_color.alpha(selected_bg_alpha + state_opacity_step),
5350 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5351 )
5352 } else {
5353 (
5354 colors.ghost_element_background,
5355 colors.ghost_element_hover,
5356 colors.ghost_element_active,
5357 )
5358 };
5359
5360 let folder_icon = if entry.expanded {
5361 IconName::FolderOpen
5362 } else {
5363 IconName::Folder
5364 };
5365
5366 let stage_status = if let Some(repo) = &self.active_repository {
5367 self.stage_status_for_directory(entry, repo.read(cx))
5368 } else {
5369 util::debug_panic!(
5370 "Won't have entries to render without an active repository in Git Panel"
5371 );
5372 StageStatus::PartiallyStaged
5373 };
5374
5375 let toggle_state: ToggleState = match stage_status {
5376 StageStatus::Staged => ToggleState::Selected,
5377 StageStatus::Unstaged => ToggleState::Unselected,
5378 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5379 };
5380
5381 let name_row = h_flex()
5382 .min_w_0()
5383 .gap_1()
5384 .pl(px(entry.depth as f32 * TREE_INDENT))
5385 .child(
5386 Icon::new(folder_icon)
5387 .size(IconSize::Small)
5388 .color(Color::Muted),
5389 )
5390 .child(self.entry_label(entry.name.clone(), label_color).truncate());
5391
5392 h_flex()
5393 .id(id)
5394 .h(self.list_item_height())
5395 .min_w_0()
5396 .w_full()
5397 .pl_3()
5398 .pr_1()
5399 .gap_1p5()
5400 .justify_between()
5401 .border_1()
5402 .border_r_2()
5403 .when(selected && self.focus_handle.is_focused(window), |el| {
5404 el.border_color(cx.theme().colors().panel_focused_border)
5405 })
5406 .bg(base_bg)
5407 .hover(|s| s.bg(hover_bg))
5408 .active(|s| s.bg(active_bg))
5409 .child(name_row)
5410 .child(
5411 div()
5412 .id(checkbox_wrapper_id)
5413 .flex_none()
5414 .occlude()
5415 .cursor_pointer()
5416 .child(
5417 Checkbox::new(checkbox_id, toggle_state)
5418 .disabled(!has_write_access)
5419 .fill()
5420 .elevation(ElevationIndex::Surface)
5421 .on_click({
5422 let entry = entry.clone();
5423 let this = cx.weak_entity();
5424 move |_, window, cx| {
5425 this.update(cx, |this, cx| {
5426 if !has_write_access {
5427 return;
5428 }
5429 this.toggle_staged_for_entry(
5430 &GitListEntry::Directory(entry.clone()),
5431 window,
5432 cx,
5433 );
5434 cx.stop_propagation();
5435 })
5436 .ok();
5437 }
5438 })
5439 .tooltip(move |_window, cx| {
5440 let action = match stage_status {
5441 StageStatus::Staged => "Unstage",
5442 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5443 };
5444 Tooltip::simple(format!("{action} folder"), cx)
5445 }),
5446 ),
5447 )
5448 .on_click({
5449 let key = entry.key.clone();
5450 cx.listener(move |this, _event: &ClickEvent, window, cx| {
5451 this.selected_entry = Some(ix);
5452 this.toggle_directory(&key, window, cx);
5453 })
5454 })
5455 .into_any_element()
5456 }
5457
5458 fn path_formatted(
5459 &self,
5460 directory: Option<String>,
5461 path_color: Color,
5462 file_name: String,
5463 label_color: Color,
5464 path_style: PathStyle,
5465 git_path_style: GitPathStyle,
5466 strikethrough: bool,
5467 ) -> Div {
5468 let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5469 let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5470
5471 let file_name = format!("{} ", file_name);
5472
5473 h_flex()
5474 .min_w_0()
5475 .overflow_hidden()
5476 .when(file_path_first, |this| this.flex_row_reverse())
5477 .child(
5478 div().flex_none().child(
5479 self.entry_label(file_name, label_color)
5480 .when(strikethrough, Label::strikethrough),
5481 ),
5482 )
5483 .when_some(directory, |this, dir| {
5484 let path_name = if file_name_first {
5485 dir
5486 } else {
5487 format!("{dir}{}", path_style.primary_separator())
5488 };
5489
5490 this.child(
5491 self.entry_label(path_name, path_color)
5492 .truncate_start()
5493 .when(strikethrough, Label::strikethrough),
5494 )
5495 })
5496 }
5497
5498 fn has_write_access(&self, cx: &App) -> bool {
5499 !self.project.read(cx).is_read_only(cx)
5500 }
5501
5502 pub fn amend_pending(&self) -> bool {
5503 self.amend_pending
5504 }
5505
5506 /// Sets the pending amend state, ensuring that the original commit message
5507 /// is either saved, when `value` is `true` and there's no pending amend, or
5508 /// restored, when `value` is `false` and there's a pending amend.
5509 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5510 if value && !self.amend_pending {
5511 let current_message = self.commit_message_buffer(cx).read(cx).text();
5512 self.original_commit_message = if current_message.trim().is_empty() {
5513 None
5514 } else {
5515 Some(current_message)
5516 };
5517 } else if !value && self.amend_pending {
5518 let message = self.original_commit_message.take().unwrap_or_default();
5519 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5520 let start = buffer.anchor_before(0);
5521 let end = buffer.anchor_after(buffer.len());
5522 buffer.edit([(start..end, message)], None, cx);
5523 });
5524 }
5525
5526 self.amend_pending = value;
5527 self.serialize(cx);
5528 cx.notify();
5529 }
5530
5531 pub fn signoff_enabled(&self) -> bool {
5532 self.signoff_enabled
5533 }
5534
5535 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5536 self.signoff_enabled = value;
5537 self.serialize(cx);
5538 cx.notify();
5539 }
5540
5541 pub fn toggle_signoff_enabled(
5542 &mut self,
5543 _: &Signoff,
5544 _window: &mut Window,
5545 cx: &mut Context<Self>,
5546 ) {
5547 self.set_signoff_enabled(!self.signoff_enabled, cx);
5548 }
5549
5550 pub async fn load(
5551 workspace: WeakEntity<Workspace>,
5552 mut cx: AsyncWindowContext,
5553 ) -> anyhow::Result<Entity<Self>> {
5554 let serialized_panel = match workspace
5555 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
5556 .ok()
5557 .flatten()
5558 {
5559 Some(serialization_key) => cx
5560 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
5561 .await
5562 .context("loading git panel")
5563 .log_err()
5564 .flatten()
5565 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5566 .transpose()
5567 .log_err()
5568 .flatten(),
5569 None => None,
5570 };
5571
5572 workspace.update_in(&mut cx, |workspace, window, cx| {
5573 let panel = GitPanel::new(workspace, window, cx);
5574
5575 if let Some(serialized_panel) = serialized_panel {
5576 panel.update(cx, |panel, cx| {
5577 panel.width = serialized_panel.width;
5578 panel.amend_pending = serialized_panel.amend_pending;
5579 panel.signoff_enabled = serialized_panel.signoff_enabled;
5580 cx.notify();
5581 })
5582 }
5583
5584 panel
5585 })
5586 }
5587
5588 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5589 let Some(op) = self.bulk_staging.as_ref() else {
5590 return;
5591 };
5592 let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5593 return;
5594 };
5595 if let Some(entry) = self.entries.get(index)
5596 && let Some(entry) = entry.status_entry()
5597 {
5598 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5599 }
5600 if index < anchor_index {
5601 std::mem::swap(&mut index, &mut anchor_index);
5602 }
5603 let entries = self
5604 .entries
5605 .get(anchor_index..=index)
5606 .unwrap_or_default()
5607 .iter()
5608 .filter_map(|entry| entry.status_entry().cloned())
5609 .collect::<Vec<_>>();
5610 self.change_file_stage(true, entries, cx);
5611 }
5612
5613 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5614 let Some(repo) = self.active_repository.as_ref() else {
5615 return;
5616 };
5617 self.bulk_staging = Some(BulkStaging {
5618 repo_id: repo.read(cx).id,
5619 anchor: path,
5620 });
5621 }
5622
5623 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5624 self.set_amend_pending(!self.amend_pending, cx);
5625 if self.amend_pending {
5626 self.load_last_commit_message(cx);
5627 }
5628 }
5629}
5630
5631impl Render for GitPanel {
5632 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5633 let project = self.project.read(cx);
5634 let has_entries = !self.entries.is_empty();
5635 let room = self.workspace.upgrade().and_then(|_workspace| {
5636 call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
5637 });
5638
5639 let has_write_access = self.has_write_access(cx);
5640
5641 let has_co_authors = room.is_some_and(|room| {
5642 self.load_local_committer(cx);
5643 let room = room.read(cx);
5644 room.remote_participants()
5645 .values()
5646 .any(|remote_participant| remote_participant.can_write())
5647 });
5648
5649 v_flex()
5650 .id("git_panel")
5651 .key_context(self.dispatch_context(window, cx))
5652 .track_focus(&self.focus_handle)
5653 .when(has_write_access && !project.is_read_only(cx), |this| {
5654 this.on_action(cx.listener(Self::toggle_staged_for_selected))
5655 .on_action(cx.listener(Self::stage_range))
5656 .on_action(cx.listener(GitPanel::on_commit))
5657 .on_action(cx.listener(GitPanel::on_amend))
5658 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5659 .on_action(cx.listener(Self::stage_all))
5660 .on_action(cx.listener(Self::unstage_all))
5661 .on_action(cx.listener(Self::stage_selected))
5662 .on_action(cx.listener(Self::unstage_selected))
5663 .on_action(cx.listener(Self::restore_tracked_files))
5664 .on_action(cx.listener(Self::revert_selected))
5665 .on_action(cx.listener(Self::add_to_gitignore))
5666 .on_action(cx.listener(Self::clean_all))
5667 .on_action(cx.listener(Self::generate_commit_message_action))
5668 .on_action(cx.listener(Self::stash_all))
5669 .on_action(cx.listener(Self::stash_pop))
5670 })
5671 .on_action(cx.listener(Self::collapse_selected_entry))
5672 .on_action(cx.listener(Self::expand_selected_entry))
5673 .on_action(cx.listener(Self::select_first))
5674 .on_action(cx.listener(Self::select_next))
5675 .on_action(cx.listener(Self::select_previous))
5676 .on_action(cx.listener(Self::select_last))
5677 .on_action(cx.listener(Self::first_entry))
5678 .on_action(cx.listener(Self::next_entry))
5679 .on_action(cx.listener(Self::previous_entry))
5680 .on_action(cx.listener(Self::last_entry))
5681 .on_action(cx.listener(Self::close_panel))
5682 .on_action(cx.listener(Self::open_diff))
5683 .on_action(cx.listener(Self::open_file))
5684 .on_action(cx.listener(Self::file_history))
5685 .on_action(cx.listener(Self::focus_changes_list))
5686 .on_action(cx.listener(Self::focus_editor))
5687 .on_action(cx.listener(Self::expand_commit_editor))
5688 .when(has_write_access && has_co_authors, |git_panel| {
5689 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5690 })
5691 .on_action(cx.listener(Self::toggle_sort_by_path))
5692 .on_action(cx.listener(Self::toggle_tree_view))
5693 .size_full()
5694 .overflow_hidden()
5695 .bg(cx.theme().colors().panel_background)
5696 .child(
5697 v_flex()
5698 .size_full()
5699 .children(self.render_panel_header(window, cx))
5700 .map(|this| {
5701 if let Some(repo) = self.active_repository.clone()
5702 && has_entries
5703 {
5704 this.child(self.render_entries(has_write_access, repo, window, cx))
5705 } else {
5706 this.child(self.render_empty_state(cx).into_any_element())
5707 }
5708 })
5709 .children(self.render_footer(window, cx))
5710 .when(self.amend_pending, |this| {
5711 this.child(self.render_pending_amend(cx))
5712 })
5713 .when(!self.amend_pending, |this| {
5714 this.children(self.render_previous_commit(window, cx))
5715 })
5716 .into_any_element(),
5717 )
5718 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5719 deferred(
5720 anchored()
5721 .position(*position)
5722 .anchor(Corner::TopLeft)
5723 .child(menu.clone()),
5724 )
5725 .with_priority(1)
5726 }))
5727 }
5728}
5729
5730impl Focusable for GitPanel {
5731 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5732 if self.entries.is_empty() {
5733 self.commit_editor.focus_handle(cx)
5734 } else {
5735 self.focus_handle.clone()
5736 }
5737 }
5738}
5739
5740impl EventEmitter<Event> for GitPanel {}
5741
5742impl EventEmitter<PanelEvent> for GitPanel {}
5743
5744pub(crate) struct GitPanelAddon {
5745 pub(crate) workspace: WeakEntity<Workspace>,
5746}
5747
5748impl editor::Addon for GitPanelAddon {
5749 fn to_any(&self) -> &dyn std::any::Any {
5750 self
5751 }
5752
5753 fn render_buffer_header_controls(
5754 &self,
5755 excerpt_info: &ExcerptInfo,
5756 window: &Window,
5757 cx: &App,
5758 ) -> Option<AnyElement> {
5759 let file = excerpt_info.buffer.file()?;
5760 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5761
5762 git_panel
5763 .read(cx)
5764 .render_buffer_header_controls(&git_panel, file, window, cx)
5765 }
5766}
5767
5768impl Panel for GitPanel {
5769 fn persistent_name() -> &'static str {
5770 "GitPanel"
5771 }
5772
5773 fn panel_key() -> &'static str {
5774 GIT_PANEL_KEY
5775 }
5776
5777 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5778 GitPanelSettings::get_global(cx).dock
5779 }
5780
5781 fn position_is_valid(&self, position: DockPosition) -> bool {
5782 matches!(position, DockPosition::Left | DockPosition::Right)
5783 }
5784
5785 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5786 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5787 settings.git_panel.get_or_insert_default().dock = Some(position.into())
5788 });
5789 }
5790
5791 fn size(&self, _: &Window, cx: &App) -> Pixels {
5792 self.width
5793 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
5794 }
5795
5796 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
5797 self.width = size;
5798 self.serialize(cx);
5799 cx.notify();
5800 }
5801
5802 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5803 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5804 }
5805
5806 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5807 Some("Git Panel")
5808 }
5809
5810 fn toggle_action(&self) -> Box<dyn Action> {
5811 Box::new(ToggleFocus)
5812 }
5813
5814 fn activation_priority(&self) -> u32 {
5815 2
5816 }
5817}
5818
5819impl PanelHeader for GitPanel {}
5820
5821pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5822 v_flex()
5823 .size_full()
5824 .gap(px(8.))
5825 .p_2()
5826 .bg(cx.theme().colors().editor_background)
5827}
5828
5829pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5830 let settings = ThemeSettings::get_global(cx);
5831
5832 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5833
5834 let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5835 (
5836 settings.buffer_font.family.clone(),
5837 settings.buffer_font.fallbacks.clone(),
5838 settings.buffer_font.features.clone(),
5839 settings.buffer_font.weight,
5840 font_size * settings.buffer_line_height.value(),
5841 )
5842 } else {
5843 (
5844 settings.ui_font.family.clone(),
5845 settings.ui_font.fallbacks.clone(),
5846 settings.ui_font.features.clone(),
5847 settings.ui_font.weight,
5848 window.line_height(),
5849 )
5850 };
5851
5852 EditorStyle {
5853 background: cx.theme().colors().editor_background,
5854 local_player: cx.theme().players().local(),
5855 text: TextStyle {
5856 color: cx.theme().colors().text,
5857 font_family,
5858 font_fallbacks,
5859 font_features,
5860 font_size: TextSize::Small.rems(cx).into(),
5861 font_weight,
5862 line_height: line_height.into(),
5863 ..Default::default()
5864 },
5865 syntax: cx.theme().syntax().clone(),
5866 ..Default::default()
5867 }
5868}
5869
5870struct GitPanelMessageTooltip {
5871 commit_tooltip: Option<Entity<CommitTooltip>>,
5872}
5873
5874impl GitPanelMessageTooltip {
5875 fn new(
5876 git_panel: Entity<GitPanel>,
5877 sha: SharedString,
5878 repository: Entity<Repository>,
5879 window: &mut Window,
5880 cx: &mut App,
5881 ) -> Entity<Self> {
5882 let remote_url = repository.read(cx).default_remote_url();
5883 cx.new(|cx| {
5884 cx.spawn_in(window, async move |this, cx| {
5885 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5886 (
5887 git_panel.load_commit_details(sha.to_string(), cx),
5888 git_panel.workspace.clone(),
5889 )
5890 });
5891 let details = details.await?;
5892 let provider_registry = cx
5893 .update(|_, app| GitHostingProviderRegistry::default_global(app))
5894 .ok();
5895
5896 let commit_details = crate::commit_tooltip::CommitDetails {
5897 sha: details.sha.clone(),
5898 author_name: details.author_name.clone(),
5899 author_email: details.author_email.clone(),
5900 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5901 message: Some(ParsedCommitMessage::parse(
5902 details.sha.to_string(),
5903 details.message.to_string(),
5904 remote_url.as_deref(),
5905 provider_registry,
5906 )),
5907 };
5908
5909 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5910 this.commit_tooltip = Some(cx.new(move |cx| {
5911 CommitTooltip::new(commit_details, repository, workspace, cx)
5912 }));
5913 cx.notify();
5914 })
5915 })
5916 .detach();
5917
5918 Self {
5919 commit_tooltip: None,
5920 }
5921 })
5922 }
5923}
5924
5925impl Render for GitPanelMessageTooltip {
5926 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5927 if let Some(commit_tooltip) = &self.commit_tooltip {
5928 commit_tooltip.clone().into_any_element()
5929 } else {
5930 gpui::Empty.into_any_element()
5931 }
5932 }
5933}
5934
5935#[derive(IntoElement, RegisterComponent)]
5936pub struct PanelRepoFooter {
5937 active_repository: SharedString,
5938 branch: Option<Branch>,
5939 head_commit: Option<CommitDetails>,
5940
5941 // Getting a GitPanel in previews will be difficult.
5942 //
5943 // For now just take an option here, and we won't bind handlers to buttons in previews.
5944 git_panel: Option<Entity<GitPanel>>,
5945}
5946
5947impl PanelRepoFooter {
5948 pub fn new(
5949 active_repository: SharedString,
5950 branch: Option<Branch>,
5951 head_commit: Option<CommitDetails>,
5952 git_panel: Option<Entity<GitPanel>>,
5953 ) -> Self {
5954 Self {
5955 active_repository,
5956 branch,
5957 head_commit,
5958 git_panel,
5959 }
5960 }
5961
5962 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5963 Self {
5964 active_repository,
5965 branch,
5966 head_commit: None,
5967 git_panel: None,
5968 }
5969 }
5970}
5971
5972impl RenderOnce for PanelRepoFooter {
5973 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5974 let project = self
5975 .git_panel
5976 .as_ref()
5977 .map(|panel| panel.read(cx).project.clone());
5978
5979 let (workspace, repo) = self
5980 .git_panel
5981 .as_ref()
5982 .map(|panel| {
5983 let panel = panel.read(cx);
5984 (panel.workspace.clone(), panel.active_repository.clone())
5985 })
5986 .unzip();
5987
5988 let single_repo = project
5989 .as_ref()
5990 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5991 .unwrap_or(true);
5992
5993 const MAX_BRANCH_LEN: usize = 16;
5994 const MAX_REPO_LEN: usize = 16;
5995 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
5996 const MAX_SHORT_SHA_LEN: usize = 8;
5997 let branch_name = self
5998 .branch
5999 .as_ref()
6000 .map(|branch| branch.name().to_owned())
6001 .or_else(|| {
6002 self.head_commit.as_ref().map(|commit| {
6003 commit
6004 .sha
6005 .chars()
6006 .take(MAX_SHORT_SHA_LEN)
6007 .collect::<String>()
6008 })
6009 })
6010 .unwrap_or_else(|| " (no branch)".to_owned());
6011 let show_separator = self.branch.is_some() || self.head_commit.is_some();
6012
6013 let active_repo_name = self.active_repository.clone();
6014
6015 let branch_actual_len = branch_name.len();
6016 let repo_actual_len = active_repo_name.len();
6017
6018 // ideally, show the whole branch and repo names but
6019 // when we can't, use a budget to allocate space between the two
6020 let (repo_display_len, branch_display_len) =
6021 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
6022 (repo_actual_len, branch_actual_len)
6023 } else if branch_actual_len <= MAX_BRANCH_LEN {
6024 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
6025 (repo_space, branch_actual_len)
6026 } else if repo_actual_len <= MAX_REPO_LEN {
6027 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
6028 (repo_actual_len, branch_space)
6029 } else {
6030 (MAX_REPO_LEN, MAX_BRANCH_LEN)
6031 };
6032
6033 let truncated_repo_name = if repo_actual_len <= repo_display_len {
6034 active_repo_name.to_string()
6035 } else {
6036 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
6037 };
6038
6039 let truncated_branch_name = if branch_actual_len <= branch_display_len {
6040 branch_name
6041 } else {
6042 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
6043 };
6044
6045 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
6046 .size(ButtonSize::None)
6047 .label_size(LabelSize::Small);
6048
6049 let repo_selector = PopoverMenu::new("repository-switcher")
6050 .menu({
6051 let project = project;
6052 move |window, cx| {
6053 let project = project.clone()?;
6054 Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
6055 }
6056 })
6057 .trigger_with_tooltip(
6058 repo_selector_trigger
6059 .when(single_repo, |this| this.disabled(true).color(Color::Muted))
6060 .truncate(true),
6061 move |_, cx| {
6062 if single_repo {
6063 cx.new(|_| Empty).into()
6064 } else {
6065 Tooltip::simple("Switch Active Repository", cx)
6066 }
6067 },
6068 )
6069 .anchor(Corner::BottomLeft)
6070 .offset(gpui::Point {
6071 x: px(0.0),
6072 y: px(-2.0),
6073 })
6074 .into_any_element();
6075
6076 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
6077 .size(ButtonSize::None)
6078 .label_size(LabelSize::Small)
6079 .truncate(true)
6080 .on_click(|_, window, cx| {
6081 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
6082 });
6083
6084 let branch_selector = PopoverMenu::new("popover-button")
6085 .menu(move |window, cx| {
6086 let workspace = workspace.clone()?;
6087 let repo = repo.clone().flatten();
6088 Some(branch_picker::popover(workspace, false, repo, window, cx))
6089 })
6090 .trigger_with_tooltip(
6091 branch_selector_button,
6092 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
6093 )
6094 .anchor(Corner::BottomLeft)
6095 .offset(gpui::Point {
6096 x: px(0.0),
6097 y: px(-2.0),
6098 });
6099
6100 h_flex()
6101 .h(px(36.))
6102 .w_full()
6103 .px_2()
6104 .justify_between()
6105 .gap_1()
6106 .child(
6107 h_flex()
6108 .flex_1()
6109 .overflow_hidden()
6110 .gap_px()
6111 .child(
6112 Icon::new(IconName::GitBranchAlt)
6113 .size(IconSize::Small)
6114 .color(if single_repo {
6115 Color::Disabled
6116 } else {
6117 Color::Muted
6118 }),
6119 )
6120 .child(repo_selector)
6121 .when(show_separator, |this| {
6122 this.child(
6123 div()
6124 .text_sm()
6125 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
6126 .child("/"),
6127 )
6128 })
6129 .child(branch_selector),
6130 )
6131 .children(if let Some(git_panel) = self.git_panel {
6132 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
6133 } else {
6134 None
6135 })
6136 }
6137}
6138
6139impl Component for PanelRepoFooter {
6140 fn scope() -> ComponentScope {
6141 ComponentScope::VersionControl
6142 }
6143
6144 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
6145 let unknown_upstream = None;
6146 let no_remote_upstream = Some(UpstreamTracking::Gone);
6147 let ahead_of_upstream = Some(
6148 UpstreamTrackingStatus {
6149 ahead: 2,
6150 behind: 0,
6151 }
6152 .into(),
6153 );
6154 let behind_upstream = Some(
6155 UpstreamTrackingStatus {
6156 ahead: 0,
6157 behind: 2,
6158 }
6159 .into(),
6160 );
6161 let ahead_and_behind_upstream = Some(
6162 UpstreamTrackingStatus {
6163 ahead: 3,
6164 behind: 1,
6165 }
6166 .into(),
6167 );
6168
6169 let not_ahead_or_behind_upstream = Some(
6170 UpstreamTrackingStatus {
6171 ahead: 0,
6172 behind: 0,
6173 }
6174 .into(),
6175 );
6176
6177 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6178 Branch {
6179 is_head: true,
6180 ref_name: "some-branch".into(),
6181 upstream: upstream.map(|tracking| Upstream {
6182 ref_name: "origin/some-branch".into(),
6183 tracking,
6184 }),
6185 most_recent_commit: Some(CommitSummary {
6186 sha: "abc123".into(),
6187 subject: "Modify stuff".into(),
6188 commit_timestamp: 1710932954,
6189 author_name: "John Doe".into(),
6190 has_parent: true,
6191 }),
6192 }
6193 }
6194
6195 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6196 Branch {
6197 is_head: true,
6198 ref_name: branch_name.to_string().into(),
6199 upstream: upstream.map(|tracking| Upstream {
6200 ref_name: format!("zed/{}", branch_name).into(),
6201 tracking,
6202 }),
6203 most_recent_commit: Some(CommitSummary {
6204 sha: "abc123".into(),
6205 subject: "Modify stuff".into(),
6206 commit_timestamp: 1710932954,
6207 author_name: "John Doe".into(),
6208 has_parent: true,
6209 }),
6210 }
6211 }
6212
6213 fn active_repository(id: usize) -> SharedString {
6214 format!("repo-{}", id).into()
6215 }
6216
6217 let example_width = px(340.);
6218 Some(
6219 v_flex()
6220 .gap_6()
6221 .w_full()
6222 .flex_none()
6223 .children(vec![
6224 example_group_with_title(
6225 "Action Button States",
6226 vec![
6227 single_example(
6228 "No Branch",
6229 div()
6230 .w(example_width)
6231 .overflow_hidden()
6232 .child(PanelRepoFooter::new_preview(active_repository(1), None))
6233 .into_any_element(),
6234 ),
6235 single_example(
6236 "Remote status unknown",
6237 div()
6238 .w(example_width)
6239 .overflow_hidden()
6240 .child(PanelRepoFooter::new_preview(
6241 active_repository(2),
6242 Some(branch(unknown_upstream)),
6243 ))
6244 .into_any_element(),
6245 ),
6246 single_example(
6247 "No Remote Upstream",
6248 div()
6249 .w(example_width)
6250 .overflow_hidden()
6251 .child(PanelRepoFooter::new_preview(
6252 active_repository(3),
6253 Some(branch(no_remote_upstream)),
6254 ))
6255 .into_any_element(),
6256 ),
6257 single_example(
6258 "Not Ahead or Behind",
6259 div()
6260 .w(example_width)
6261 .overflow_hidden()
6262 .child(PanelRepoFooter::new_preview(
6263 active_repository(4),
6264 Some(branch(not_ahead_or_behind_upstream)),
6265 ))
6266 .into_any_element(),
6267 ),
6268 single_example(
6269 "Behind remote",
6270 div()
6271 .w(example_width)
6272 .overflow_hidden()
6273 .child(PanelRepoFooter::new_preview(
6274 active_repository(5),
6275 Some(branch(behind_upstream)),
6276 ))
6277 .into_any_element(),
6278 ),
6279 single_example(
6280 "Ahead of remote",
6281 div()
6282 .w(example_width)
6283 .overflow_hidden()
6284 .child(PanelRepoFooter::new_preview(
6285 active_repository(6),
6286 Some(branch(ahead_of_upstream)),
6287 ))
6288 .into_any_element(),
6289 ),
6290 single_example(
6291 "Ahead and behind remote",
6292 div()
6293 .w(example_width)
6294 .overflow_hidden()
6295 .child(PanelRepoFooter::new_preview(
6296 active_repository(7),
6297 Some(branch(ahead_and_behind_upstream)),
6298 ))
6299 .into_any_element(),
6300 ),
6301 ],
6302 )
6303 .grow()
6304 .vertical(),
6305 ])
6306 .children(vec![
6307 example_group_with_title(
6308 "Labels",
6309 vec![
6310 single_example(
6311 "Short Branch & Repo",
6312 div()
6313 .w(example_width)
6314 .overflow_hidden()
6315 .child(PanelRepoFooter::new_preview(
6316 SharedString::from("zed"),
6317 Some(custom("main", behind_upstream)),
6318 ))
6319 .into_any_element(),
6320 ),
6321 single_example(
6322 "Long Branch",
6323 div()
6324 .w(example_width)
6325 .overflow_hidden()
6326 .child(PanelRepoFooter::new_preview(
6327 SharedString::from("zed"),
6328 Some(custom(
6329 "redesign-and-update-git-ui-list-entry-style",
6330 behind_upstream,
6331 )),
6332 ))
6333 .into_any_element(),
6334 ),
6335 single_example(
6336 "Long Repo",
6337 div()
6338 .w(example_width)
6339 .overflow_hidden()
6340 .child(PanelRepoFooter::new_preview(
6341 SharedString::from("zed-industries-community-examples"),
6342 Some(custom("gpui", ahead_of_upstream)),
6343 ))
6344 .into_any_element(),
6345 ),
6346 single_example(
6347 "Long Repo & Branch",
6348 div()
6349 .w(example_width)
6350 .overflow_hidden()
6351 .child(PanelRepoFooter::new_preview(
6352 SharedString::from("zed-industries-community-examples"),
6353 Some(custom(
6354 "redesign-and-update-git-ui-list-entry-style",
6355 behind_upstream,
6356 )),
6357 ))
6358 .into_any_element(),
6359 ),
6360 single_example(
6361 "Uppercase Repo",
6362 div()
6363 .w(example_width)
6364 .overflow_hidden()
6365 .child(PanelRepoFooter::new_preview(
6366 SharedString::from("LICENSES"),
6367 Some(custom("main", ahead_of_upstream)),
6368 ))
6369 .into_any_element(),
6370 ),
6371 single_example(
6372 "Uppercase Branch",
6373 div()
6374 .w(example_width)
6375 .overflow_hidden()
6376 .child(PanelRepoFooter::new_preview(
6377 SharedString::from("zed"),
6378 Some(custom("update-README", behind_upstream)),
6379 ))
6380 .into_any_element(),
6381 ),
6382 ],
6383 )
6384 .grow()
6385 .vertical(),
6386 ])
6387 .into_any_element(),
6388 )
6389 }
6390}
6391
6392fn open_output(
6393 operation: impl Into<SharedString>,
6394 workspace: &mut Workspace,
6395 output: &str,
6396 window: &mut Window,
6397 cx: &mut Context<Workspace>,
6398) {
6399 let operation = operation.into();
6400 let buffer = cx.new(|cx| Buffer::local(output, cx));
6401 buffer.update(cx, |buffer, cx| {
6402 buffer.set_capability(language::Capability::ReadOnly, cx);
6403 });
6404 let editor = cx.new(|cx| {
6405 let mut editor = Editor::for_buffer(buffer, None, window, cx);
6406 editor.buffer().update(cx, |buffer, cx| {
6407 buffer.set_title(format!("Output from git {operation}"), cx);
6408 });
6409 editor.set_read_only(true);
6410 editor
6411 });
6412
6413 workspace.add_item_to_center(Box::new(editor), window, cx);
6414}
6415
6416pub(crate) fn show_error_toast(
6417 workspace: Entity<Workspace>,
6418 action: impl Into<SharedString>,
6419 e: anyhow::Error,
6420 cx: &mut App,
6421) {
6422 let action = action.into();
6423 let message = e.to_string().trim().to_string();
6424 if message
6425 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6426 .next()
6427 .is_some()
6428 { // Hide the cancelled by user message
6429 } else {
6430 workspace.update(cx, |workspace, cx| {
6431 let workspace_weak = cx.weak_entity();
6432 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6433 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6434 .action("View Log", move |window, cx| {
6435 let message = message.clone();
6436 let action = action.clone();
6437 workspace_weak
6438 .update(cx, move |workspace, cx| {
6439 open_output(action, workspace, &message, window, cx)
6440 })
6441 .ok();
6442 })
6443 });
6444 workspace.toggle_status_toast(toast, cx)
6445 });
6446 }
6447}
6448
6449#[cfg(test)]
6450mod tests {
6451 use git::{
6452 repository::repo_path,
6453 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6454 };
6455 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
6456 use indoc::indoc;
6457 use project::FakeFs;
6458 use serde_json::json;
6459 use settings::SettingsStore;
6460 use theme::LoadThemes;
6461 use util::path;
6462 use util::rel_path::rel_path;
6463
6464 use workspace::MultiWorkspace;
6465
6466 use super::*;
6467
6468 fn init_test(cx: &mut gpui::TestAppContext) {
6469 zlog::init_test();
6470
6471 cx.update(|cx| {
6472 let settings_store = SettingsStore::test(cx);
6473 cx.set_global(settings_store);
6474 theme::init(LoadThemes::JustBase, cx);
6475 editor::init(cx);
6476 crate::init(cx);
6477 });
6478 }
6479
6480 #[gpui::test]
6481 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6482 init_test(cx);
6483 let fs = FakeFs::new(cx.background_executor.clone());
6484 fs.insert_tree(
6485 "/root",
6486 json!({
6487 "zed": {
6488 ".git": {},
6489 "crates": {
6490 "gpui": {
6491 "gpui.rs": "fn main() {}"
6492 },
6493 "util": {
6494 "util.rs": "fn do_it() {}"
6495 }
6496 }
6497 },
6498 }),
6499 )
6500 .await;
6501
6502 fs.set_status_for_repo(
6503 Path::new(path!("/root/zed/.git")),
6504 &[
6505 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6506 ("crates/util/util.rs", StatusCode::Modified.worktree()),
6507 ],
6508 );
6509
6510 let project =
6511 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6512 let window_handle =
6513 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6514 let workspace = window_handle
6515 .read_with(cx, |mw, _| mw.workspace().clone())
6516 .unwrap();
6517 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6518
6519 cx.read(|cx| {
6520 project
6521 .read(cx)
6522 .worktrees(cx)
6523 .next()
6524 .unwrap()
6525 .read(cx)
6526 .as_local()
6527 .unwrap()
6528 .scan_complete()
6529 })
6530 .await;
6531
6532 cx.executor().run_until_parked();
6533
6534 let panel = workspace.update_in(cx, GitPanel::new);
6535
6536 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6537 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6538 });
6539 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6540 handle.await;
6541
6542 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6543 pretty_assertions::assert_eq!(
6544 entries,
6545 [
6546 GitListEntry::Header(GitHeaderEntry {
6547 header: Section::Tracked
6548 }),
6549 GitListEntry::Status(GitStatusEntry {
6550 repo_path: repo_path("crates/gpui/gpui.rs"),
6551 status: StatusCode::Modified.worktree(),
6552 staging: StageStatus::Unstaged,
6553 }),
6554 GitListEntry::Status(GitStatusEntry {
6555 repo_path: repo_path("crates/util/util.rs"),
6556 status: StatusCode::Modified.worktree(),
6557 staging: StageStatus::Unstaged,
6558 },),
6559 ],
6560 );
6561
6562 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6563 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6564 });
6565 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6566 handle.await;
6567 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6568 pretty_assertions::assert_eq!(
6569 entries,
6570 [
6571 GitListEntry::Header(GitHeaderEntry {
6572 header: Section::Tracked
6573 }),
6574 GitListEntry::Status(GitStatusEntry {
6575 repo_path: repo_path("crates/gpui/gpui.rs"),
6576 status: StatusCode::Modified.worktree(),
6577 staging: StageStatus::Unstaged,
6578 }),
6579 GitListEntry::Status(GitStatusEntry {
6580 repo_path: repo_path("crates/util/util.rs"),
6581 status: StatusCode::Modified.worktree(),
6582 staging: StageStatus::Unstaged,
6583 },),
6584 ],
6585 );
6586 }
6587
6588 #[gpui::test]
6589 async fn test_bulk_staging(cx: &mut TestAppContext) {
6590 use GitListEntry::*;
6591
6592 init_test(cx);
6593 let fs = FakeFs::new(cx.background_executor.clone());
6594 fs.insert_tree(
6595 "/root",
6596 json!({
6597 "project": {
6598 ".git": {},
6599 "src": {
6600 "main.rs": "fn main() {}",
6601 "lib.rs": "pub fn hello() {}",
6602 "utils.rs": "pub fn util() {}"
6603 },
6604 "tests": {
6605 "test.rs": "fn test() {}"
6606 },
6607 "new_file.txt": "new content",
6608 "another_new.rs": "// new file",
6609 "conflict.txt": "conflicted content"
6610 }
6611 }),
6612 )
6613 .await;
6614
6615 fs.set_status_for_repo(
6616 Path::new(path!("/root/project/.git")),
6617 &[
6618 ("src/main.rs", StatusCode::Modified.worktree()),
6619 ("src/lib.rs", StatusCode::Modified.worktree()),
6620 ("tests/test.rs", StatusCode::Modified.worktree()),
6621 ("new_file.txt", FileStatus::Untracked),
6622 ("another_new.rs", FileStatus::Untracked),
6623 ("src/utils.rs", FileStatus::Untracked),
6624 (
6625 "conflict.txt",
6626 UnmergedStatus {
6627 first_head: UnmergedStatusCode::Updated,
6628 second_head: UnmergedStatusCode::Updated,
6629 }
6630 .into(),
6631 ),
6632 ],
6633 );
6634
6635 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6636 let window_handle =
6637 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6638 let workspace = window_handle
6639 .read_with(cx, |mw, _| mw.workspace().clone())
6640 .unwrap();
6641 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6642
6643 cx.read(|cx| {
6644 project
6645 .read(cx)
6646 .worktrees(cx)
6647 .next()
6648 .unwrap()
6649 .read(cx)
6650 .as_local()
6651 .unwrap()
6652 .scan_complete()
6653 })
6654 .await;
6655
6656 cx.executor().run_until_parked();
6657
6658 let panel = workspace.update_in(cx, GitPanel::new);
6659
6660 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6661 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6662 });
6663 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6664 handle.await;
6665
6666 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6667 #[rustfmt::skip]
6668 pretty_assertions::assert_matches!(
6669 entries.as_slice(),
6670 &[
6671 Header(GitHeaderEntry { header: Section::Conflict }),
6672 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6673 Header(GitHeaderEntry { header: Section::Tracked }),
6674 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6675 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6676 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6677 Header(GitHeaderEntry { header: Section::New }),
6678 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6679 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6680 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6681 ],
6682 );
6683
6684 let second_status_entry = entries[3].clone();
6685 panel.update_in(cx, |panel, window, cx| {
6686 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6687 });
6688
6689 panel.update_in(cx, |panel, window, cx| {
6690 panel.selected_entry = Some(7);
6691 panel.stage_range(&git::StageRange, window, cx);
6692 });
6693
6694 cx.read(|cx| {
6695 project
6696 .read(cx)
6697 .worktrees(cx)
6698 .next()
6699 .unwrap()
6700 .read(cx)
6701 .as_local()
6702 .unwrap()
6703 .scan_complete()
6704 })
6705 .await;
6706
6707 cx.executor().run_until_parked();
6708
6709 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6710 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6711 });
6712 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6713 handle.await;
6714
6715 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6716 #[rustfmt::skip]
6717 pretty_assertions::assert_matches!(
6718 entries.as_slice(),
6719 &[
6720 Header(GitHeaderEntry { header: Section::Conflict }),
6721 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6722 Header(GitHeaderEntry { header: Section::Tracked }),
6723 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6724 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6725 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6726 Header(GitHeaderEntry { header: Section::New }),
6727 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6728 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6729 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6730 ],
6731 );
6732
6733 let third_status_entry = entries[4].clone();
6734 panel.update_in(cx, |panel, window, cx| {
6735 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6736 });
6737
6738 panel.update_in(cx, |panel, window, cx| {
6739 panel.selected_entry = Some(9);
6740 panel.stage_range(&git::StageRange, window, cx);
6741 });
6742
6743 cx.read(|cx| {
6744 project
6745 .read(cx)
6746 .worktrees(cx)
6747 .next()
6748 .unwrap()
6749 .read(cx)
6750 .as_local()
6751 .unwrap()
6752 .scan_complete()
6753 })
6754 .await;
6755
6756 cx.executor().run_until_parked();
6757
6758 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6759 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6760 });
6761 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6762 handle.await;
6763
6764 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6765 #[rustfmt::skip]
6766 pretty_assertions::assert_matches!(
6767 entries.as_slice(),
6768 &[
6769 Header(GitHeaderEntry { header: Section::Conflict }),
6770 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6771 Header(GitHeaderEntry { header: Section::Tracked }),
6772 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6773 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6774 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6775 Header(GitHeaderEntry { header: Section::New }),
6776 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6777 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6778 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6779 ],
6780 );
6781 }
6782
6783 #[gpui::test]
6784 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6785 use GitListEntry::*;
6786
6787 init_test(cx);
6788 let fs = FakeFs::new(cx.background_executor.clone());
6789 fs.insert_tree(
6790 "/root",
6791 json!({
6792 "project": {
6793 ".git": {},
6794 "src": {
6795 "main.rs": "fn main() {}",
6796 "lib.rs": "pub fn hello() {}",
6797 "utils.rs": "pub fn util() {}"
6798 },
6799 "tests": {
6800 "test.rs": "fn test() {}"
6801 },
6802 "new_file.txt": "new content",
6803 "another_new.rs": "// new file",
6804 "conflict.txt": "conflicted content"
6805 }
6806 }),
6807 )
6808 .await;
6809
6810 fs.set_status_for_repo(
6811 Path::new(path!("/root/project/.git")),
6812 &[
6813 ("src/main.rs", StatusCode::Modified.worktree()),
6814 ("src/lib.rs", StatusCode::Modified.worktree()),
6815 ("tests/test.rs", StatusCode::Modified.worktree()),
6816 ("new_file.txt", FileStatus::Untracked),
6817 ("another_new.rs", FileStatus::Untracked),
6818 ("src/utils.rs", FileStatus::Untracked),
6819 (
6820 "conflict.txt",
6821 UnmergedStatus {
6822 first_head: UnmergedStatusCode::Updated,
6823 second_head: UnmergedStatusCode::Updated,
6824 }
6825 .into(),
6826 ),
6827 ],
6828 );
6829
6830 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6831 let window_handle =
6832 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6833 let workspace = window_handle
6834 .read_with(cx, |mw, _| mw.workspace().clone())
6835 .unwrap();
6836 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6837
6838 cx.read(|cx| {
6839 project
6840 .read(cx)
6841 .worktrees(cx)
6842 .next()
6843 .unwrap()
6844 .read(cx)
6845 .as_local()
6846 .unwrap()
6847 .scan_complete()
6848 })
6849 .await;
6850
6851 cx.executor().run_until_parked();
6852
6853 let panel = workspace.update_in(cx, GitPanel::new);
6854
6855 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6856 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6857 });
6858 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6859 handle.await;
6860
6861 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6862 #[rustfmt::skip]
6863 pretty_assertions::assert_matches!(
6864 entries.as_slice(),
6865 &[
6866 Header(GitHeaderEntry { header: Section::Conflict }),
6867 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6868 Header(GitHeaderEntry { header: Section::Tracked }),
6869 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6870 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6871 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6872 Header(GitHeaderEntry { header: Section::New }),
6873 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6874 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6875 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6876 ],
6877 );
6878
6879 assert_entry_paths(
6880 &entries,
6881 &[
6882 None,
6883 Some("conflict.txt"),
6884 None,
6885 Some("src/lib.rs"),
6886 Some("src/main.rs"),
6887 Some("tests/test.rs"),
6888 None,
6889 Some("another_new.rs"),
6890 Some("new_file.txt"),
6891 Some("src/utils.rs"),
6892 ],
6893 );
6894
6895 let second_status_entry = entries[3].clone();
6896 panel.update_in(cx, |panel, window, cx| {
6897 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6898 });
6899
6900 cx.update(|_window, cx| {
6901 SettingsStore::update_global(cx, |store, cx| {
6902 store.update_user_settings(cx, |settings| {
6903 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6904 })
6905 });
6906 });
6907
6908 panel.update_in(cx, |panel, window, cx| {
6909 panel.selected_entry = Some(7);
6910 panel.stage_range(&git::StageRange, window, cx);
6911 });
6912
6913 cx.read(|cx| {
6914 project
6915 .read(cx)
6916 .worktrees(cx)
6917 .next()
6918 .unwrap()
6919 .read(cx)
6920 .as_local()
6921 .unwrap()
6922 .scan_complete()
6923 })
6924 .await;
6925
6926 cx.executor().run_until_parked();
6927
6928 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6929 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6930 });
6931 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6932 handle.await;
6933
6934 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6935 #[rustfmt::skip]
6936 pretty_assertions::assert_matches!(
6937 entries.as_slice(),
6938 &[
6939 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6940 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6941 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6942 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6943 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6944 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6945 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6946 ],
6947 );
6948
6949 assert_entry_paths(
6950 &entries,
6951 &[
6952 Some("another_new.rs"),
6953 Some("conflict.txt"),
6954 Some("new_file.txt"),
6955 Some("src/lib.rs"),
6956 Some("src/main.rs"),
6957 Some("src/utils.rs"),
6958 Some("tests/test.rs"),
6959 ],
6960 );
6961
6962 let third_status_entry = entries[4].clone();
6963 panel.update_in(cx, |panel, window, cx| {
6964 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6965 });
6966
6967 panel.update_in(cx, |panel, window, cx| {
6968 panel.selected_entry = Some(9);
6969 panel.stage_range(&git::StageRange, window, cx);
6970 });
6971
6972 cx.read(|cx| {
6973 project
6974 .read(cx)
6975 .worktrees(cx)
6976 .next()
6977 .unwrap()
6978 .read(cx)
6979 .as_local()
6980 .unwrap()
6981 .scan_complete()
6982 })
6983 .await;
6984
6985 cx.executor().run_until_parked();
6986
6987 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6988 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6989 });
6990 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6991 handle.await;
6992
6993 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6994 #[rustfmt::skip]
6995 pretty_assertions::assert_matches!(
6996 entries.as_slice(),
6997 &[
6998 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6999 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7000 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7001 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7002 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7003 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7004 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7005 ],
7006 );
7007
7008 assert_entry_paths(
7009 &entries,
7010 &[
7011 Some("another_new.rs"),
7012 Some("conflict.txt"),
7013 Some("new_file.txt"),
7014 Some("src/lib.rs"),
7015 Some("src/main.rs"),
7016 Some("src/utils.rs"),
7017 Some("tests/test.rs"),
7018 ],
7019 );
7020 }
7021
7022 #[gpui::test]
7023 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
7024 init_test(cx);
7025 let fs = FakeFs::new(cx.background_executor.clone());
7026 fs.insert_tree(
7027 "/root",
7028 json!({
7029 "project": {
7030 ".git": {},
7031 "src": {
7032 "main.rs": "fn main() {}"
7033 }
7034 }
7035 }),
7036 )
7037 .await;
7038
7039 fs.set_status_for_repo(
7040 Path::new(path!("/root/project/.git")),
7041 &[("src/main.rs", StatusCode::Modified.worktree())],
7042 );
7043
7044 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7045 let window_handle =
7046 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7047 let workspace = window_handle
7048 .read_with(cx, |mw, _| mw.workspace().clone())
7049 .unwrap();
7050 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7051
7052 let panel = workspace.update_in(cx, GitPanel::new);
7053
7054 // Test: User has commit message, enables amend (saves message), then disables (restores message)
7055 panel.update(cx, |panel, cx| {
7056 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7057 let start = buffer.anchor_before(0);
7058 let end = buffer.anchor_after(buffer.len());
7059 buffer.edit([(start..end, "Initial commit message")], None, cx);
7060 });
7061
7062 panel.set_amend_pending(true, cx);
7063 assert!(panel.original_commit_message.is_some());
7064
7065 panel.set_amend_pending(false, cx);
7066 let current_message = panel.commit_message_buffer(cx).read(cx).text();
7067 assert_eq!(current_message, "Initial commit message");
7068 assert!(panel.original_commit_message.is_none());
7069 });
7070
7071 // Test: User has empty commit message, enables amend, then disables (clears message)
7072 panel.update(cx, |panel, cx| {
7073 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7074 let start = buffer.anchor_before(0);
7075 let end = buffer.anchor_after(buffer.len());
7076 buffer.edit([(start..end, "")], None, cx);
7077 });
7078
7079 panel.set_amend_pending(true, cx);
7080 assert!(panel.original_commit_message.is_none());
7081
7082 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7083 let start = buffer.anchor_before(0);
7084 let end = buffer.anchor_after(buffer.len());
7085 buffer.edit([(start..end, "Previous commit message")], None, cx);
7086 });
7087
7088 panel.set_amend_pending(false, cx);
7089 let current_message = panel.commit_message_buffer(cx).read(cx).text();
7090 assert_eq!(current_message, "");
7091 });
7092 }
7093
7094 #[gpui::test]
7095 async fn test_amend(cx: &mut TestAppContext) {
7096 init_test(cx);
7097 let fs = FakeFs::new(cx.background_executor.clone());
7098 fs.insert_tree(
7099 "/root",
7100 json!({
7101 "project": {
7102 ".git": {},
7103 "src": {
7104 "main.rs": "fn main() {}"
7105 }
7106 }
7107 }),
7108 )
7109 .await;
7110
7111 fs.set_status_for_repo(
7112 Path::new(path!("/root/project/.git")),
7113 &[("src/main.rs", StatusCode::Modified.worktree())],
7114 );
7115
7116 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7117 let window_handle =
7118 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7119 let workspace = window_handle
7120 .read_with(cx, |mw, _| mw.workspace().clone())
7121 .unwrap();
7122 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7123
7124 // Wait for the project scanning to finish so that `head_commit(cx)` is
7125 // actually set, otherwise no head commit would be available from which
7126 // to fetch the latest commit message from.
7127 cx.executor().run_until_parked();
7128
7129 let panel = workspace.update_in(cx, GitPanel::new);
7130 panel.read_with(cx, |panel, cx| {
7131 assert!(panel.active_repository.is_some());
7132 assert!(panel.head_commit(cx).is_some());
7133 });
7134
7135 panel.update_in(cx, |panel, window, cx| {
7136 // Update the commit editor's message to ensure that its contents
7137 // are later restored, after amending is finished.
7138 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7139 buffer.set_text("refactor: update main.rs", cx);
7140 });
7141
7142 // Start amending the previous commit.
7143 panel.focus_editor(&Default::default(), window, cx);
7144 panel.on_amend(&Amend, window, cx);
7145 });
7146
7147 // Since `GitPanel.amend` attempts to fetch the latest commit message in
7148 // a background task, we need to wait for it to complete before being
7149 // able to assert that the commit message editor's state has been
7150 // updated.
7151 cx.run_until_parked();
7152
7153 panel.update_in(cx, |panel, window, cx| {
7154 assert_eq!(
7155 panel.commit_message_buffer(cx).read(cx).text(),
7156 "initial commit"
7157 );
7158 assert_eq!(
7159 panel.original_commit_message,
7160 Some("refactor: update main.rs".to_string())
7161 );
7162
7163 // Finish amending the previous commit.
7164 panel.focus_editor(&Default::default(), window, cx);
7165 panel.on_amend(&Amend, window, cx);
7166 });
7167
7168 // Since the actual commit logic is run in a background task, we need to
7169 // await its completion to actually ensure that the commit message
7170 // editor's contents are set to the original message and haven't been
7171 // cleared.
7172 cx.run_until_parked();
7173
7174 panel.update_in(cx, |panel, _window, cx| {
7175 // After amending, the commit editor's message should be restored to
7176 // the original message.
7177 assert_eq!(
7178 panel.commit_message_buffer(cx).read(cx).text(),
7179 "refactor: update main.rs"
7180 );
7181 assert!(panel.original_commit_message.is_none());
7182 });
7183 }
7184
7185 #[gpui::test]
7186 async fn test_open_diff(cx: &mut TestAppContext) {
7187 init_test(cx);
7188
7189 let fs = FakeFs::new(cx.background_executor.clone());
7190 fs.insert_tree(
7191 path!("/project"),
7192 json!({
7193 ".git": {},
7194 "tracked": "tracked\n",
7195 "untracked": "\n",
7196 }),
7197 )
7198 .await;
7199
7200 fs.set_head_and_index_for_repo(
7201 path!("/project/.git").as_ref(),
7202 &[("tracked", "old tracked\n".into())],
7203 );
7204
7205 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7206 let window_handle =
7207 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7208 let workspace = window_handle
7209 .read_with(cx, |mw, _| mw.workspace().clone())
7210 .unwrap();
7211 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7212 let panel = workspace.update_in(cx, GitPanel::new);
7213
7214 // Enable the `sort_by_path` setting and wait for entries to be updated,
7215 // as there should no longer be separators between Tracked and Untracked
7216 // files.
7217 cx.update(|_window, cx| {
7218 SettingsStore::update_global(cx, |store, cx| {
7219 store.update_user_settings(cx, |settings| {
7220 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7221 })
7222 });
7223 });
7224
7225 cx.update_window_entity(&panel, |panel, _, _| {
7226 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7227 })
7228 .await;
7229
7230 // Confirm that `Open Diff` still works for the untracked file, updating
7231 // the Project Diff's active path.
7232 panel.update_in(cx, |panel, window, cx| {
7233 panel.selected_entry = Some(1);
7234 panel.open_diff(&menu::Confirm, window, cx);
7235 });
7236 cx.run_until_parked();
7237
7238 workspace.update_in(cx, |workspace, _window, cx| {
7239 let active_path = workspace
7240 .item_of_type::<ProjectDiff>(cx)
7241 .expect("ProjectDiff should exist")
7242 .read(cx)
7243 .active_path(cx)
7244 .expect("active_path should exist");
7245
7246 assert_eq!(active_path.path, rel_path("untracked").into_arc());
7247 });
7248 }
7249
7250 #[gpui::test]
7251 async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7252 cx: &mut TestAppContext,
7253 ) {
7254 init_test(cx);
7255
7256 let fs = FakeFs::new(cx.background_executor.clone());
7257 fs.insert_tree(
7258 path!("/project"),
7259 json!({
7260 ".git": {},
7261 "src": {
7262 "a": {
7263 "foo.rs": "fn foo() {}",
7264 },
7265 "b": {
7266 "bar.rs": "fn bar() {}",
7267 },
7268 },
7269 }),
7270 )
7271 .await;
7272
7273 fs.set_status_for_repo(
7274 path!("/project/.git").as_ref(),
7275 &[
7276 ("src/a/foo.rs", StatusCode::Modified.worktree()),
7277 ("src/b/bar.rs", StatusCode::Modified.worktree()),
7278 ],
7279 );
7280
7281 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7282 let window_handle =
7283 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7284 let workspace = window_handle
7285 .read_with(cx, |mw, _| mw.workspace().clone())
7286 .unwrap();
7287 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7288
7289 cx.read(|cx| {
7290 project
7291 .read(cx)
7292 .worktrees(cx)
7293 .next()
7294 .unwrap()
7295 .read(cx)
7296 .as_local()
7297 .unwrap()
7298 .scan_complete()
7299 })
7300 .await;
7301
7302 cx.executor().run_until_parked();
7303
7304 cx.update(|_window, cx| {
7305 SettingsStore::update_global(cx, |store, cx| {
7306 store.update_user_settings(cx, |settings| {
7307 settings.git_panel.get_or_insert_default().tree_view = Some(true);
7308 })
7309 });
7310 });
7311
7312 let panel = workspace.update_in(cx, GitPanel::new);
7313
7314 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7315 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7316 });
7317 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7318 handle.await;
7319
7320 let src_key = panel.read_with(cx, |panel, _| {
7321 panel
7322 .entries
7323 .iter()
7324 .find_map(|entry| match entry {
7325 GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7326 Some(dir.key.clone())
7327 }
7328 _ => None,
7329 })
7330 .expect("src directory should exist in tree view")
7331 });
7332
7333 panel.update_in(cx, |panel, window, cx| {
7334 panel.toggle_directory(&src_key, window, cx);
7335 });
7336
7337 panel.read_with(cx, |panel, _| {
7338 let state = panel
7339 .view_mode
7340 .tree_state()
7341 .expect("tree view state should exist");
7342 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7343 });
7344
7345 let worktree_id =
7346 cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7347 let project_path = ProjectPath {
7348 worktree_id,
7349 path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7350 };
7351
7352 panel.update_in(cx, |panel, window, cx| {
7353 panel.select_entry_by_path(project_path, window, cx);
7354 });
7355
7356 panel.read_with(cx, |panel, _| {
7357 let state = panel
7358 .view_mode
7359 .tree_state()
7360 .expect("tree view state should exist");
7361 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7362
7363 let selected_ix = panel.selected_entry.expect("selection should be set");
7364 assert!(state.logical_indices.contains(&selected_ix));
7365
7366 let selected_entry = panel
7367 .entries
7368 .get(selected_ix)
7369 .and_then(|entry| entry.status_entry())
7370 .expect("selected entry should be a status entry");
7371 assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7372 });
7373 }
7374
7375 #[gpui::test]
7376 async fn test_tree_view_select_next_at_last_visible_collapsed_directory(
7377 cx: &mut TestAppContext,
7378 ) {
7379 init_test(cx);
7380
7381 let fs = FakeFs::new(cx.background_executor.clone());
7382 fs.insert_tree(
7383 path!("/project"),
7384 json!({
7385 ".git": {},
7386 "bar": {
7387 "bar1.py": "print('bar1')",
7388 "bar2.py": "print('bar2')",
7389 },
7390 "foo": {
7391 "foo1.py": "print('foo1')",
7392 "foo2.py": "print('foo2')",
7393 },
7394 "foobar.py": "print('foobar')",
7395 }),
7396 )
7397 .await;
7398
7399 fs.set_status_for_repo(
7400 path!("/project/.git").as_ref(),
7401 &[
7402 ("bar/bar1.py", StatusCode::Modified.worktree()),
7403 ("bar/bar2.py", StatusCode::Modified.worktree()),
7404 ("foo/foo1.py", StatusCode::Modified.worktree()),
7405 ("foo/foo2.py", StatusCode::Modified.worktree()),
7406 ("foobar.py", FileStatus::Untracked),
7407 ],
7408 );
7409
7410 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7411 let window_handle =
7412 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7413 let workspace = window_handle
7414 .read_with(cx, |mw, _| mw.workspace().clone())
7415 .unwrap();
7416 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7417
7418 cx.read(|cx| {
7419 project
7420 .read(cx)
7421 .worktrees(cx)
7422 .next()
7423 .unwrap()
7424 .read(cx)
7425 .as_local()
7426 .unwrap()
7427 .scan_complete()
7428 })
7429 .await;
7430
7431 cx.executor().run_until_parked();
7432 cx.update(|_window, cx| {
7433 SettingsStore::update_global(cx, |store, cx| {
7434 store.update_user_settings(cx, |settings| {
7435 settings.git_panel.get_or_insert_default().tree_view = Some(true);
7436 })
7437 });
7438 });
7439
7440 let panel = workspace.update_in(cx, GitPanel::new);
7441 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7442 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7443 });
7444
7445 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7446 handle.await;
7447
7448 let foo_key = panel.read_with(cx, |panel, _| {
7449 panel
7450 .entries
7451 .iter()
7452 .find_map(|entry| match entry {
7453 GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => {
7454 Some(dir.key.clone())
7455 }
7456 _ => None,
7457 })
7458 .expect("foo directory should exist in tree view")
7459 });
7460
7461 panel.update_in(cx, |panel, window, cx| {
7462 panel.toggle_directory(&foo_key, window, cx);
7463 });
7464
7465 let foo_idx = panel.read_with(cx, |panel, _| {
7466 let state = panel
7467 .view_mode
7468 .tree_state()
7469 .expect("tree view state should exist");
7470 assert_eq!(state.expanded_dirs.get(&foo_key).copied(), Some(false));
7471
7472 let foo_idx = panel
7473 .entries
7474 .iter()
7475 .enumerate()
7476 .find_map(|(index, entry)| match entry {
7477 GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => Some(index),
7478 _ => None,
7479 })
7480 .expect("foo directory should exist in tree view");
7481
7482 let foo_logical_idx = state
7483 .logical_indices
7484 .iter()
7485 .position(|&index| index == foo_idx)
7486 .expect("foo directory should be visible");
7487 let next_logical_idx = state.logical_indices[foo_logical_idx + 1];
7488 assert!(matches!(
7489 panel.entries.get(next_logical_idx),
7490 Some(GitListEntry::Header(GitHeaderEntry {
7491 header: Section::New
7492 }))
7493 ));
7494
7495 foo_idx
7496 });
7497
7498 panel.update_in(cx, |panel, window, cx| {
7499 panel.selected_entry = Some(foo_idx);
7500 panel.select_next(&menu::SelectNext, window, cx);
7501 });
7502
7503 panel.read_with(cx, |panel, _| {
7504 let selected_idx = panel.selected_entry.expect("selection should be set");
7505 let selected_entry = panel
7506 .entries
7507 .get(selected_idx)
7508 .and_then(|entry| entry.status_entry())
7509 .expect("selected entry should be a status entry");
7510 assert_eq!(selected_entry.repo_path, repo_path("foobar.py"));
7511 });
7512 }
7513
7514 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7515 assert_eq!(entries.len(), expected_paths.len());
7516 for (entry, expected_path) in entries.iter().zip(expected_paths) {
7517 assert_eq!(
7518 entry.status_entry().map(|status| status
7519 .repo_path
7520 .as_ref()
7521 .as_std_path()
7522 .to_string_lossy()
7523 .to_string()),
7524 expected_path.map(|s| s.to_string())
7525 );
7526 }
7527 }
7528
7529 #[test]
7530 fn test_compress_diff_no_truncation() {
7531 let diff = indoc! {"
7532 --- a/file.txt
7533 +++ b/file.txt
7534 @@ -1,2 +1,2 @@
7535 -old
7536 +new
7537 "};
7538 let result = GitPanel::compress_commit_diff(diff, 1000);
7539 assert_eq!(result, diff);
7540 }
7541
7542 #[test]
7543 fn test_compress_diff_truncate_long_lines() {
7544 let long_line = "🦀".repeat(300);
7545 let diff = indoc::formatdoc! {"
7546 --- a/file.txt
7547 +++ b/file.txt
7548 @@ -1,2 +1,3 @@
7549 context
7550 +{}
7551 more context
7552 ", long_line};
7553 let result = GitPanel::compress_commit_diff(&diff, 100);
7554 assert!(result.contains("...[truncated]"));
7555 assert!(result.len() < diff.len());
7556 }
7557
7558 #[test]
7559 fn test_compress_diff_truncate_hunks() {
7560 let diff = indoc! {"
7561 --- a/file.txt
7562 +++ b/file.txt
7563 @@ -1,2 +1,2 @@
7564 context
7565 -old1
7566 +new1
7567 @@ -5,2 +5,2 @@
7568 context 2
7569 -old2
7570 +new2
7571 @@ -10,2 +10,2 @@
7572 context 3
7573 -old3
7574 +new3
7575 "};
7576 let result = GitPanel::compress_commit_diff(diff, 100);
7577 let expected = indoc! {"
7578 --- a/file.txt
7579 +++ b/file.txt
7580 @@ -1,2 +1,2 @@
7581 context
7582 -old1
7583 +new1
7584 [...skipped 2 hunks...]
7585 "};
7586 assert_eq!(result, expected);
7587 }
7588
7589 #[gpui::test]
7590 async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7591 init_test(cx);
7592
7593 let fs = FakeFs::new(cx.background_executor.clone());
7594 fs.insert_tree(
7595 path!("/project"),
7596 json!({
7597 ".git": {},
7598 "tracked": "tracked\n",
7599 "untracked": "\n",
7600 }),
7601 )
7602 .await;
7603
7604 fs.set_head_and_index_for_repo(
7605 path!("/project/.git").as_ref(),
7606 &[("tracked", "old tracked\n".into())],
7607 );
7608
7609 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7610 let window_handle =
7611 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7612 let workspace = window_handle
7613 .read_with(cx, |mw, _| mw.workspace().clone())
7614 .unwrap();
7615 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7616 let panel = workspace.update_in(cx, GitPanel::new);
7617
7618 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7619 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7620 });
7621 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7622 handle.await;
7623
7624 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7625
7626 // GitPanel
7627 // - Tracked:
7628 // - [] tracked
7629 // - Untracked
7630 // - [] untracked
7631 //
7632 // The commit message should now read:
7633 // "Update tracked"
7634 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7635 assert_eq!(message, Some("Update tracked".to_string()));
7636
7637 let first_status_entry = entries[1].clone();
7638 panel.update_in(cx, |panel, window, cx| {
7639 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7640 });
7641
7642 cx.read(|cx| {
7643 project
7644 .read(cx)
7645 .worktrees(cx)
7646 .next()
7647 .unwrap()
7648 .read(cx)
7649 .as_local()
7650 .unwrap()
7651 .scan_complete()
7652 })
7653 .await;
7654
7655 cx.executor().run_until_parked();
7656
7657 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7658 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7659 });
7660 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7661 handle.await;
7662
7663 // GitPanel
7664 // - Tracked:
7665 // - [x] tracked
7666 // - Untracked
7667 // - [] untracked
7668 //
7669 // The commit message should still read:
7670 // "Update tracked"
7671 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7672 assert_eq!(message, Some("Update tracked".to_string()));
7673
7674 let second_status_entry = entries[3].clone();
7675 panel.update_in(cx, |panel, window, cx| {
7676 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7677 });
7678
7679 cx.read(|cx| {
7680 project
7681 .read(cx)
7682 .worktrees(cx)
7683 .next()
7684 .unwrap()
7685 .read(cx)
7686 .as_local()
7687 .unwrap()
7688 .scan_complete()
7689 })
7690 .await;
7691
7692 cx.executor().run_until_parked();
7693
7694 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7695 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7696 });
7697 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7698 handle.await;
7699
7700 // GitPanel
7701 // - Tracked:
7702 // - [x] tracked
7703 // - Untracked
7704 // - [x] untracked
7705 //
7706 // The commit message should now read:
7707 // "Enter commit message"
7708 // (which means we should see None returned).
7709 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7710 assert!(message.is_none());
7711
7712 panel.update_in(cx, |panel, window, cx| {
7713 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7714 });
7715
7716 cx.read(|cx| {
7717 project
7718 .read(cx)
7719 .worktrees(cx)
7720 .next()
7721 .unwrap()
7722 .read(cx)
7723 .as_local()
7724 .unwrap()
7725 .scan_complete()
7726 })
7727 .await;
7728
7729 cx.executor().run_until_parked();
7730
7731 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7732 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7733 });
7734 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7735 handle.await;
7736
7737 // GitPanel
7738 // - Tracked:
7739 // - [] tracked
7740 // - Untracked
7741 // - [x] untracked
7742 //
7743 // The commit message should now read:
7744 // "Update untracked"
7745 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7746 assert_eq!(message, Some("Create untracked".to_string()));
7747
7748 panel.update_in(cx, |panel, window, cx| {
7749 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7750 });
7751
7752 cx.read(|cx| {
7753 project
7754 .read(cx)
7755 .worktrees(cx)
7756 .next()
7757 .unwrap()
7758 .read(cx)
7759 .as_local()
7760 .unwrap()
7761 .scan_complete()
7762 })
7763 .await;
7764
7765 cx.executor().run_until_parked();
7766
7767 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7768 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7769 });
7770 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7771 handle.await;
7772
7773 // GitPanel
7774 // - Tracked:
7775 // - [] tracked
7776 // - Untracked
7777 // - [] untracked
7778 //
7779 // The commit message should now read:
7780 // "Update tracked"
7781 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7782 assert_eq!(message, Some("Update tracked".to_string()));
7783 }
7784}