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