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