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 anyhow::Context as _;
15use askpass::AskPassDelegate;
16use collections::{BTreeMap, HashMap, HashSet};
17use db::kvp::KeyValueStore;
18use editor::{
19 Direction, Editor, EditorElement, EditorMode, MultiBuffer, MultiBufferOffset,
20 actions::ExpandAllDiffHunks,
21};
22use editor::{EditorStyle, RewrapOptions};
23use feature_flags::{FeatureFlagAppExt as _, GitGraphFeatureFlag};
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::ExcerptInfo;
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::BranchChanged,
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 },
2160 window,
2161 cx,
2162 );
2163 true
2164 } else {
2165 cx.propagate();
2166 false
2167 }
2168 }
2169
2170 fn on_amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
2171 if self.amend(&self.commit_editor.focus_handle(cx), window, cx) {
2172 telemetry::event!("Git Amended", source = "Git Panel");
2173 }
2174 }
2175
2176 /// Amends the most recent commit with staged changes and/or an updated commit message.
2177 ///
2178 /// Uses a two-stage workflow where the first invocation loads the commit
2179 /// message for editing, second invocation performs the amend. Returns
2180 /// `true` if the amend was executed, `false` otherwise.
2181 pub(crate) fn amend(
2182 &mut self,
2183 commit_editor_focus_handle: &FocusHandle,
2184 window: &mut Window,
2185 cx: &mut Context<Self>,
2186 ) -> bool {
2187 if commit_editor_focus_handle.contains_focused(window, cx) {
2188 if self.head_commit(cx).is_some() {
2189 if !self.amend_pending {
2190 self.set_amend_pending(true, cx);
2191 self.load_last_commit_message(cx);
2192
2193 return false;
2194 } else {
2195 self.commit_changes(
2196 CommitOptions {
2197 amend: true,
2198 signoff: self.signoff_enabled,
2199 },
2200 window,
2201 cx,
2202 );
2203
2204 return true;
2205 }
2206 }
2207 return false;
2208 } else {
2209 cx.propagate();
2210 return false;
2211 }
2212 }
2213 pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
2214 self.active_repository
2215 .as_ref()
2216 .and_then(|repo| repo.read(cx).head_commit.as_ref())
2217 .cloned()
2218 }
2219
2220 pub fn load_last_commit_message(&mut self, cx: &mut Context<Self>) {
2221 let Some(head_commit) = self.head_commit(cx) else {
2222 return;
2223 };
2224
2225 let recent_sha = head_commit.sha.to_string();
2226 let detail_task = self.load_commit_details(recent_sha, cx);
2227 cx.spawn(async move |this, cx| {
2228 if let Ok(message) = detail_task.await.map(|detail| detail.message) {
2229 this.update(cx, |this, cx| {
2230 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2231 let start = buffer.anchor_before(0);
2232 let end = buffer.anchor_after(buffer.len());
2233 buffer.edit([(start..end, message)], None, cx);
2234 });
2235 })
2236 .log_err();
2237 }
2238 })
2239 .detach();
2240 }
2241
2242 fn custom_or_suggested_commit_message(
2243 &self,
2244 window: &mut Window,
2245 cx: &mut Context<Self>,
2246 ) -> Option<String> {
2247 let git_commit_language = self
2248 .commit_editor
2249 .read(cx)
2250 .language_at(MultiBufferOffset(0), cx);
2251 let message = self.commit_editor.read(cx).text(cx);
2252 if message.is_empty() {
2253 return self
2254 .suggest_commit_message(cx)
2255 .filter(|message| !message.trim().is_empty());
2256 } else if message.trim().is_empty() {
2257 return None;
2258 }
2259 let buffer = cx.new(|cx| {
2260 let mut buffer = Buffer::local(message, cx);
2261 buffer.set_language(git_commit_language, cx);
2262 buffer
2263 });
2264 let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
2265 let wrapped_message = editor.update(cx, |editor, cx| {
2266 editor.select_all(&Default::default(), window, cx);
2267 editor.rewrap_impl(
2268 RewrapOptions {
2269 override_language_settings: false,
2270 preserve_existing_whitespace: true,
2271 line_length: None,
2272 },
2273 cx,
2274 );
2275 editor.text(cx)
2276 });
2277 if wrapped_message.trim().is_empty() {
2278 return None;
2279 }
2280 Some(wrapped_message)
2281 }
2282
2283 fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
2284 let text = self.commit_editor.read(cx).text(cx);
2285 if !text.trim().is_empty() {
2286 true
2287 } else if text.is_empty() {
2288 self.suggest_commit_message(cx)
2289 .is_some_and(|text| !text.trim().is_empty())
2290 } else {
2291 false
2292 }
2293 }
2294
2295 pub(crate) fn commit_changes(
2296 &mut self,
2297 options: CommitOptions,
2298 window: &mut Window,
2299 cx: &mut Context<Self>,
2300 ) {
2301 let Some(active_repository) = self.active_repository.clone() else {
2302 return;
2303 };
2304 let error_spawn = |message, window: &mut Window, cx: &mut App| {
2305 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
2306 cx.spawn(async move |_| {
2307 prompt.await.ok();
2308 })
2309 .detach();
2310 };
2311
2312 if self.has_unstaged_conflicts() {
2313 error_spawn(
2314 "There are still conflicts. You must stage these before committing",
2315 window,
2316 cx,
2317 );
2318 return;
2319 }
2320
2321 let askpass = self.askpass_delegate("git commit", window, cx);
2322 let commit_message = self.custom_or_suggested_commit_message(window, cx);
2323
2324 let Some(mut message) = commit_message else {
2325 self.commit_editor
2326 .read(cx)
2327 .focus_handle(cx)
2328 .focus(window, cx);
2329 return;
2330 };
2331
2332 if self.add_coauthors {
2333 self.fill_co_authors(&mut message, cx);
2334 }
2335
2336 let task = if self.has_staged_changes() {
2337 // Repository serializes all git operations, so we can just send a commit immediately
2338 let commit_task = active_repository.update(cx, |repo, cx| {
2339 repo.commit(message.into(), None, options, askpass, cx)
2340 });
2341 cx.background_spawn(async move { commit_task.await? })
2342 } else {
2343 let changed_files = self
2344 .entries
2345 .iter()
2346 .filter_map(|entry| entry.status_entry())
2347 .filter(|status_entry| !status_entry.status.is_created())
2348 .map(|status_entry| status_entry.repo_path.clone())
2349 .collect::<Vec<_>>();
2350
2351 if changed_files.is_empty() && !options.amend {
2352 error_spawn("No changes to commit", window, cx);
2353 return;
2354 }
2355
2356 let stage_task =
2357 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
2358 cx.spawn(async move |_, cx| {
2359 stage_task.await?;
2360 let commit_task = active_repository.update(cx, |repo, cx| {
2361 repo.commit(message.into(), None, options, askpass, cx)
2362 });
2363 commit_task.await?
2364 })
2365 };
2366 let task = cx.spawn_in(window, async move |this, cx| {
2367 let result = task.await;
2368 this.update_in(cx, |this, window, cx| {
2369 this.pending_commit.take();
2370
2371 match result {
2372 Ok(()) => {
2373 if options.amend {
2374 this.set_amend_pending(false, cx);
2375 } else {
2376 this.commit_editor
2377 .update(cx, |editor, cx| editor.clear(window, cx));
2378 this.original_commit_message = None;
2379 }
2380 }
2381 Err(e) => this.show_error_toast("commit", e, cx),
2382 }
2383 })
2384 .ok();
2385 });
2386
2387 self.pending_commit = Some(task);
2388 }
2389
2390 pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2391 let Some(repo) = self.active_repository.clone() else {
2392 return;
2393 };
2394 telemetry::event!("Git Uncommitted");
2395
2396 let confirmation = self.check_for_pushed_commits(window, cx);
2397 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
2398
2399 let task = cx.spawn_in(window, async move |this, cx| {
2400 let result = maybe!(async {
2401 if let Ok(true) = confirmation.await {
2402 let prior_head = prior_head.await?;
2403
2404 repo.update(cx, |repo, cx| {
2405 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
2406 })
2407 .await??;
2408
2409 Ok(Some(prior_head))
2410 } else {
2411 Ok(None)
2412 }
2413 })
2414 .await;
2415
2416 this.update_in(cx, |this, window, cx| {
2417 this.pending_commit.take();
2418 match result {
2419 Ok(None) => {}
2420 Ok(Some(prior_commit)) => {
2421 this.commit_editor.update(cx, |editor, cx| {
2422 editor.set_text(prior_commit.message, window, cx)
2423 });
2424 }
2425 Err(e) => this.show_error_toast("reset", e, cx),
2426 }
2427 })
2428 .ok();
2429 });
2430
2431 self.pending_commit = Some(task);
2432 }
2433
2434 fn check_for_pushed_commits(
2435 &mut self,
2436 window: &mut Window,
2437 cx: &mut Context<Self>,
2438 ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
2439 let repo = self.active_repository.clone();
2440 let mut cx = window.to_async(cx);
2441
2442 async move {
2443 let repo = repo.context("No active repository")?;
2444
2445 let pushed_to: Vec<SharedString> = repo
2446 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())
2447 .await??;
2448
2449 if pushed_to.is_empty() {
2450 Ok(true)
2451 } else {
2452 #[derive(strum::EnumIter, strum::VariantNames)]
2453 #[strum(serialize_all = "title_case")]
2454 enum CancelUncommit {
2455 Uncommit,
2456 Cancel,
2457 }
2458 let detail = format!(
2459 "This commit was already pushed to {}.",
2460 pushed_to.into_iter().join(", ")
2461 );
2462 let result = cx
2463 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
2464 .await?;
2465
2466 match result {
2467 CancelUncommit::Cancel => Ok(false),
2468 CancelUncommit::Uncommit => Ok(true),
2469 }
2470 }
2471 }
2472 }
2473
2474 /// Suggests a commit message based on the changed files and their statuses
2475 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
2476 if let Some(merge_message) = self
2477 .active_repository
2478 .as_ref()
2479 .and_then(|repo| repo.read(cx).merge.message.as_ref())
2480 {
2481 return Some(merge_message.to_string());
2482 }
2483
2484 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
2485 Some(staged_entry)
2486 } else if self.total_staged_count() == 0
2487 && let Some(single_tracked_entry) = &self.single_tracked_entry
2488 {
2489 Some(single_tracked_entry)
2490 } else {
2491 None
2492 }?;
2493
2494 let action_text = if git_status_entry.status.is_deleted() {
2495 Some("Delete")
2496 } else if git_status_entry.status.is_created() {
2497 Some("Create")
2498 } else if git_status_entry.status.is_modified() {
2499 Some("Update")
2500 } else {
2501 None
2502 }?;
2503
2504 let file_name = git_status_entry
2505 .repo_path
2506 .file_name()
2507 .unwrap_or_default()
2508 .to_string();
2509
2510 Some(format!("{} {}", action_text, file_name))
2511 }
2512
2513 fn generate_commit_message_action(
2514 &mut self,
2515 _: &git::GenerateCommitMessage,
2516 _window: &mut Window,
2517 cx: &mut Context<Self>,
2518 ) {
2519 self.generate_commit_message(cx);
2520 }
2521
2522 fn split_patch(patch: &str) -> Vec<String> {
2523 let mut result = Vec::new();
2524 let mut current_patch = String::new();
2525
2526 for line in patch.lines() {
2527 if line.starts_with("---") && !current_patch.is_empty() {
2528 result.push(current_patch.trim_end_matches('\n').into());
2529 current_patch = String::new();
2530 }
2531 current_patch.push_str(line);
2532 current_patch.push('\n');
2533 }
2534
2535 if !current_patch.is_empty() {
2536 result.push(current_patch.trim_end_matches('\n').into());
2537 }
2538
2539 result
2540 }
2541 fn truncate_iteratively(patch: &str, max_bytes: usize) -> String {
2542 let mut current_size = patch.len();
2543 if current_size <= max_bytes {
2544 return patch.to_string();
2545 }
2546 let file_patches = Self::split_patch(patch);
2547 let mut file_infos: Vec<TruncatedPatch> = file_patches
2548 .iter()
2549 .filter_map(|patch| TruncatedPatch::from_unified_diff(patch))
2550 .collect();
2551
2552 if file_infos.is_empty() {
2553 return patch.to_string();
2554 }
2555
2556 current_size = file_infos.iter().map(|f| f.calculate_size()).sum::<usize>();
2557 while current_size > max_bytes {
2558 let file_idx = file_infos
2559 .iter()
2560 .enumerate()
2561 .filter(|(_, f)| f.hunks_to_keep > 1)
2562 .max_by_key(|(_, f)| f.hunks_to_keep)
2563 .map(|(idx, _)| idx);
2564 match file_idx {
2565 Some(idx) => {
2566 let file = &mut file_infos[idx];
2567 let size_before = file.calculate_size();
2568 file.hunks_to_keep -= 1;
2569 let size_after = file.calculate_size();
2570 let saved = size_before.saturating_sub(size_after);
2571 current_size = current_size.saturating_sub(saved);
2572 }
2573 None => {
2574 break;
2575 }
2576 }
2577 }
2578
2579 file_infos
2580 .iter()
2581 .map(|info| info.to_string())
2582 .collect::<Vec<_>>()
2583 .join("\n")
2584 }
2585
2586 pub fn compress_commit_diff(diff_text: &str, max_bytes: usize) -> String {
2587 if diff_text.len() <= max_bytes {
2588 return diff_text.to_string();
2589 }
2590
2591 let mut compressed = diff_text
2592 .lines()
2593 .map(|line| {
2594 if line.len() > 256 {
2595 format!("{}...[truncated]\n", &line[..line.floor_char_boundary(256)])
2596 } else {
2597 format!("{}\n", line)
2598 }
2599 })
2600 .collect::<Vec<_>>()
2601 .join("");
2602
2603 if compressed.len() <= max_bytes {
2604 return compressed;
2605 }
2606
2607 compressed = Self::truncate_iteratively(&compressed, max_bytes);
2608
2609 compressed
2610 }
2611
2612 async fn load_project_rules(
2613 project: &Entity<Project>,
2614 repo_work_dir: &Arc<Path>,
2615 cx: &mut AsyncApp,
2616 ) -> Option<String> {
2617 let rules_path = cx.update(|cx| {
2618 for worktree in project.read(cx).worktrees(cx) {
2619 let worktree_abs_path = worktree.read(cx).abs_path();
2620 if !worktree_abs_path.starts_with(&repo_work_dir) {
2621 continue;
2622 }
2623
2624 let worktree_snapshot = worktree.read(cx).snapshot();
2625 for rules_name in RULES_FILE_NAMES {
2626 if let Ok(rel_path) = RelPath::unix(rules_name) {
2627 if let Some(entry) = worktree_snapshot.entry_for_path(rel_path) {
2628 if entry.is_file() {
2629 return Some(ProjectPath {
2630 worktree_id: worktree.read(cx).id(),
2631 path: entry.path.clone(),
2632 });
2633 }
2634 }
2635 }
2636 }
2637 }
2638 None
2639 })?;
2640
2641 let buffer = project
2642 .update(cx, |project, cx| project.open_buffer(rules_path, cx))
2643 .await
2644 .ok()?;
2645
2646 let content = buffer
2647 .read_with(cx, |buffer, _| buffer.text())
2648 .trim()
2649 .to_string();
2650
2651 if content.is_empty() {
2652 None
2653 } else {
2654 Some(content)
2655 }
2656 }
2657
2658 async fn load_commit_message_prompt(cx: &mut AsyncApp) -> String {
2659 let load = async {
2660 let store = cx.update(|cx| PromptStore::global(cx)).await.ok()?;
2661 store
2662 .update(cx, |s, cx| {
2663 s.load(PromptId::BuiltIn(BuiltInPrompt::CommitMessage), cx)
2664 })
2665 .await
2666 .ok()
2667 };
2668 load.await
2669 .unwrap_or_else(|| BuiltInPrompt::CommitMessage.default_content().to_string())
2670 }
2671
2672 /// Generates a commit message using an LLM.
2673 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
2674 if !self.can_commit() || !AgentSettings::get_global(cx).enabled(cx) {
2675 return;
2676 }
2677
2678 let Some(ConfiguredModel { provider, model }) =
2679 LanguageModelRegistry::read_global(cx).commit_message_model()
2680 else {
2681 return;
2682 };
2683
2684 let Some(repo) = self.active_repository.as_ref() else {
2685 return;
2686 };
2687
2688 telemetry::event!("Git Commit Message Generated");
2689
2690 let diff = repo.update(cx, |repo, cx| {
2691 if self.has_staged_changes() {
2692 repo.diff(DiffType::HeadToIndex, cx)
2693 } else {
2694 repo.diff(DiffType::HeadToWorktree, cx)
2695 }
2696 });
2697
2698 let temperature = AgentSettings::temperature_for_model(&model, cx);
2699 let project = self.project.clone();
2700 let repo_work_dir = repo.read(cx).work_directory_abs_path.clone();
2701
2702 self.generate_commit_message_task = Some(cx.spawn(async move |this, mut cx| {
2703 async move {
2704 let _defer = cx.on_drop(&this, |this, _cx| {
2705 this.generate_commit_message_task.take();
2706 });
2707
2708 if let Some(task) = cx.update(|cx| {
2709 if !provider.is_authenticated(cx) {
2710 Some(provider.authenticate(cx))
2711 } else {
2712 None
2713 }
2714 }) {
2715 task.await.log_err();
2716 }
2717
2718 let mut diff_text = match diff.await {
2719 Ok(result) => match result {
2720 Ok(text) => text,
2721 Err(e) => {
2722 Self::show_commit_message_error(&this, &e, cx);
2723 return anyhow::Ok(());
2724 }
2725 },
2726 Err(e) => {
2727 Self::show_commit_message_error(&this, &e, cx);
2728 return anyhow::Ok(());
2729 }
2730 };
2731
2732 const MAX_DIFF_BYTES: usize = 20_000;
2733 diff_text = Self::compress_commit_diff(&diff_text, MAX_DIFF_BYTES);
2734
2735 let rules_content = Self::load_project_rules(&project, &repo_work_dir, &mut cx).await;
2736
2737 let prompt = Self::load_commit_message_prompt(&mut cx).await;
2738
2739 let subject = this.update(cx, |this, cx| {
2740 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
2741 })?;
2742
2743 let text_empty = subject.trim().is_empty();
2744
2745 let rules_section = match &rules_content {
2746 Some(rules) => format!(
2747 "\n\nThe user has provided the following project rules that you should follow when writing the commit message:\n\
2748 <project_rules>\n{rules}\n</project_rules>\n"
2749 ),
2750 None => String::new(),
2751 };
2752
2753 let subject_section = if text_empty {
2754 String::new()
2755 } else {
2756 format!("\nHere is the user's subject line:\n{subject}")
2757 };
2758
2759 let content = format!(
2760 "{prompt}{rules_section}{subject_section}\nHere are the changes in this commit:\n{diff_text}"
2761 );
2762
2763 let request = LanguageModelRequest {
2764 thread_id: None,
2765 prompt_id: None,
2766 intent: Some(CompletionIntent::GenerateGitCommitMessage),
2767 messages: vec![LanguageModelRequestMessage {
2768 role: Role::User,
2769 content: vec![content.into()],
2770 cache: false,
2771 reasoning_details: None,
2772 }],
2773 tools: Vec::new(),
2774 tool_choice: None,
2775 stop: Vec::new(),
2776 temperature,
2777 thinking_allowed: false,
2778 thinking_effort: None,
2779 speed: None,
2780 };
2781
2782 let stream = model.stream_completion_text(request, cx);
2783 match stream.await {
2784 Ok(mut messages) => {
2785 if !text_empty {
2786 this.update(cx, |this, cx| {
2787 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2788 let insert_position = buffer.anchor_before(buffer.len());
2789 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
2790 });
2791 })?;
2792 }
2793
2794 while let Some(message) = messages.stream.next().await {
2795 match message {
2796 Ok(text) => {
2797 this.update(cx, |this, cx| {
2798 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2799 let insert_position = buffer.anchor_before(buffer.len());
2800 buffer.edit([(insert_position..insert_position, text)], None, cx);
2801 });
2802 })?;
2803 }
2804 Err(e) => {
2805 Self::show_commit_message_error(&this, &e, cx);
2806 break;
2807 }
2808 }
2809 }
2810 }
2811 Err(e) => {
2812 Self::show_commit_message_error(&this, &e, cx);
2813 }
2814 }
2815
2816 anyhow::Ok(())
2817 }
2818 .log_err().await
2819 }));
2820 }
2821
2822 fn get_fetch_options(
2823 &self,
2824 window: &mut Window,
2825 cx: &mut Context<Self>,
2826 ) -> Task<Option<FetchOptions>> {
2827 let repo = self.active_repository.clone();
2828 let workspace = self.workspace.clone();
2829
2830 cx.spawn_in(window, async move |_, cx| {
2831 let repo = repo?;
2832 let remotes = repo
2833 .update(cx, |repo, _| repo.get_remotes(None, false))
2834 .await
2835 .ok()?
2836 .log_err()?;
2837
2838 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2839 if remotes.len() > 1 {
2840 remotes.push(FetchOptions::All);
2841 }
2842 let selection = cx
2843 .update(|window, cx| {
2844 picker_prompt::prompt(
2845 "Pick which remote to fetch",
2846 remotes.iter().map(|r| r.name()).collect(),
2847 workspace,
2848 window,
2849 cx,
2850 )
2851 })
2852 .ok()?
2853 .await?;
2854 remotes.get(selection).cloned()
2855 })
2856 }
2857
2858 pub(crate) fn fetch(
2859 &mut self,
2860 is_fetch_all: bool,
2861 window: &mut Window,
2862 cx: &mut Context<Self>,
2863 ) {
2864 if !self.can_push_and_pull(cx) {
2865 return;
2866 }
2867
2868 let Some(repo) = self.active_repository.clone() else {
2869 return;
2870 };
2871 telemetry::event!("Git Fetched");
2872 let askpass = self.askpass_delegate("git fetch", window, cx);
2873 let this = cx.weak_entity();
2874
2875 let fetch_options = if is_fetch_all {
2876 Task::ready(Some(FetchOptions::All))
2877 } else {
2878 self.get_fetch_options(window, cx)
2879 };
2880
2881 window
2882 .spawn(cx, async move |cx| {
2883 let Some(fetch_options) = fetch_options.await else {
2884 return Ok(());
2885 };
2886 let fetch = repo.update(cx, |repo, cx| {
2887 repo.fetch(fetch_options.clone(), askpass, cx)
2888 });
2889
2890 let remote_message = fetch.await?;
2891 this.update(cx, |this, cx| {
2892 let action = match fetch_options {
2893 FetchOptions::All => RemoteAction::Fetch(None),
2894 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2895 };
2896 match remote_message {
2897 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2898 Err(e) => {
2899 log::error!("Error while fetching {:?}", e);
2900 this.show_error_toast(action.name(), e, cx)
2901 }
2902 }
2903
2904 anyhow::Ok(())
2905 })
2906 .ok();
2907 anyhow::Ok(())
2908 })
2909 .detach_and_log_err(cx);
2910 }
2911
2912 pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2913 let workspace = self.workspace.clone();
2914
2915 crate::clone::clone_and_open(
2916 repo.into(),
2917 workspace,
2918 window,
2919 cx,
2920 Arc::new(|_workspace: &mut workspace::Workspace, _window, _cx| {}),
2921 );
2922 }
2923
2924 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2925 let worktrees = self
2926 .project
2927 .read(cx)
2928 .visible_worktrees(cx)
2929 .collect::<Vec<_>>();
2930
2931 let worktree = if worktrees.len() == 1 {
2932 Task::ready(Some(worktrees.first().unwrap().clone()))
2933 } else if worktrees.is_empty() {
2934 let result = window.prompt(
2935 PromptLevel::Warning,
2936 "Unable to initialize a git repository",
2937 Some("Open a directory first"),
2938 &["Ok"],
2939 cx,
2940 );
2941 cx.background_executor()
2942 .spawn(async move {
2943 result.await.ok();
2944 })
2945 .detach();
2946 return;
2947 } else {
2948 let worktree_directories = worktrees
2949 .iter()
2950 .map(|worktree| worktree.read(cx).abs_path())
2951 .map(|worktree_abs_path| {
2952 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2953 Path::new("~")
2954 .join(path)
2955 .to_string_lossy()
2956 .to_string()
2957 .into()
2958 } else {
2959 worktree_abs_path.to_string_lossy().into_owned().into()
2960 }
2961 })
2962 .collect_vec();
2963 let prompt = picker_prompt::prompt(
2964 "Where would you like to initialize this git repository?",
2965 worktree_directories,
2966 self.workspace.clone(),
2967 window,
2968 cx,
2969 );
2970
2971 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2972 };
2973
2974 cx.spawn_in(window, async move |this, cx| {
2975 let worktree = match worktree.await {
2976 Some(worktree) => worktree,
2977 None => {
2978 return;
2979 }
2980 };
2981
2982 let Ok(result) = this.update(cx, |this, cx| {
2983 let fallback_branch_name = GitPanelSettings::get_global(cx)
2984 .fallback_branch_name
2985 .clone();
2986 this.project.read(cx).git_init(
2987 worktree.read(cx).abs_path(),
2988 fallback_branch_name,
2989 cx,
2990 )
2991 }) else {
2992 return;
2993 };
2994
2995 let result = result.await;
2996
2997 this.update_in(cx, |this, _, cx| match result {
2998 Ok(()) => {}
2999 Err(e) => this.show_error_toast("init", e, cx),
3000 })
3001 .ok();
3002 })
3003 .detach();
3004 }
3005
3006 pub(crate) fn pull(&mut self, rebase: bool, window: &mut Window, cx: &mut Context<Self>) {
3007 if !self.can_push_and_pull(cx) {
3008 return;
3009 }
3010 let Some(repo) = self.active_repository.clone() else {
3011 return;
3012 };
3013 let Some(branch) = repo.read(cx).branch.as_ref() else {
3014 return;
3015 };
3016 telemetry::event!("Git Pulled");
3017 let branch = branch.clone();
3018 let remote = self.get_remote(false, false, window, cx);
3019 cx.spawn_in(window, async move |this, cx| {
3020 let remote = match remote.await {
3021 Ok(Some(remote)) => remote,
3022 Ok(None) => {
3023 return Ok(());
3024 }
3025 Err(e) => {
3026 log::error!("Failed to get current remote: {}", e);
3027 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
3028 .ok();
3029 return Ok(());
3030 }
3031 };
3032
3033 let askpass = this.update_in(cx, |this, window, cx| {
3034 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
3035 })?;
3036
3037 let branch_name = branch
3038 .upstream
3039 .is_none()
3040 .then(|| branch.name().to_owned().into());
3041
3042 let pull = repo.update(cx, |repo, cx| {
3043 repo.pull(branch_name, remote.name.clone(), rebase, askpass, cx)
3044 });
3045
3046 let remote_message = pull.await?;
3047
3048 let action = RemoteAction::Pull(remote);
3049 this.update(cx, |this, cx| match remote_message {
3050 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3051 Err(e) => {
3052 log::error!("Error while pulling {:?}", e);
3053 this.show_error_toast(action.name(), e, cx)
3054 }
3055 })
3056 .ok();
3057
3058 anyhow::Ok(())
3059 })
3060 .detach_and_log_err(cx);
3061 }
3062
3063 pub(crate) fn push(
3064 &mut self,
3065 force_push: bool,
3066 select_remote: bool,
3067 window: &mut Window,
3068 cx: &mut Context<Self>,
3069 ) {
3070 if !self.can_push_and_pull(cx) {
3071 return;
3072 }
3073 let Some(repo) = self.active_repository.clone() else {
3074 return;
3075 };
3076 let Some(branch) = repo.read(cx).branch.as_ref() else {
3077 return;
3078 };
3079 telemetry::event!("Git Pushed");
3080 let branch = branch.clone();
3081
3082 let options = if force_push {
3083 Some(PushOptions::Force)
3084 } else {
3085 match branch.upstream {
3086 Some(Upstream {
3087 tracking: UpstreamTracking::Gone,
3088 ..
3089 })
3090 | None => Some(PushOptions::SetUpstream),
3091 _ => None,
3092 }
3093 };
3094 let remote = self.get_remote(select_remote, true, window, cx);
3095
3096 cx.spawn_in(window, async move |this, cx| {
3097 let remote = match remote.await {
3098 Ok(Some(remote)) => remote,
3099 Ok(None) => {
3100 return Ok(());
3101 }
3102 Err(e) => {
3103 log::error!("Failed to get current remote: {}", e);
3104 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
3105 .ok();
3106 return Ok(());
3107 }
3108 };
3109
3110 let askpass_delegate = this.update_in(cx, |this, window, cx| {
3111 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
3112 })?;
3113
3114 let push = repo.update(cx, |repo, cx| {
3115 repo.push(
3116 branch.name().to_owned().into(),
3117 branch
3118 .upstream
3119 .as_ref()
3120 .filter(|u| matches!(u.tracking, UpstreamTracking::Tracked(_)))
3121 .and_then(|u| u.branch_name())
3122 .unwrap_or_else(|| branch.name())
3123 .to_owned()
3124 .into(),
3125 remote.name.clone(),
3126 options,
3127 askpass_delegate,
3128 cx,
3129 )
3130 });
3131
3132 let remote_output = push.await?;
3133
3134 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
3135 this.update(cx, |this, cx| match remote_output {
3136 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3137 Err(e) => {
3138 log::error!("Error while pushing {:?}", e);
3139 this.show_error_toast(action.name(), e, cx)
3140 }
3141 })?;
3142
3143 anyhow::Ok(())
3144 })
3145 .detach_and_log_err(cx);
3146 }
3147
3148 pub fn create_pull_request(&self, window: &mut Window, cx: &mut Context<Self>) {
3149 let result = (|| -> anyhow::Result<()> {
3150 let repo = self
3151 .active_repository
3152 .clone()
3153 .ok_or_else(|| anyhow::anyhow!("No active repository"))?;
3154
3155 let (branch, remote_origin, remote_upstream) = {
3156 let repository = repo.read(cx);
3157 (
3158 repository.branch.clone(),
3159 repository.remote_origin_url.clone(),
3160 repository.remote_upstream_url.clone(),
3161 )
3162 };
3163
3164 let branch = branch.ok_or_else(|| anyhow::anyhow!("No active branch"))?;
3165 let source_branch = branch
3166 .upstream
3167 .as_ref()
3168 .filter(|upstream| matches!(upstream.tracking, UpstreamTracking::Tracked(_)))
3169 .and_then(|upstream| upstream.branch_name())
3170 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3171 let source_branch = source_branch.to_string();
3172
3173 let remote_url = branch
3174 .upstream
3175 .as_ref()
3176 .and_then(|upstream| match upstream.remote_name() {
3177 Some("upstream") => remote_upstream.as_deref(),
3178 Some(_) => remote_origin.as_deref(),
3179 None => None,
3180 })
3181 .or(remote_origin.as_deref())
3182 .or(remote_upstream.as_deref())
3183 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3184 let remote_url = remote_url.to_string();
3185
3186 let provider_registry = GitHostingProviderRegistry::global(cx);
3187 let Some((provider, parsed_remote)) =
3188 git::parse_git_remote_url(provider_registry, &remote_url)
3189 else {
3190 return Err(anyhow::anyhow!("Unsupported remote URL: {}", remote_url));
3191 };
3192
3193 let Some(url) = provider.build_create_pull_request_url(&parsed_remote, &source_branch)
3194 else {
3195 return Err(anyhow::anyhow!("Unable to construct pull request URL"));
3196 };
3197
3198 cx.open_url(url.as_str());
3199 Ok(())
3200 })();
3201
3202 if let Err(err) = result {
3203 log::error!("Error while creating pull request {:?}", err);
3204 cx.defer_in(window, |panel, _window, cx| {
3205 panel.show_error_toast("create pull request", err, cx);
3206 });
3207 }
3208 }
3209
3210 fn askpass_delegate(
3211 &self,
3212 operation: impl Into<SharedString>,
3213 window: &mut Window,
3214 cx: &mut Context<Self>,
3215 ) -> AskPassDelegate {
3216 let workspace = self.workspace.clone();
3217 let operation = operation.into();
3218 let window = window.window_handle();
3219 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
3220 window
3221 .update(cx, |_, window, cx| {
3222 workspace.update(cx, |workspace, cx| {
3223 workspace.toggle_modal(window, cx, |window, cx| {
3224 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
3225 });
3226 })
3227 })
3228 .ok();
3229 })
3230 }
3231
3232 fn can_push_and_pull(&self, cx: &App) -> bool {
3233 !self.project.read(cx).is_via_collab()
3234 }
3235
3236 fn get_remote(
3237 &mut self,
3238 always_select: bool,
3239 is_push: bool,
3240 window: &mut Window,
3241 cx: &mut Context<Self>,
3242 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
3243 let repo = self.active_repository.clone();
3244 let workspace = self.workspace.clone();
3245 let mut cx = window.to_async(cx);
3246
3247 async move {
3248 let repo = repo.context("No active repository")?;
3249 let current_remotes: Vec<Remote> = repo
3250 .update(&mut cx, |repo, _| {
3251 let current_branch = if always_select {
3252 None
3253 } else {
3254 let current_branch = repo.branch.as_ref().context("No active branch")?;
3255 Some(current_branch.name().to_string())
3256 };
3257 anyhow::Ok(repo.get_remotes(current_branch, is_push))
3258 })?
3259 .await??;
3260
3261 let current_remotes: Vec<_> = current_remotes
3262 .into_iter()
3263 .map(|remotes| remotes.name)
3264 .collect();
3265 let selection = cx
3266 .update(|window, cx| {
3267 picker_prompt::prompt(
3268 "Pick which remote to push to",
3269 current_remotes.clone(),
3270 workspace,
3271 window,
3272 cx,
3273 )
3274 })?
3275 .await;
3276
3277 Ok(selection.map(|selection| Remote {
3278 name: current_remotes[selection].clone(),
3279 }))
3280 }
3281 }
3282
3283 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
3284 if self.local_committer_task.is_none() {
3285 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
3286 let committer = get_git_committer(cx).await;
3287 this.update(cx, |this, cx| {
3288 this.local_committer = Some(committer);
3289 cx.notify()
3290 })
3291 .ok();
3292 }));
3293 }
3294 }
3295
3296 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
3297 let mut new_co_authors = Vec::new();
3298 let project = self.project.read(cx);
3299
3300 let Some(room) =
3301 call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
3302 else {
3303 return Vec::default();
3304 };
3305
3306 let room = room.read(cx);
3307
3308 for (peer_id, collaborator) in project.collaborators() {
3309 if collaborator.is_host {
3310 continue;
3311 }
3312
3313 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
3314 continue;
3315 };
3316 if !participant.can_write() {
3317 continue;
3318 }
3319 if let Some(email) = &collaborator.committer_email {
3320 let name = collaborator
3321 .committer_name
3322 .clone()
3323 .or_else(|| participant.user.name.clone())
3324 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
3325 new_co_authors.push((name.clone(), email.clone()))
3326 }
3327 }
3328 if !project.is_local()
3329 && !project.is_read_only(cx)
3330 && let Some(local_committer) = self.local_committer(room, cx)
3331 {
3332 new_co_authors.push(local_committer);
3333 }
3334 new_co_authors
3335 }
3336
3337 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
3338 let user = room.local_participant_user(cx)?;
3339 let committer = self.local_committer.as_ref()?;
3340 let email = committer.email.clone()?;
3341 let name = committer
3342 .name
3343 .clone()
3344 .or_else(|| user.name.clone())
3345 .unwrap_or_else(|| user.github_login.clone().to_string());
3346 Some((name, email))
3347 }
3348
3349 fn toggle_fill_co_authors(
3350 &mut self,
3351 _: &ToggleFillCoAuthors,
3352 _: &mut Window,
3353 cx: &mut Context<Self>,
3354 ) {
3355 self.add_coauthors = !self.add_coauthors;
3356 cx.notify();
3357 }
3358
3359 fn toggle_sort_by_path(
3360 &mut self,
3361 _: &ToggleSortByPath,
3362 _: &mut Window,
3363 cx: &mut Context<Self>,
3364 ) {
3365 let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
3366 if let Some(workspace) = self.workspace.upgrade() {
3367 let workspace = workspace.read(cx);
3368 let fs = workspace.app_state().fs.clone();
3369 cx.update_global::<SettingsStore, _>(|store, _cx| {
3370 store.update_settings_file(fs, move |settings, _cx| {
3371 settings.git_panel.get_or_insert_default().sort_by_path =
3372 Some(!current_setting);
3373 });
3374 });
3375 }
3376 }
3377
3378 fn toggle_tree_view(&mut self, _: &ToggleTreeView, _: &mut Window, cx: &mut Context<Self>) {
3379 let current_setting = GitPanelSettings::get_global(cx).tree_view;
3380 if let Some(workspace) = self.workspace.upgrade() {
3381 let workspace = workspace.read(cx);
3382 let fs = workspace.app_state().fs.clone();
3383 cx.update_global::<SettingsStore, _>(|store, _cx| {
3384 store.update_settings_file(fs, move |settings, _cx| {
3385 settings.git_panel.get_or_insert_default().tree_view = Some(!current_setting);
3386 });
3387 })
3388 }
3389 }
3390
3391 fn toggle_directory(&mut self, key: &TreeKey, window: &mut Window, cx: &mut Context<Self>) {
3392 if let Some(state) = self.view_mode.tree_state_mut() {
3393 let expanded = state.expanded_dirs.entry(key.clone()).or_insert(true);
3394 *expanded = !*expanded;
3395 self.update_visible_entries(window, cx);
3396 } else {
3397 util::debug_panic!("Attempted to toggle directory in flat Git Panel state");
3398 }
3399 }
3400
3401 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
3402 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
3403
3404 let existing_text = message.to_ascii_lowercase();
3405 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
3406 let mut ends_with_co_authors = false;
3407 let existing_co_authors = existing_text
3408 .lines()
3409 .filter_map(|line| {
3410 let line = line.trim();
3411 if line.starts_with(&lowercase_co_author_prefix) {
3412 ends_with_co_authors = true;
3413 Some(line)
3414 } else {
3415 ends_with_co_authors = false;
3416 None
3417 }
3418 })
3419 .collect::<HashSet<_>>();
3420
3421 let new_co_authors = self
3422 .potential_co_authors(cx)
3423 .into_iter()
3424 .filter(|(_, email)| {
3425 !existing_co_authors
3426 .iter()
3427 .any(|existing| existing.contains(email.as_str()))
3428 })
3429 .collect::<Vec<_>>();
3430
3431 if new_co_authors.is_empty() {
3432 return;
3433 }
3434
3435 if !ends_with_co_authors {
3436 message.push('\n');
3437 }
3438 for (name, email) in new_co_authors {
3439 message.push('\n');
3440 message.push_str(CO_AUTHOR_PREFIX);
3441 message.push_str(&name);
3442 message.push_str(" <");
3443 message.push_str(&email);
3444 message.push('>');
3445 }
3446 message.push('\n');
3447 }
3448
3449 fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3450 let handle = cx.entity().downgrade();
3451 self.reopen_commit_buffer(window, cx);
3452 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
3453 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
3454 if let Some(git_panel) = handle.upgrade() {
3455 git_panel
3456 .update_in(cx, |git_panel, window, cx| {
3457 git_panel.update_visible_entries(window, cx);
3458 })
3459 .ok();
3460 }
3461 });
3462 }
3463
3464 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3465 let Some(active_repo) = self.active_repository.as_ref() else {
3466 return;
3467 };
3468 let load_buffer = active_repo.update(cx, |active_repo, cx| {
3469 let project = self.project.read(cx);
3470 active_repo.open_commit_buffer(
3471 Some(project.languages().clone()),
3472 project.buffer_store().clone(),
3473 cx,
3474 )
3475 });
3476
3477 cx.spawn_in(window, async move |git_panel, cx| {
3478 let buffer = load_buffer.await?;
3479 git_panel.update_in(cx, |git_panel, window, cx| {
3480 if git_panel
3481 .commit_editor
3482 .read(cx)
3483 .buffer()
3484 .read(cx)
3485 .as_singleton()
3486 .as_ref()
3487 != Some(&buffer)
3488 {
3489 git_panel.commit_editor = cx.new(|cx| {
3490 commit_message_editor(
3491 buffer,
3492 git_panel.suggest_commit_message(cx).map(SharedString::from),
3493 git_panel.project.clone(),
3494 true,
3495 window,
3496 cx,
3497 )
3498 });
3499 }
3500 })
3501 })
3502 .detach_and_log_err(cx);
3503 }
3504
3505 fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3506 let path_style = self.project.read(cx).path_style(cx);
3507 let bulk_staging = self.bulk_staging.take();
3508 let last_staged_path_prev_index = bulk_staging
3509 .as_ref()
3510 .and_then(|op| self.entry_by_path(&op.anchor));
3511
3512 self.active_repository = self.project.read(cx).active_repository(cx);
3513 self.entries.clear();
3514 self.entries_indices.clear();
3515 self.single_staged_entry.take();
3516 self.single_tracked_entry.take();
3517 self.conflicted_count = 0;
3518 self.conflicted_staged_count = 0;
3519 self.changes_count = 0;
3520 self.new_count = 0;
3521 self.tracked_count = 0;
3522 self.new_staged_count = 0;
3523 self.tracked_staged_count = 0;
3524 self.entry_count = 0;
3525 self.max_width_item_index = None;
3526
3527 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
3528 let is_tree_view = matches!(self.view_mode, GitPanelViewMode::Tree(_));
3529 let group_by_status = is_tree_view || !sort_by_path;
3530
3531 let mut changed_entries = Vec::new();
3532 let mut new_entries = Vec::new();
3533 let mut conflict_entries = Vec::new();
3534 let mut single_staged_entry = None;
3535 let mut staged_count = 0;
3536 let mut seen_directories = HashSet::default();
3537 let mut max_width_estimate = 0usize;
3538 let mut max_width_item_index = None;
3539
3540 let Some(repo) = self.active_repository.as_ref() else {
3541 // Just clear entries if no repository is active.
3542 cx.notify();
3543 return;
3544 };
3545
3546 let repo = repo.read(cx);
3547
3548 self.stash_entries = repo.cached_stash();
3549
3550 for entry in repo.cached_status() {
3551 self.changes_count += 1;
3552 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
3553 let is_new = entry.status.is_created();
3554 let staging = entry.status.staging();
3555
3556 if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
3557 && pending
3558 .ops
3559 .iter()
3560 .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
3561 {
3562 continue;
3563 }
3564
3565 let entry = GitStatusEntry {
3566 repo_path: entry.repo_path.clone(),
3567 status: entry.status,
3568 staging,
3569 diff_stat: entry.diff_stat,
3570 };
3571
3572 if staging.has_staged() {
3573 staged_count += 1;
3574 single_staged_entry = Some(entry.clone());
3575 }
3576
3577 if group_by_status && is_conflict {
3578 conflict_entries.push(entry);
3579 } else if group_by_status && is_new {
3580 new_entries.push(entry);
3581 } else {
3582 changed_entries.push(entry);
3583 }
3584 }
3585
3586 if conflict_entries.is_empty() {
3587 if staged_count == 1
3588 && let Some(entry) = single_staged_entry.as_ref()
3589 {
3590 if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
3591 if ops.staged() {
3592 self.single_staged_entry = single_staged_entry;
3593 }
3594 } else {
3595 self.single_staged_entry = single_staged_entry;
3596 }
3597 } else if repo.pending_ops_summary().item_summary.staging_count == 1
3598 && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
3599 {
3600 self.single_staged_entry =
3601 repo.status_for_path(&ops.repo_path)
3602 .map(|status| GitStatusEntry {
3603 repo_path: ops.repo_path.clone(),
3604 status: status.status,
3605 staging: StageStatus::Staged,
3606 diff_stat: status.diff_stat,
3607 });
3608 }
3609 }
3610
3611 if conflict_entries.is_empty() && changed_entries.len() == 1 {
3612 self.single_tracked_entry = changed_entries.first().cloned();
3613 }
3614
3615 let mut push_entry =
3616 |this: &mut Self,
3617 entry: GitListEntry,
3618 is_visible: bool,
3619 logical_indices: Option<&mut Vec<usize>>| {
3620 if let Some(estimate) =
3621 this.width_estimate_for_list_entry(is_tree_view, &entry, path_style)
3622 {
3623 if estimate > max_width_estimate {
3624 max_width_estimate = estimate;
3625 max_width_item_index = Some(this.entries.len());
3626 }
3627 }
3628
3629 if let Some(repo_path) = entry.status_entry().map(|status| status.repo_path.clone())
3630 {
3631 this.entries_indices.insert(repo_path, this.entries.len());
3632 }
3633
3634 if let (Some(indices), true) = (logical_indices, is_visible) {
3635 indices.push(this.entries.len());
3636 }
3637
3638 this.entries.push(entry);
3639 };
3640
3641 macro_rules! take_section_entries {
3642 () => {
3643 [
3644 (Section::Conflict, std::mem::take(&mut conflict_entries)),
3645 (Section::Tracked, std::mem::take(&mut changed_entries)),
3646 (Section::New, std::mem::take(&mut new_entries)),
3647 ]
3648 };
3649 }
3650
3651 match &mut self.view_mode {
3652 GitPanelViewMode::Tree(tree_state) => {
3653 tree_state.logical_indices.clear();
3654 tree_state.directory_descendants.clear();
3655
3656 // This is just to get around the borrow checker
3657 // because push_entry mutably borrows self
3658 let mut tree_state = std::mem::take(tree_state);
3659
3660 for (section, entries) in take_section_entries!() {
3661 if entries.is_empty() {
3662 continue;
3663 }
3664
3665 push_entry(
3666 self,
3667 GitListEntry::Header(GitHeaderEntry { header: section }),
3668 true,
3669 Some(&mut tree_state.logical_indices),
3670 );
3671
3672 for (entry, is_visible) in
3673 tree_state.build_tree_entries(section, entries, &mut seen_directories)
3674 {
3675 push_entry(
3676 self,
3677 entry,
3678 is_visible,
3679 Some(&mut tree_state.logical_indices),
3680 );
3681 }
3682 }
3683
3684 tree_state
3685 .expanded_dirs
3686 .retain(|key, _| seen_directories.contains(key));
3687 self.view_mode = GitPanelViewMode::Tree(tree_state);
3688 }
3689 GitPanelViewMode::Flat => {
3690 for (section, entries) in take_section_entries!() {
3691 if entries.is_empty() {
3692 continue;
3693 }
3694
3695 if section != Section::Tracked || !sort_by_path {
3696 push_entry(
3697 self,
3698 GitListEntry::Header(GitHeaderEntry { header: section }),
3699 true,
3700 None,
3701 );
3702 }
3703
3704 for entry in entries {
3705 push_entry(self, GitListEntry::Status(entry), true, None);
3706 }
3707 }
3708 }
3709 }
3710
3711 self.max_width_item_index = max_width_item_index;
3712
3713 self.update_counts(repo);
3714
3715 let bulk_staging_anchor_new_index = bulk_staging
3716 .as_ref()
3717 .filter(|op| op.repo_id == repo.id)
3718 .and_then(|op| self.entry_by_path(&op.anchor));
3719 if bulk_staging_anchor_new_index == last_staged_path_prev_index
3720 && let Some(index) = bulk_staging_anchor_new_index
3721 && let Some(entry) = self.entries.get(index)
3722 && let Some(entry) = entry.status_entry()
3723 && GitPanel::stage_status_for_entry(entry, &repo)
3724 .as_bool()
3725 .unwrap_or(false)
3726 {
3727 self.bulk_staging = bulk_staging;
3728 }
3729
3730 self.select_first_entry_if_none(window, cx);
3731
3732 let suggested_commit_message = self.suggest_commit_message(cx);
3733 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
3734
3735 self.commit_editor.update(cx, |editor, cx| {
3736 editor.set_placeholder_text(&placeholder_text, window, cx)
3737 });
3738
3739 cx.notify();
3740 }
3741
3742 fn header_state(&self, header_type: Section) -> ToggleState {
3743 let (staged_count, count) = match header_type {
3744 Section::New => (self.new_staged_count, self.new_count),
3745 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
3746 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
3747 };
3748 if staged_count == 0 {
3749 ToggleState::Unselected
3750 } else if count == staged_count {
3751 ToggleState::Selected
3752 } else {
3753 ToggleState::Indeterminate
3754 }
3755 }
3756
3757 fn update_counts(&mut self, repo: &Repository) {
3758 self.show_placeholders = false;
3759 self.conflicted_count = 0;
3760 self.conflicted_staged_count = 0;
3761 self.new_count = 0;
3762 self.tracked_count = 0;
3763 self.new_staged_count = 0;
3764 self.tracked_staged_count = 0;
3765 self.entry_count = 0;
3766
3767 for status_entry in self.entries.iter().filter_map(|entry| entry.status_entry()) {
3768 self.entry_count += 1;
3769 let is_staging_or_staged = GitPanel::stage_status_for_entry(status_entry, repo)
3770 .as_bool()
3771 .unwrap_or(true);
3772
3773 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
3774 self.conflicted_count += 1;
3775 if is_staging_or_staged {
3776 self.conflicted_staged_count += 1;
3777 }
3778 } else if status_entry.status.is_created() {
3779 self.new_count += 1;
3780 if is_staging_or_staged {
3781 self.new_staged_count += 1;
3782 }
3783 } else {
3784 self.tracked_count += 1;
3785 if is_staging_or_staged {
3786 self.tracked_staged_count += 1;
3787 }
3788 }
3789 }
3790 }
3791
3792 pub(crate) fn has_staged_changes(&self) -> bool {
3793 self.tracked_staged_count > 0
3794 || self.new_staged_count > 0
3795 || self.conflicted_staged_count > 0
3796 }
3797
3798 pub(crate) fn has_unstaged_changes(&self) -> bool {
3799 self.tracked_count > self.tracked_staged_count
3800 || self.new_count > self.new_staged_count
3801 || self.conflicted_count > self.conflicted_staged_count
3802 }
3803
3804 fn has_tracked_changes(&self) -> bool {
3805 self.tracked_count > 0
3806 }
3807
3808 pub fn has_unstaged_conflicts(&self) -> bool {
3809 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3810 }
3811
3812 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3813 let Some(workspace) = self.workspace.upgrade() else {
3814 return;
3815 };
3816 show_error_toast(workspace, action, e, cx)
3817 }
3818
3819 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3820 where
3821 E: std::fmt::Debug + std::fmt::Display,
3822 {
3823 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3824 let _ = workspace.update(cx, |workspace, cx| {
3825 struct CommitMessageError;
3826 let notification_id = NotificationId::unique::<CommitMessageError>();
3827 workspace.show_notification(notification_id, cx, |cx| {
3828 cx.new(|cx| {
3829 ErrorMessagePrompt::new(
3830 format!("Failed to generate commit message: {err}"),
3831 cx,
3832 )
3833 })
3834 });
3835 });
3836 }
3837 }
3838
3839 fn show_remote_output(
3840 &mut self,
3841 action: RemoteAction,
3842 info: RemoteCommandOutput,
3843 cx: &mut Context<Self>,
3844 ) {
3845 let Some(workspace) = self.workspace.upgrade() else {
3846 return;
3847 };
3848
3849 workspace.update(cx, |workspace, cx| {
3850 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3851 let workspace_weak = cx.weak_entity();
3852 let operation = action.name();
3853
3854 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3855 use remote_output::SuccessStyle::*;
3856 match style {
3857 Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3858 ToastWithLog { output } => this
3859 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3860 .action("View Log", move |window, cx| {
3861 let output = output.clone();
3862 let output =
3863 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3864 workspace_weak
3865 .update(cx, move |workspace, cx| {
3866 open_output(operation, workspace, &output, window, cx)
3867 })
3868 .ok();
3869 }),
3870 PushPrLink { text, link } => this
3871 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3872 .action(text, move |_, cx| cx.open_url(&link)),
3873 }
3874 .dismiss_button(true)
3875 });
3876 workspace.toggle_status_toast(status_toast, cx)
3877 });
3878 }
3879
3880 pub fn can_commit(&self) -> bool {
3881 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3882 }
3883
3884 pub fn can_stage_all(&self) -> bool {
3885 self.has_unstaged_changes()
3886 }
3887
3888 pub fn can_unstage_all(&self) -> bool {
3889 self.has_staged_changes()
3890 }
3891
3892 /// Computes tree indentation depths for visible entries in the given range.
3893 /// Used by indent guides to render vertical connector lines in tree view.
3894 fn compute_visible_depths(&self, range: Range<usize>) -> SmallVec<[usize; 64]> {
3895 let GitPanelViewMode::Tree(state) = &self.view_mode else {
3896 return SmallVec::new();
3897 };
3898
3899 range
3900 .map(|ix| {
3901 state
3902 .logical_indices
3903 .get(ix)
3904 .and_then(|&entry_ix| self.entries.get(entry_ix))
3905 .map_or(0, |entry| entry.depth())
3906 })
3907 .collect()
3908 }
3909
3910 fn status_width_estimate(
3911 tree_view: bool,
3912 entry: &GitStatusEntry,
3913 path_style: PathStyle,
3914 depth: usize,
3915 ) -> usize {
3916 if tree_view {
3917 Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3918 } else {
3919 Self::item_width_estimate(
3920 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3921 entry.display_name(path_style).len(),
3922 0,
3923 )
3924 }
3925 }
3926
3927 fn width_estimate_for_list_entry(
3928 &self,
3929 tree_view: bool,
3930 entry: &GitListEntry,
3931 path_style: PathStyle,
3932 ) -> Option<usize> {
3933 match entry {
3934 GitListEntry::Status(status) => Some(Self::status_width_estimate(
3935 tree_view, status, path_style, 0,
3936 )),
3937 GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3938 tree_view,
3939 &status.entry,
3940 path_style,
3941 status.depth,
3942 )),
3943 GitListEntry::Directory(dir) => {
3944 Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3945 }
3946 GitListEntry::Header(_) => None,
3947 }
3948 }
3949
3950 fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3951 path + file_name + depth * 2
3952 }
3953
3954 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3955 let focus_handle = self.focus_handle.clone();
3956 let has_tracked_changes = self.has_tracked_changes();
3957 let has_staged_changes = self.has_staged_changes();
3958 let has_unstaged_changes = self.has_unstaged_changes();
3959 let has_new_changes = self.new_count > 0;
3960 let has_stash_items = self.stash_entries.entries.len() > 0;
3961
3962 PopoverMenu::new(id.into())
3963 .trigger(
3964 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3965 .icon_size(IconSize::Small)
3966 .icon_color(Color::Muted),
3967 )
3968 .menu(move |window, cx| {
3969 Some(git_panel_context_menu(
3970 focus_handle.clone(),
3971 GitMenuState {
3972 has_tracked_changes,
3973 has_staged_changes,
3974 has_unstaged_changes,
3975 has_new_changes,
3976 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3977 has_stash_items,
3978 tree_view: GitPanelSettings::get_global(cx).tree_view,
3979 },
3980 window,
3981 cx,
3982 ))
3983 })
3984 .anchor(Corner::TopRight)
3985 }
3986
3987 pub(crate) fn render_generate_commit_message_button(
3988 &self,
3989 cx: &Context<Self>,
3990 ) -> Option<AnyElement> {
3991 if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
3992 return None;
3993 }
3994
3995 if self.generate_commit_message_task.is_some() {
3996 return Some(
3997 h_flex()
3998 .gap_1()
3999 .child(
4000 Icon::new(IconName::ArrowCircle)
4001 .size(IconSize::XSmall)
4002 .color(Color::Info)
4003 .with_rotate_animation(2),
4004 )
4005 .child(
4006 Label::new("Generating Commit…")
4007 .size(LabelSize::Small)
4008 .color(Color::Muted),
4009 )
4010 .into_any_element(),
4011 );
4012 }
4013
4014 let model_registry = LanguageModelRegistry::read_global(cx);
4015 let has_commit_model_configuration_error = model_registry
4016 .configuration_error(model_registry.commit_message_model(), cx)
4017 .is_some();
4018 let can_commit = self.can_commit();
4019
4020 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4021
4022 Some(
4023 IconButton::new("generate-commit-message", IconName::AiEdit)
4024 .shape(ui::IconButtonShape::Square)
4025 .icon_color(if has_commit_model_configuration_error {
4026 Color::Disabled
4027 } else {
4028 Color::Muted
4029 })
4030 .tooltip(move |_window, cx| {
4031 if !can_commit {
4032 Tooltip::simple("No Changes to Commit", cx)
4033 } else if has_commit_model_configuration_error {
4034 Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
4035 } else {
4036 Tooltip::for_action_in(
4037 "Generate Commit Message",
4038 &git::GenerateCommitMessage,
4039 &editor_focus_handle,
4040 cx,
4041 )
4042 }
4043 })
4044 .disabled(!can_commit || has_commit_model_configuration_error)
4045 .on_click(cx.listener(move |this, _event, _window, cx| {
4046 this.generate_commit_message(cx);
4047 }))
4048 .into_any_element(),
4049 )
4050 }
4051
4052 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
4053 let potential_co_authors = self.potential_co_authors(cx);
4054
4055 let (tooltip_label, icon) = if self.add_coauthors {
4056 ("Remove co-authored-by", IconName::Person)
4057 } else {
4058 ("Add co-authored-by", IconName::UserCheck)
4059 };
4060
4061 if potential_co_authors.is_empty() {
4062 None
4063 } else {
4064 Some(
4065 IconButton::new("co-authors", icon)
4066 .shape(ui::IconButtonShape::Square)
4067 .icon_color(Color::Disabled)
4068 .selected_icon_color(Color::Selected)
4069 .toggle_state(self.add_coauthors)
4070 .tooltip(move |_, cx| {
4071 let title = format!(
4072 "{}:{}{}",
4073 tooltip_label,
4074 if potential_co_authors.len() == 1 {
4075 ""
4076 } else {
4077 "\n"
4078 },
4079 potential_co_authors
4080 .iter()
4081 .map(|(name, email)| format!(" {} <{}>", name, email))
4082 .join("\n")
4083 );
4084 Tooltip::simple(title, cx)
4085 })
4086 .on_click(cx.listener(|this, _, _, cx| {
4087 this.add_coauthors = !this.add_coauthors;
4088 cx.notify();
4089 }))
4090 .into_any_element(),
4091 )
4092 }
4093 }
4094
4095 fn render_git_commit_menu(
4096 &self,
4097 id: impl Into<ElementId>,
4098 keybinding_target: Option<FocusHandle>,
4099 cx: &mut Context<Self>,
4100 ) -> impl IntoElement {
4101 PopoverMenu::new(id.into())
4102 .trigger(
4103 ui::ButtonLike::new_rounded_right("commit-split-button-right")
4104 .layer(ui::ElevationIndex::ModalSurface)
4105 .size(ButtonSize::None)
4106 .child(
4107 h_flex()
4108 .px_1()
4109 .h_full()
4110 .justify_center()
4111 .border_l_1()
4112 .border_color(cx.theme().colors().border)
4113 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4114 ),
4115 )
4116 .menu({
4117 let git_panel = cx.entity();
4118 let has_previous_commit = self.head_commit(cx).is_some();
4119 let amend = self.amend_pending();
4120 let signoff = self.signoff_enabled;
4121
4122 move |window, cx| {
4123 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4124 context_menu
4125 .when_some(keybinding_target.clone(), |el, keybinding_target| {
4126 el.context(keybinding_target)
4127 })
4128 .when(has_previous_commit, |this| {
4129 this.toggleable_entry(
4130 "Amend",
4131 amend,
4132 IconPosition::Start,
4133 Some(Box::new(Amend)),
4134 {
4135 let git_panel = git_panel.downgrade();
4136 move |_, cx| {
4137 git_panel
4138 .update(cx, |git_panel, cx| {
4139 git_panel.toggle_amend_pending(cx);
4140 })
4141 .ok();
4142 }
4143 },
4144 )
4145 })
4146 .toggleable_entry(
4147 "Signoff",
4148 signoff,
4149 IconPosition::Start,
4150 Some(Box::new(Signoff)),
4151 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4152 )
4153 }))
4154 }
4155 })
4156 .anchor(Corner::TopRight)
4157 }
4158
4159 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4160 if self.has_unstaged_conflicts() {
4161 (false, "You must resolve conflicts before committing")
4162 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4163 (false, "No changes to commit")
4164 } else if self.pending_commit.is_some() {
4165 (false, "Commit in progress")
4166 } else if !self.has_commit_message(cx) {
4167 (false, "No commit message")
4168 } else if !self.has_write_access(cx) {
4169 (false, "You do not have write access to this project")
4170 } else {
4171 (true, self.commit_button_title())
4172 }
4173 }
4174
4175 pub fn commit_button_title(&self) -> &'static str {
4176 if self.amend_pending {
4177 if self.has_staged_changes() {
4178 "Amend"
4179 } else if self.has_tracked_changes() {
4180 "Amend Tracked"
4181 } else {
4182 "Amend"
4183 }
4184 } else if self.has_staged_changes() {
4185 "Commit"
4186 } else {
4187 "Commit Tracked"
4188 }
4189 }
4190
4191 fn expand_commit_editor(
4192 &mut self,
4193 _: &git::ExpandCommitEditor,
4194 window: &mut Window,
4195 cx: &mut Context<Self>,
4196 ) {
4197 let workspace = self.workspace.clone();
4198 window.defer(cx, move |window, cx| {
4199 workspace
4200 .update(cx, |workspace, cx| {
4201 CommitModal::toggle(workspace, None, window, cx)
4202 })
4203 .ok();
4204 })
4205 }
4206
4207 fn render_panel_header(
4208 &self,
4209 window: &mut Window,
4210 cx: &mut Context<Self>,
4211 ) -> Option<impl IntoElement> {
4212 self.active_repository.as_ref()?;
4213
4214 let (text, action, stage, tooltip) =
4215 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4216 ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4217 } else {
4218 ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4219 };
4220
4221 let change_string = match self.changes_count {
4222 0 => "No Changes".to_string(),
4223 1 => "1 Change".to_string(),
4224 count => format!("{} Changes", count),
4225 };
4226
4227 Some(
4228 self.panel_header_container(window, cx)
4229 .px_2()
4230 .justify_between()
4231 .child(
4232 panel_button(change_string)
4233 .color(Color::Muted)
4234 .tooltip(Tooltip::for_action_title_in(
4235 "Open Diff",
4236 &Diff,
4237 &self.focus_handle,
4238 ))
4239 .on_click(|_, _, cx| {
4240 cx.defer(|cx| {
4241 cx.dispatch_action(&Diff);
4242 })
4243 }),
4244 )
4245 .child(
4246 h_flex()
4247 .gap_1()
4248 .child(self.render_overflow_menu("overflow_menu"))
4249 .child(
4250 panel_filled_button(text)
4251 .tooltip(Tooltip::for_action_title_in(
4252 tooltip,
4253 action.as_ref(),
4254 &self.focus_handle,
4255 ))
4256 .disabled(self.entry_count == 0)
4257 .on_click({
4258 let git_panel = cx.weak_entity();
4259 move |_, _, cx| {
4260 git_panel
4261 .update(cx, |git_panel, cx| {
4262 git_panel.change_all_files_stage(stage, cx);
4263 })
4264 .ok();
4265 }
4266 }),
4267 ),
4268 ),
4269 )
4270 }
4271
4272 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4273 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4274 if !self.can_push_and_pull(cx) {
4275 return None;
4276 }
4277 Some(
4278 h_flex()
4279 .gap_1()
4280 .flex_shrink_0()
4281 .when_some(branch, |this, branch| {
4282 let focus_handle = Some(self.focus_handle(cx));
4283
4284 this.children(render_remote_button(
4285 "remote-button",
4286 &branch,
4287 focus_handle,
4288 true,
4289 ))
4290 })
4291 .into_any_element(),
4292 )
4293 }
4294
4295 pub fn render_footer(
4296 &self,
4297 window: &mut Window,
4298 cx: &mut Context<Self>,
4299 ) -> Option<impl IntoElement> {
4300 let active_repository = self.active_repository.clone()?;
4301 let panel_editor_style = panel_editor_style(true, window, cx);
4302 let enable_coauthors = self.render_co_authors(cx);
4303
4304 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4305 let expand_tooltip_focus_handle = editor_focus_handle;
4306
4307 let branch = active_repository.read(cx).branch.clone();
4308 let head_commit = active_repository.read(cx).head_commit.clone();
4309
4310 let footer_size = px(32.);
4311 let gap = px(9.0);
4312 let max_height = panel_editor_style
4313 .text
4314 .line_height_in_pixels(window.rem_size())
4315 * MAX_PANEL_EDITOR_LINES
4316 + gap;
4317
4318 let git_panel = cx.entity();
4319 let display_name = SharedString::from(Arc::from(
4320 active_repository
4321 .read(cx)
4322 .display_name()
4323 .trim_end_matches("/"),
4324 ));
4325 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4326 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4327 });
4328
4329 let footer = v_flex()
4330 .child(PanelRepoFooter::new(
4331 display_name,
4332 branch,
4333 head_commit,
4334 Some(git_panel),
4335 ))
4336 .child(
4337 panel_editor_container(window, cx)
4338 .id("commit-editor-container")
4339 .relative()
4340 .w_full()
4341 .h(max_height + footer_size)
4342 .border_t_1()
4343 .border_color(cx.theme().colors().border)
4344 .cursor_text()
4345 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4346 window.focus(&this.commit_editor.focus_handle(cx), cx);
4347 }))
4348 .child(
4349 h_flex()
4350 .id("commit-footer")
4351 .border_t_1()
4352 .when(editor_is_long, |el| {
4353 el.border_color(cx.theme().colors().border_variant)
4354 })
4355 .absolute()
4356 .bottom_0()
4357 .left_0()
4358 .w_full()
4359 .px_2()
4360 .h(footer_size)
4361 .flex_none()
4362 .justify_between()
4363 .child(
4364 self.render_generate_commit_message_button(cx)
4365 .unwrap_or_else(|| div().into_any_element()),
4366 )
4367 .child(
4368 h_flex()
4369 .gap_0p5()
4370 .children(enable_coauthors)
4371 .child(self.render_commit_button(cx)),
4372 ),
4373 )
4374 .child(
4375 div()
4376 .pr_2p5()
4377 .on_action(|&zed_actions::editor::MoveUp, _, cx| {
4378 cx.stop_propagation();
4379 })
4380 .on_action(|&zed_actions::editor::MoveDown, _, cx| {
4381 cx.stop_propagation();
4382 })
4383 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4384 )
4385 .child(
4386 h_flex()
4387 .absolute()
4388 .top_2()
4389 .right_2()
4390 .opacity(0.5)
4391 .hover(|this| this.opacity(1.0))
4392 .child(
4393 panel_icon_button("expand-commit-editor", IconName::Maximize)
4394 .icon_size(IconSize::Small)
4395 .size(ui::ButtonSize::Default)
4396 .tooltip(move |_window, cx| {
4397 Tooltip::for_action_in(
4398 "Open Commit Modal",
4399 &git::ExpandCommitEditor,
4400 &expand_tooltip_focus_handle,
4401 cx,
4402 )
4403 })
4404 .on_click(cx.listener({
4405 move |_, _, window, cx| {
4406 window.dispatch_action(
4407 git::ExpandCommitEditor.boxed_clone(),
4408 cx,
4409 )
4410 }
4411 })),
4412 ),
4413 ),
4414 );
4415
4416 Some(footer)
4417 }
4418
4419 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4420 let (can_commit, tooltip) = self.configure_commit_button(cx);
4421 let title = self.commit_button_title();
4422 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4423 let amend = self.amend_pending();
4424 let signoff = self.signoff_enabled;
4425
4426 let label_color = if self.pending_commit.is_some() {
4427 Color::Disabled
4428 } else {
4429 Color::Default
4430 };
4431
4432 div()
4433 .id("commit-wrapper")
4434 .on_hover(cx.listener(move |this, hovered, _, cx| {
4435 this.show_placeholders =
4436 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4437 cx.notify()
4438 }))
4439 .child(SplitButton::new(
4440 ButtonLike::new_rounded_left(ElementId::Name(
4441 format!("split-button-left-{}", title).into(),
4442 ))
4443 .layer(ElevationIndex::ModalSurface)
4444 .size(ButtonSize::Compact)
4445 .child(
4446 Label::new(title)
4447 .size(LabelSize::Small)
4448 .color(label_color)
4449 .mr_0p5(),
4450 )
4451 .on_click({
4452 let git_panel = cx.weak_entity();
4453 move |_, window, cx| {
4454 telemetry::event!("Git Committed", source = "Git Panel");
4455 git_panel
4456 .update(cx, |git_panel, cx| {
4457 git_panel.commit_changes(
4458 CommitOptions { amend, signoff },
4459 window,
4460 cx,
4461 );
4462 })
4463 .ok();
4464 }
4465 })
4466 .disabled(!can_commit || self.modal_open)
4467 .tooltip({
4468 let handle = commit_tooltip_focus_handle.clone();
4469 move |_window, cx| {
4470 if can_commit {
4471 Tooltip::with_meta_in(
4472 tooltip,
4473 Some(if amend { &git::Amend } else { &git::Commit }),
4474 format!(
4475 "git commit{}{}",
4476 if amend { " --amend" } else { "" },
4477 if signoff { " --signoff" } else { "" }
4478 ),
4479 &handle.clone(),
4480 cx,
4481 )
4482 } else {
4483 Tooltip::simple(tooltip, cx)
4484 }
4485 }
4486 }),
4487 self.render_git_commit_menu(
4488 ElementId::Name(format!("split-button-right-{}", title).into()),
4489 Some(commit_tooltip_focus_handle),
4490 cx,
4491 )
4492 .into_any_element(),
4493 ))
4494 }
4495
4496 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4497 h_flex()
4498 .py_1p5()
4499 .px_2()
4500 .gap_1p5()
4501 .justify_between()
4502 .border_t_1()
4503 .border_color(cx.theme().colors().border.opacity(0.8))
4504 .child(
4505 div()
4506 .flex_grow()
4507 .overflow_hidden()
4508 .max_w(relative(0.85))
4509 .child(
4510 Label::new("This will update your most recent commit.")
4511 .size(LabelSize::Small)
4512 .truncate(),
4513 ),
4514 )
4515 .child(
4516 panel_button("Cancel")
4517 .size(ButtonSize::Default)
4518 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4519 )
4520 }
4521
4522 fn render_previous_commit(
4523 &self,
4524 _window: &mut Window,
4525 cx: &mut Context<Self>,
4526 ) -> Option<impl IntoElement> {
4527 let active_repository = self.active_repository.as_ref()?;
4528 let branch = active_repository.read(cx).branch.as_ref()?;
4529 let commit = branch.most_recent_commit.as_ref()?.clone();
4530 let workspace = self.workspace.clone();
4531 let this = cx.entity();
4532 let can_open_git_graph = cx.has_flag::<GitGraphFeatureFlag>();
4533
4534 Some(
4535 h_flex()
4536 .p_1p5()
4537 .gap_1p5()
4538 .justify_between()
4539 .border_t_1()
4540 .border_color(cx.theme().colors().border.opacity(0.8))
4541 .child(
4542 div()
4543 .id("commit-msg-hover")
4544 .cursor_pointer()
4545 .px_1()
4546 .rounded_sm()
4547 .line_clamp(1)
4548 .hover(|s| s.bg(cx.theme().colors().element_hover))
4549 .child(
4550 Label::new(commit.subject.clone())
4551 .size(LabelSize::Small)
4552 .truncate(),
4553 )
4554 .on_click({
4555 let commit = commit.clone();
4556 let repo = active_repository.downgrade();
4557 move |_, window, cx| {
4558 CommitView::open(
4559 commit.sha.to_string(),
4560 repo.clone(),
4561 workspace.clone(),
4562 None,
4563 None,
4564 window,
4565 cx,
4566 );
4567 }
4568 })
4569 .hoverable_tooltip({
4570 let repo = active_repository.clone();
4571 move |window, cx| {
4572 GitPanelMessageTooltip::new(
4573 this.clone(),
4574 commit.sha.clone(),
4575 repo.clone(),
4576 window,
4577 cx,
4578 )
4579 .into()
4580 }
4581 }),
4582 )
4583 .child(
4584 h_flex()
4585 .gap_0p5()
4586 .when(commit.has_parent, |this| {
4587 let has_unstaged = self.has_unstaged_changes();
4588 this.child(
4589 panel_icon_button("undo", IconName::Undo)
4590 .icon_size(IconSize::Small)
4591 .tooltip(move |_window, cx| {
4592 Tooltip::with_meta(
4593 "Uncommit",
4594 Some(&git::Uncommit),
4595 if has_unstaged {
4596 "git reset HEAD^ --soft"
4597 } else {
4598 "git reset HEAD^"
4599 },
4600 cx,
4601 )
4602 })
4603 .on_click(
4604 cx.listener(|this, _, window, cx| {
4605 this.uncommit(window, cx)
4606 }),
4607 ),
4608 )
4609 })
4610 .when(can_open_git_graph, |this| {
4611 this.child(
4612 panel_icon_button("git-graph-button", IconName::GitGraph)
4613 .icon_size(IconSize::Small)
4614 .tooltip(|_window, cx| {
4615 Tooltip::for_action("Open Git Graph", &Open, cx)
4616 })
4617 .on_click(|_, window, cx| {
4618 window.dispatch_action(Open.boxed_clone(), cx)
4619 }),
4620 )
4621 }),
4622 ),
4623 )
4624 }
4625
4626 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4627 let has_repo = self.active_repository.is_some();
4628 let has_no_repo = self.active_repository.is_none();
4629 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4630
4631 let should_show_branch_diff =
4632 has_repo && self.changes_count == 0 && !self.is_on_main_branch(cx);
4633
4634 let label = if has_repo {
4635 "No changes to commit"
4636 } else {
4637 "No Git repositories"
4638 };
4639
4640 v_flex()
4641 .gap_1p5()
4642 .flex_1()
4643 .items_center()
4644 .justify_center()
4645 .child(Label::new(label).size(LabelSize::Small).color(Color::Muted))
4646 .when(has_no_repo && worktree_count > 0, |this| {
4647 this.child(
4648 panel_filled_button("Initialize Repository")
4649 .tooltip(Tooltip::for_action_title_in(
4650 "git init",
4651 &git::Init,
4652 &self.focus_handle,
4653 ))
4654 .on_click(move |_, _, cx| {
4655 cx.defer(move |cx| {
4656 cx.dispatch_action(&git::Init);
4657 })
4658 }),
4659 )
4660 })
4661 .when(should_show_branch_diff, |this| {
4662 this.child(
4663 panel_filled_button("View Branch Diff")
4664 .tooltip(move |_, cx| {
4665 Tooltip::with_meta(
4666 "Branch Diff",
4667 Some(&BranchDiff),
4668 "Show diff between working directory and default branch",
4669 cx,
4670 )
4671 })
4672 .on_click(move |_, _, cx| {
4673 cx.defer(move |cx| {
4674 cx.dispatch_action(&BranchDiff);
4675 })
4676 }),
4677 )
4678 })
4679 }
4680
4681 fn is_on_main_branch(&self, cx: &Context<Self>) -> bool {
4682 let Some(repo) = self.active_repository.as_ref() else {
4683 return false;
4684 };
4685
4686 let Some(branch) = repo.read(cx).branch.as_ref() else {
4687 return false;
4688 };
4689
4690 let branch_name = branch.name();
4691 matches!(branch_name, "main" | "master")
4692 }
4693
4694 fn render_buffer_header_controls(
4695 &self,
4696 entity: &Entity<Self>,
4697 file: &Arc<dyn File>,
4698 _: &Window,
4699 cx: &App,
4700 ) -> Option<AnyElement> {
4701 let repo = self.active_repository.as_ref()?.read(cx);
4702 let project_path = (file.worktree_id(cx), file.path().clone()).into();
4703 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4704 let ix = self.entry_by_path(&repo_path)?;
4705 let entry = self.entries.get(ix)?;
4706
4707 let is_staging_or_staged = repo
4708 .pending_ops_for_path(&repo_path)
4709 .map(|ops| ops.staging() || ops.staged())
4710 .or_else(|| {
4711 repo.status_for_path(&repo_path)
4712 .and_then(|status| status.status.staging().as_bool())
4713 })
4714 .or_else(|| {
4715 entry
4716 .status_entry()
4717 .and_then(|entry| entry.staging.as_bool())
4718 });
4719
4720 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4721 .disabled(!self.has_write_access(cx))
4722 .fill()
4723 .elevation(ElevationIndex::Surface)
4724 .on_click({
4725 let entry = entry.clone();
4726 let git_panel = entity.downgrade();
4727 move |_, window, cx| {
4728 git_panel
4729 .update(cx, |this, cx| {
4730 this.toggle_staged_for_entry(&entry, window, cx);
4731 cx.stop_propagation();
4732 })
4733 .ok();
4734 }
4735 });
4736 Some(
4737 h_flex()
4738 .id("start-slot")
4739 .text_lg()
4740 .child(checkbox)
4741 .on_mouse_down(MouseButton::Left, |_, _, cx| {
4742 // prevent the list item active state triggering when toggling checkbox
4743 cx.stop_propagation();
4744 })
4745 .into_any_element(),
4746 )
4747 }
4748
4749 fn render_entries(
4750 &self,
4751 has_write_access: bool,
4752 repo: Entity<Repository>,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) -> impl IntoElement {
4756 let (is_tree_view, entry_count) = match &self.view_mode {
4757 GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4758 GitPanelViewMode::Flat => (false, self.entries.len()),
4759 };
4760 let repo = repo.downgrade();
4761
4762 v_flex()
4763 .flex_1()
4764 .size_full()
4765 .overflow_hidden()
4766 .relative()
4767 .child(
4768 h_flex()
4769 .flex_1()
4770 .size_full()
4771 .relative()
4772 .overflow_hidden()
4773 .child(
4774 uniform_list(
4775 "entries",
4776 entry_count,
4777 cx.processor(move |this, range: Range<usize>, window, cx| {
4778 let Some(repo) = repo.upgrade() else {
4779 return Vec::new();
4780 };
4781 let repo = repo.read(cx);
4782
4783 let mut items = Vec::with_capacity(range.end - range.start);
4784
4785 for ix in range.into_iter().map(|ix| match &this.view_mode {
4786 GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4787 GitPanelViewMode::Flat => ix,
4788 }) {
4789 match &this.entries.get(ix) {
4790 Some(GitListEntry::Status(entry)) => {
4791 items.push(this.render_status_entry(
4792 ix,
4793 entry,
4794 0,
4795 has_write_access,
4796 repo,
4797 window,
4798 cx,
4799 ));
4800 }
4801 Some(GitListEntry::TreeStatus(entry)) => {
4802 items.push(this.render_status_entry(
4803 ix,
4804 &entry.entry,
4805 entry.depth,
4806 has_write_access,
4807 repo,
4808 window,
4809 cx,
4810 ));
4811 }
4812 Some(GitListEntry::Directory(entry)) => {
4813 items.push(this.render_directory_entry(
4814 ix,
4815 entry,
4816 has_write_access,
4817 window,
4818 cx,
4819 ));
4820 }
4821 Some(GitListEntry::Header(header)) => {
4822 items.push(this.render_list_header(
4823 ix,
4824 header,
4825 has_write_access,
4826 window,
4827 cx,
4828 ));
4829 }
4830 None => {}
4831 }
4832 }
4833
4834 items
4835 }),
4836 )
4837 .when(is_tree_view, |list| {
4838 let indent_size = px(TREE_INDENT);
4839 list.with_decoration(
4840 ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4841 .with_compute_indents_fn(
4842 cx.entity(),
4843 |this, range, _window, _cx| {
4844 this.compute_visible_depths(range)
4845 },
4846 )
4847 .with_render_fn(cx.entity(), |_, params, _, _| {
4848 // Magic number to align the tree item is 3 here
4849 // because we're using 12px as the left-side padding
4850 // and 3 makes the alignment work with the bounding box of the icon
4851 let left_offset = px(TREE_INDENT + 3_f32);
4852 let indent_size = params.indent_size;
4853 let item_height = params.item_height;
4854
4855 params
4856 .indent_guides
4857 .into_iter()
4858 .map(|layout| {
4859 let bounds = Bounds::new(
4860 point(
4861 layout.offset.x * indent_size + left_offset,
4862 layout.offset.y * item_height,
4863 ),
4864 size(px(1.), layout.length * item_height),
4865 );
4866 RenderedIndentGuide {
4867 bounds,
4868 layout,
4869 is_active: false,
4870 hitbox: None,
4871 }
4872 })
4873 .collect()
4874 }),
4875 )
4876 })
4877 .size_full()
4878 .flex_grow()
4879 .with_width_from_item(self.max_width_item_index)
4880 .track_scroll(&self.scroll_handle),
4881 )
4882 .on_mouse_down(
4883 MouseButton::Right,
4884 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4885 this.deploy_panel_context_menu(event.position, window, cx)
4886 }),
4887 )
4888 .custom_scrollbars(
4889 Scrollbars::for_settings::<GitPanelScrollbarAccessor>()
4890 .tracked_scroll_handle(&self.scroll_handle)
4891 .with_track_along(
4892 ScrollAxes::Horizontal,
4893 cx.theme().colors().panel_background,
4894 ),
4895 window,
4896 cx,
4897 ),
4898 )
4899 }
4900
4901 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4902 Label::new(label.into()).color(color)
4903 }
4904
4905 fn list_item_height(&self) -> Rems {
4906 rems(1.75)
4907 }
4908
4909 fn render_list_header(
4910 &self,
4911 ix: usize,
4912 header: &GitHeaderEntry,
4913 _: bool,
4914 _: &Window,
4915 _: &Context<Self>,
4916 ) -> AnyElement {
4917 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4918
4919 h_flex()
4920 .id(id)
4921 .h(self.list_item_height())
4922 .w_full()
4923 .items_end()
4924 .px_3()
4925 .pb_1()
4926 .child(
4927 Label::new(header.title())
4928 .color(Color::Muted)
4929 .size(LabelSize::Small)
4930 .line_height_style(LineHeightStyle::UiLabel)
4931 .single_line(),
4932 )
4933 .into_any_element()
4934 }
4935
4936 pub fn load_commit_details(
4937 &self,
4938 sha: String,
4939 cx: &mut Context<Self>,
4940 ) -> Task<anyhow::Result<CommitDetails>> {
4941 let Some(repo) = self.active_repository.clone() else {
4942 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4943 };
4944 repo.update(cx, |repo, cx| {
4945 let show = repo.show(sha);
4946 cx.spawn(async move |_, _| show.await?)
4947 })
4948 }
4949
4950 fn deploy_entry_context_menu(
4951 &mut self,
4952 position: Point<Pixels>,
4953 ix: usize,
4954 window: &mut Window,
4955 cx: &mut Context<Self>,
4956 ) {
4957 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4958 return;
4959 };
4960 let stage_title = if entry.status.staging().is_fully_staged() {
4961 "Unstage File"
4962 } else {
4963 "Stage File"
4964 };
4965 let restore_title = if entry.status.is_created() {
4966 "Trash File"
4967 } else {
4968 "Discard Changes"
4969 };
4970 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4971 let is_created = entry.status.is_created();
4972 context_menu
4973 .context(self.focus_handle.clone())
4974 .action(stage_title, ToggleStaged.boxed_clone())
4975 .action(restore_title, git::RestoreFile::default().boxed_clone())
4976 .action_disabled_when(
4977 !is_created,
4978 "Add to .gitignore",
4979 git::AddToGitignore.boxed_clone(),
4980 )
4981 .separator()
4982 .action("Open Diff", menu::Confirm.boxed_clone())
4983 .action("Open File", menu::SecondaryConfirm.boxed_clone())
4984 .separator()
4985 .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4986 });
4987 self.selected_entry = Some(ix);
4988 self.set_context_menu(context_menu, position, window, cx);
4989 }
4990
4991 fn deploy_panel_context_menu(
4992 &mut self,
4993 position: Point<Pixels>,
4994 window: &mut Window,
4995 cx: &mut Context<Self>,
4996 ) {
4997 let context_menu = git_panel_context_menu(
4998 self.focus_handle.clone(),
4999 GitMenuState {
5000 has_tracked_changes: self.has_tracked_changes(),
5001 has_staged_changes: self.has_staged_changes(),
5002 has_unstaged_changes: self.has_unstaged_changes(),
5003 has_new_changes: self.new_count > 0,
5004 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
5005 has_stash_items: self.stash_entries.entries.len() > 0,
5006 tree_view: GitPanelSettings::get_global(cx).tree_view,
5007 },
5008 window,
5009 cx,
5010 );
5011 self.set_context_menu(context_menu, position, window, cx);
5012 }
5013
5014 fn set_context_menu(
5015 &mut self,
5016 context_menu: Entity<ContextMenu>,
5017 position: Point<Pixels>,
5018 window: &Window,
5019 cx: &mut Context<Self>,
5020 ) {
5021 let subscription = cx.subscribe_in(
5022 &context_menu,
5023 window,
5024 |this, _, _: &DismissEvent, window, cx| {
5025 if this.context_menu.as_ref().is_some_and(|context_menu| {
5026 context_menu.0.focus_handle(cx).contains_focused(window, cx)
5027 }) {
5028 cx.focus_self(window);
5029 }
5030 this.context_menu.take();
5031 cx.notify();
5032 },
5033 );
5034 self.context_menu = Some((context_menu, position, subscription));
5035 cx.notify();
5036 }
5037
5038 fn render_status_entry(
5039 &self,
5040 ix: usize,
5041 entry: &GitStatusEntry,
5042 depth: usize,
5043 has_write_access: bool,
5044 repo: &Repository,
5045 window: &Window,
5046 cx: &Context<Self>,
5047 ) -> AnyElement {
5048 let settings = GitPanelSettings::get_global(cx);
5049 let tree_view = settings.tree_view;
5050 let path_style = self.project.read(cx).path_style(cx);
5051 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
5052 let display_name = entry.display_name(path_style);
5053
5054 let selected = self.selected_entry == Some(ix);
5055 let marked = self.marked_entries.contains(&ix);
5056 let status_style = settings.status_style;
5057 let status = entry.status;
5058 let file_icon = if settings.file_icons {
5059 FileIcons::get_icon(entry.repo_path.as_std_path(), cx)
5060 } else {
5061 None
5062 };
5063
5064 let has_conflict = status.is_conflicted();
5065 let is_modified = status.is_modified();
5066 let is_deleted = status.is_deleted();
5067 let is_created = status.is_created();
5068
5069 let label_color = if status_style == StatusStyle::LabelColor {
5070 if has_conflict {
5071 Color::VersionControlConflict
5072 } else if is_created {
5073 Color::VersionControlAdded
5074 } else if is_modified {
5075 Color::VersionControlModified
5076 } else if is_deleted {
5077 // We don't want a bunch of red labels in the list
5078 Color::Disabled
5079 } else {
5080 Color::VersionControlAdded
5081 }
5082 } else {
5083 Color::Default
5084 };
5085
5086 let path_color = if status.is_deleted() {
5087 Color::Disabled
5088 } else {
5089 Color::Muted
5090 };
5091
5092 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
5093 let checkbox_wrapper_id: ElementId =
5094 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
5095 let checkbox_id: ElementId =
5096 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5097
5098 let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5099 let mut is_staged: ToggleState = match stage_status {
5100 StageStatus::Staged => ToggleState::Selected,
5101 StageStatus::Unstaged => ToggleState::Unselected,
5102 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5103 };
5104 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5105 is_staged = ToggleState::Selected;
5106 }
5107
5108 let handle = cx.weak_entity();
5109
5110 let selected_bg_alpha = 0.08;
5111 let marked_bg_alpha = 0.12;
5112 let state_opacity_step = 0.04;
5113
5114 let info_color = cx.theme().status().info;
5115
5116 let base_bg = match (selected, marked) {
5117 (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5118 (true, false) => info_color.alpha(selected_bg_alpha),
5119 (false, true) => info_color.alpha(marked_bg_alpha),
5120 _ => cx.theme().colors().ghost_element_background,
5121 };
5122
5123 let (hover_bg, active_bg) = if selected {
5124 (
5125 info_color.alpha(selected_bg_alpha + state_opacity_step),
5126 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5127 )
5128 } else {
5129 (
5130 cx.theme().colors().ghost_element_hover,
5131 cx.theme().colors().ghost_element_active,
5132 )
5133 };
5134
5135 let name_row = h_flex()
5136 .min_w_0()
5137 .flex_1()
5138 .gap_1()
5139 .when(settings.file_icons, |this| {
5140 this.child(
5141 file_icon
5142 .map(|file_icon| {
5143 Icon::from_path(file_icon)
5144 .size(IconSize::Small)
5145 .color(Color::Muted)
5146 })
5147 .unwrap_or_else(|| {
5148 Icon::new(IconName::File)
5149 .size(IconSize::Small)
5150 .color(Color::Muted)
5151 }),
5152 )
5153 })
5154 .when(status_style != StatusStyle::LabelColor, |el| {
5155 el.child(git_status_icon(status))
5156 })
5157 .map(|this| {
5158 if tree_view {
5159 this.pl(px(depth as f32 * TREE_INDENT)).child(
5160 self.entry_label(display_name, label_color)
5161 .when(status.is_deleted(), Label::strikethrough)
5162 .truncate(),
5163 )
5164 } else {
5165 this.child(self.path_formatted(
5166 entry.parent_dir(path_style),
5167 path_color,
5168 display_name,
5169 label_color,
5170 path_style,
5171 git_path_style,
5172 status.is_deleted(),
5173 ))
5174 }
5175 });
5176
5177 let id_for_diff_stat = id.clone();
5178
5179 h_flex()
5180 .id(id)
5181 .h(self.list_item_height())
5182 .w_full()
5183 .pl_3()
5184 .pr_1()
5185 .gap_1p5()
5186 .border_1()
5187 .border_r_2()
5188 .when(selected && self.focus_handle.is_focused(window), |el| {
5189 el.border_color(cx.theme().colors().panel_focused_border)
5190 })
5191 .bg(base_bg)
5192 .hover(|s| s.bg(hover_bg))
5193 .active(|s| s.bg(active_bg))
5194 .child(name_row)
5195 .when(GitPanelSettings::get_global(cx).diff_stats, |el| {
5196 el.when_some(entry.diff_stat, move |this, stat| {
5197 let id = format!("diff-stat-{}", id_for_diff_stat);
5198 this.child(ui::DiffStat::new(
5199 id,
5200 stat.added as usize,
5201 stat.deleted as usize,
5202 ))
5203 })
5204 })
5205 .child(
5206 div()
5207 .id(checkbox_wrapper_id)
5208 .flex_none()
5209 .occlude()
5210 .cursor_pointer()
5211 .child(
5212 Checkbox::new(checkbox_id, is_staged)
5213 .disabled(!has_write_access)
5214 .fill()
5215 .elevation(ElevationIndex::Surface)
5216 .on_click_ext({
5217 let entry = entry.clone();
5218 let this = cx.weak_entity();
5219 move |_, click, window, cx| {
5220 this.update(cx, |this, cx| {
5221 if !has_write_access {
5222 return;
5223 }
5224 if click.modifiers().shift {
5225 this.stage_bulk(ix, cx);
5226 } else {
5227 let list_entry =
5228 if GitPanelSettings::get_global(cx).tree_view {
5229 GitListEntry::TreeStatus(GitTreeStatusEntry {
5230 entry: entry.clone(),
5231 depth,
5232 })
5233 } else {
5234 GitListEntry::Status(entry.clone())
5235 };
5236 this.toggle_staged_for_entry(&list_entry, window, cx);
5237 }
5238 cx.stop_propagation();
5239 })
5240 .ok();
5241 }
5242 })
5243 .tooltip(move |_window, cx| {
5244 let action = match stage_status {
5245 StageStatus::Staged => "Unstage",
5246 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5247 };
5248 let tooltip_name = action.to_string();
5249
5250 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5251 }),
5252 ),
5253 )
5254 .on_click({
5255 cx.listener(move |this, event: &ClickEvent, window, cx| {
5256 this.selected_entry = Some(ix);
5257 cx.notify();
5258 if event.click_count() > 1 || event.modifiers().secondary() {
5259 this.open_file(&Default::default(), window, cx)
5260 } else {
5261 this.open_diff(&Default::default(), window, cx);
5262 this.focus_handle.focus(window, cx);
5263 }
5264 })
5265 })
5266 .on_mouse_down(
5267 MouseButton::Right,
5268 move |event: &MouseDownEvent, window, cx| {
5269 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5270 if event.button != MouseButton::Right {
5271 return;
5272 }
5273
5274 let Some(this) = handle.upgrade() else {
5275 return;
5276 };
5277 this.update(cx, |this, cx| {
5278 this.deploy_entry_context_menu(event.position, ix, window, cx);
5279 });
5280 cx.stop_propagation();
5281 },
5282 )
5283 .into_any_element()
5284 }
5285
5286 fn render_directory_entry(
5287 &self,
5288 ix: usize,
5289 entry: &GitTreeDirEntry,
5290 has_write_access: bool,
5291 window: &Window,
5292 cx: &Context<Self>,
5293 ) -> AnyElement {
5294 // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5295 let selected = self.selected_entry == Some(ix);
5296 let label_color = Color::Muted;
5297
5298 let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5299 let checkbox_id: ElementId =
5300 ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5301 let checkbox_wrapper_id: ElementId =
5302 ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5303
5304 let selected_bg_alpha = 0.08;
5305 let state_opacity_step = 0.04;
5306
5307 let info_color = cx.theme().status().info;
5308 let colors = cx.theme().colors();
5309
5310 let (base_bg, hover_bg, active_bg) = if selected {
5311 (
5312 info_color.alpha(selected_bg_alpha),
5313 info_color.alpha(selected_bg_alpha + state_opacity_step),
5314 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5315 )
5316 } else {
5317 (
5318 colors.ghost_element_background,
5319 colors.ghost_element_hover,
5320 colors.ghost_element_active,
5321 )
5322 };
5323
5324 let settings = GitPanelSettings::get_global(cx);
5325 let folder_icon = if settings.folder_icons {
5326 FileIcons::get_folder_icon(entry.expanded, entry.key.path.as_std_path(), cx)
5327 } else {
5328 FileIcons::get_chevron_icon(entry.expanded, cx)
5329 };
5330 let fallback_folder_icon = if settings.folder_icons {
5331 if entry.expanded {
5332 IconName::FolderOpen
5333 } else {
5334 IconName::Folder
5335 }
5336 } else {
5337 if entry.expanded {
5338 IconName::ChevronDown
5339 } else {
5340 IconName::ChevronRight
5341 }
5342 };
5343
5344 let stage_status = if let Some(repo) = &self.active_repository {
5345 self.stage_status_for_directory(entry, repo.read(cx))
5346 } else {
5347 util::debug_panic!(
5348 "Won't have entries to render without an active repository in Git Panel"
5349 );
5350 StageStatus::PartiallyStaged
5351 };
5352
5353 let toggle_state: ToggleState = match stage_status {
5354 StageStatus::Staged => ToggleState::Selected,
5355 StageStatus::Unstaged => ToggleState::Unselected,
5356 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5357 };
5358
5359 let name_row = h_flex()
5360 .min_w_0()
5361 .gap_1()
5362 .pl(px(entry.depth as f32 * TREE_INDENT))
5363 .child(
5364 folder_icon
5365 .map(|folder_icon| {
5366 Icon::from_path(folder_icon)
5367 .size(IconSize::Small)
5368 .color(Color::Muted)
5369 })
5370 .unwrap_or_else(|| {
5371 Icon::new(fallback_folder_icon)
5372 .size(IconSize::Small)
5373 .color(Color::Muted)
5374 }),
5375 )
5376 .child(self.entry_label(entry.name.clone(), label_color).truncate());
5377
5378 h_flex()
5379 .id(id)
5380 .h(self.list_item_height())
5381 .min_w_0()
5382 .w_full()
5383 .pl_3()
5384 .pr_1()
5385 .gap_1p5()
5386 .justify_between()
5387 .border_1()
5388 .border_r_2()
5389 .when(selected && self.focus_handle.is_focused(window), |el| {
5390 el.border_color(cx.theme().colors().panel_focused_border)
5391 })
5392 .bg(base_bg)
5393 .hover(|s| s.bg(hover_bg))
5394 .active(|s| s.bg(active_bg))
5395 .child(name_row)
5396 .child(
5397 div()
5398 .id(checkbox_wrapper_id)
5399 .flex_none()
5400 .occlude()
5401 .cursor_pointer()
5402 .child(
5403 Checkbox::new(checkbox_id, toggle_state)
5404 .disabled(!has_write_access)
5405 .fill()
5406 .elevation(ElevationIndex::Surface)
5407 .on_click({
5408 let entry = entry.clone();
5409 let this = cx.weak_entity();
5410 move |_, window, cx| {
5411 this.update(cx, |this, cx| {
5412 if !has_write_access {
5413 return;
5414 }
5415 this.toggle_staged_for_entry(
5416 &GitListEntry::Directory(entry.clone()),
5417 window,
5418 cx,
5419 );
5420 cx.stop_propagation();
5421 })
5422 .ok();
5423 }
5424 })
5425 .tooltip(move |_window, cx| {
5426 let action = match stage_status {
5427 StageStatus::Staged => "Unstage",
5428 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5429 };
5430 Tooltip::simple(format!("{action} folder"), cx)
5431 }),
5432 ),
5433 )
5434 .on_click({
5435 let key = entry.key.clone();
5436 cx.listener(move |this, _event: &ClickEvent, window, cx| {
5437 this.selected_entry = Some(ix);
5438 this.toggle_directory(&key, window, cx);
5439 })
5440 })
5441 .into_any_element()
5442 }
5443
5444 fn path_formatted(
5445 &self,
5446 directory: Option<String>,
5447 path_color: Color,
5448 file_name: String,
5449 label_color: Color,
5450 path_style: PathStyle,
5451 git_path_style: GitPathStyle,
5452 strikethrough: bool,
5453 ) -> Div {
5454 let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5455 let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5456
5457 let file_name = format!("{} ", file_name);
5458
5459 h_flex()
5460 .min_w_0()
5461 .overflow_hidden()
5462 .when(file_path_first, |this| this.flex_row_reverse())
5463 .child(
5464 div().flex_none().child(
5465 self.entry_label(file_name, label_color)
5466 .when(strikethrough, Label::strikethrough),
5467 ),
5468 )
5469 .when_some(directory, |this, dir| {
5470 let path_name = if file_name_first {
5471 dir
5472 } else {
5473 format!("{dir}{}", path_style.primary_separator())
5474 };
5475
5476 this.child(
5477 self.entry_label(path_name, path_color)
5478 .truncate_start()
5479 .when(strikethrough, Label::strikethrough),
5480 )
5481 })
5482 }
5483
5484 fn has_write_access(&self, cx: &App) -> bool {
5485 !self.project.read(cx).is_read_only(cx)
5486 }
5487
5488 pub fn amend_pending(&self) -> bool {
5489 self.amend_pending
5490 }
5491
5492 /// Sets the pending amend state, ensuring that the original commit message
5493 /// is either saved, when `value` is `true` and there's no pending amend, or
5494 /// restored, when `value` is `false` and there's a pending amend.
5495 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5496 if value && !self.amend_pending {
5497 let current_message = self.commit_message_buffer(cx).read(cx).text();
5498 self.original_commit_message = if current_message.trim().is_empty() {
5499 None
5500 } else {
5501 Some(current_message)
5502 };
5503 } else if !value && self.amend_pending {
5504 let message = self.original_commit_message.take().unwrap_or_default();
5505 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5506 let start = buffer.anchor_before(0);
5507 let end = buffer.anchor_after(buffer.len());
5508 buffer.edit([(start..end, message)], None, cx);
5509 });
5510 }
5511
5512 self.amend_pending = value;
5513 self.serialize(cx);
5514 cx.notify();
5515 }
5516
5517 pub fn signoff_enabled(&self) -> bool {
5518 self.signoff_enabled
5519 }
5520
5521 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5522 self.signoff_enabled = value;
5523 self.serialize(cx);
5524 cx.notify();
5525 }
5526
5527 pub fn toggle_signoff_enabled(
5528 &mut self,
5529 _: &Signoff,
5530 _window: &mut Window,
5531 cx: &mut Context<Self>,
5532 ) {
5533 self.set_signoff_enabled(!self.signoff_enabled, cx);
5534 }
5535
5536 pub async fn load(
5537 workspace: WeakEntity<Workspace>,
5538 mut cx: AsyncWindowContext,
5539 ) -> anyhow::Result<Entity<Self>> {
5540 let serialized_panel = match workspace
5541 .read_with(&cx, |workspace, cx| {
5542 Self::serialization_key(workspace).map(|key| (key, KeyValueStore::global(cx)))
5543 })
5544 .ok()
5545 .flatten()
5546 {
5547 Some((serialization_key, kvp)) => cx
5548 .background_spawn(async move { kvp.read_kvp(&serialization_key) })
5549 .await
5550 .context("loading git panel")
5551 .log_err()
5552 .flatten()
5553 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5554 .transpose()
5555 .log_err()
5556 .flatten(),
5557 None => None,
5558 };
5559
5560 workspace.update_in(&mut cx, |workspace, window, cx| {
5561 let panel = GitPanel::new(workspace, window, cx);
5562
5563 if let Some(serialized_panel) = serialized_panel {
5564 panel.update(cx, |panel, cx| {
5565 panel.amend_pending = serialized_panel.amend_pending;
5566 panel.signoff_enabled = serialized_panel.signoff_enabled;
5567 cx.notify();
5568 })
5569 }
5570
5571 panel
5572 })
5573 }
5574
5575 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5576 let Some(op) = self.bulk_staging.as_ref() else {
5577 return;
5578 };
5579 let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5580 return;
5581 };
5582 if let Some(entry) = self.entries.get(index)
5583 && let Some(entry) = entry.status_entry()
5584 {
5585 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5586 }
5587 if index < anchor_index {
5588 std::mem::swap(&mut index, &mut anchor_index);
5589 }
5590 let entries = self
5591 .entries
5592 .get(anchor_index..=index)
5593 .unwrap_or_default()
5594 .iter()
5595 .filter_map(|entry| entry.status_entry().cloned())
5596 .collect::<Vec<_>>();
5597 self.change_file_stage(true, entries, cx);
5598 }
5599
5600 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5601 let Some(repo) = self.active_repository.as_ref() else {
5602 return;
5603 };
5604 self.bulk_staging = Some(BulkStaging {
5605 repo_id: repo.read(cx).id,
5606 anchor: path,
5607 });
5608 }
5609
5610 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5611 self.set_amend_pending(!self.amend_pending, cx);
5612 if self.amend_pending {
5613 self.load_last_commit_message(cx);
5614 }
5615 }
5616}
5617
5618#[cfg(any(test, feature = "test-support"))]
5619impl GitPanel {
5620 pub fn new_test(
5621 workspace: &mut Workspace,
5622 window: &mut Window,
5623 cx: &mut Context<Workspace>,
5624 ) -> Entity<Self> {
5625 Self::new(workspace, window, cx)
5626 }
5627
5628 pub fn active_repository(&self) -> Option<&Entity<Repository>> {
5629 self.active_repository.as_ref()
5630 }
5631}
5632
5633impl Render for GitPanel {
5634 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5635 let project = self.project.read(cx);
5636 let has_entries = !self.entries.is_empty();
5637 let room = self.workspace.upgrade().and_then(|_workspace| {
5638 call::ActiveCall::try_global(cx).and_then(|call| call.read(cx).room().cloned())
5639 });
5640
5641 let has_write_access = self.has_write_access(cx);
5642
5643 let has_co_authors = room.is_some_and(|room| {
5644 self.load_local_committer(cx);
5645 let room = room.read(cx);
5646 room.remote_participants()
5647 .values()
5648 .any(|remote_participant| remote_participant.can_write())
5649 });
5650
5651 v_flex()
5652 .id("git_panel")
5653 .key_context(self.dispatch_context(window, cx))
5654 .track_focus(&self.focus_handle)
5655 .when(has_write_access && !project.is_read_only(cx), |this| {
5656 this.on_action(cx.listener(Self::toggle_staged_for_selected))
5657 .on_action(cx.listener(Self::stage_range))
5658 .on_action(cx.listener(GitPanel::on_commit))
5659 .on_action(cx.listener(GitPanel::on_amend))
5660 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5661 .on_action(cx.listener(Self::stage_all))
5662 .on_action(cx.listener(Self::unstage_all))
5663 .on_action(cx.listener(Self::stage_selected))
5664 .on_action(cx.listener(Self::unstage_selected))
5665 .on_action(cx.listener(Self::restore_tracked_files))
5666 .on_action(cx.listener(Self::revert_selected))
5667 .on_action(cx.listener(Self::add_to_gitignore))
5668 .on_action(cx.listener(Self::clean_all))
5669 .on_action(cx.listener(Self::generate_commit_message_action))
5670 .on_action(cx.listener(Self::stash_all))
5671 .on_action(cx.listener(Self::stash_pop))
5672 })
5673 .on_action(cx.listener(Self::collapse_selected_entry))
5674 .on_action(cx.listener(Self::expand_selected_entry))
5675 .on_action(cx.listener(Self::select_first))
5676 .on_action(cx.listener(Self::select_next))
5677 .on_action(cx.listener(Self::select_previous))
5678 .on_action(cx.listener(Self::select_last))
5679 .on_action(cx.listener(Self::first_entry))
5680 .on_action(cx.listener(Self::next_entry))
5681 .on_action(cx.listener(Self::previous_entry))
5682 .on_action(cx.listener(Self::last_entry))
5683 .on_action(cx.listener(Self::close_panel))
5684 .on_action(cx.listener(Self::open_diff))
5685 .on_action(cx.listener(Self::open_file))
5686 .on_action(cx.listener(Self::file_history))
5687 .on_action(cx.listener(Self::focus_changes_list))
5688 .on_action(cx.listener(Self::focus_editor))
5689 .on_action(cx.listener(Self::expand_commit_editor))
5690 .when(has_write_access && has_co_authors, |git_panel| {
5691 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5692 })
5693 .on_action(cx.listener(Self::toggle_sort_by_path))
5694 .on_action(cx.listener(Self::toggle_tree_view))
5695 .size_full()
5696 .overflow_hidden()
5697 .bg(cx.theme().colors().panel_background)
5698 .child(
5699 v_flex()
5700 .size_full()
5701 .children(self.render_panel_header(window, cx))
5702 .map(|this| {
5703 if let Some(repo) = self.active_repository.clone()
5704 && has_entries
5705 {
5706 this.child(self.render_entries(has_write_access, repo, window, cx))
5707 } else {
5708 this.child(self.render_empty_state(cx).into_any_element())
5709 }
5710 })
5711 .children(self.render_footer(window, cx))
5712 .when(self.amend_pending, |this| {
5713 this.child(self.render_pending_amend(cx))
5714 })
5715 .when(!self.amend_pending, |this| {
5716 this.children(self.render_previous_commit(window, cx))
5717 })
5718 .into_any_element(),
5719 )
5720 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5721 deferred(
5722 anchored()
5723 .position(*position)
5724 .anchor(Corner::TopLeft)
5725 .child(menu.clone()),
5726 )
5727 .with_priority(1)
5728 }))
5729 }
5730}
5731
5732impl Focusable for GitPanel {
5733 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5734 if self.entries.is_empty() {
5735 self.commit_editor.focus_handle(cx)
5736 } else {
5737 self.focus_handle.clone()
5738 }
5739 }
5740}
5741
5742impl EventEmitter<Event> for GitPanel {}
5743
5744impl EventEmitter<PanelEvent> for GitPanel {}
5745
5746pub(crate) struct GitPanelAddon {
5747 pub(crate) workspace: WeakEntity<Workspace>,
5748}
5749
5750impl editor::Addon for GitPanelAddon {
5751 fn to_any(&self) -> &dyn std::any::Any {
5752 self
5753 }
5754
5755 fn render_buffer_header_controls(
5756 &self,
5757 excerpt_info: &ExcerptInfo,
5758 window: &Window,
5759 cx: &App,
5760 ) -> Option<AnyElement> {
5761 let file = excerpt_info.buffer.file()?;
5762 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5763
5764 git_panel
5765 .read(cx)
5766 .render_buffer_header_controls(&git_panel, file, window, cx)
5767 }
5768}
5769
5770impl Panel for GitPanel {
5771 fn persistent_name() -> &'static str {
5772 "GitPanel"
5773 }
5774
5775 fn panel_key() -> &'static str {
5776 GIT_PANEL_KEY
5777 }
5778
5779 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5780 GitPanelSettings::get_global(cx).dock
5781 }
5782
5783 fn position_is_valid(&self, position: DockPosition) -> bool {
5784 matches!(position, DockPosition::Left | DockPosition::Right)
5785 }
5786
5787 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5788 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5789 settings.git_panel.get_or_insert_default().dock = Some(position.into())
5790 });
5791 }
5792
5793 fn default_size(&self, _: &Window, cx: &App) -> Pixels {
5794 GitPanelSettings::get_global(cx).default_width
5795 }
5796
5797 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5798 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5799 }
5800
5801 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5802 Some("Git Panel")
5803 }
5804
5805 fn icon_label(&self, _: &Window, cx: &App) -> Option<String> {
5806 if !GitPanelSettings::get_global(cx).show_count_badge {
5807 return None;
5808 }
5809 let total = self.changes_count;
5810 (total > 0).then(|| total.to_string())
5811 }
5812
5813 fn toggle_action(&self) -> Box<dyn Action> {
5814 Box::new(ToggleFocus)
5815 }
5816
5817 fn starts_open(&self, _: &Window, cx: &App) -> bool {
5818 GitPanelSettings::get_global(cx).starts_open
5819 }
5820
5821 fn activation_priority(&self) -> u32 {
5822 3
5823 }
5824}
5825
5826impl PanelHeader for GitPanel {}
5827
5828pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5829 v_flex()
5830 .size_full()
5831 .gap(px(8.))
5832 .p_2()
5833 .bg(cx.theme().colors().editor_background)
5834}
5835
5836pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5837 let settings = ThemeSettings::get_global(cx);
5838
5839 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5840
5841 let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5842 (
5843 settings.buffer_font.family.clone(),
5844 settings.buffer_font.fallbacks.clone(),
5845 settings.buffer_font.features.clone(),
5846 settings.buffer_font.weight,
5847 font_size * settings.buffer_line_height.value(),
5848 )
5849 } else {
5850 (
5851 settings.ui_font.family.clone(),
5852 settings.ui_font.fallbacks.clone(),
5853 settings.ui_font.features.clone(),
5854 settings.ui_font.weight,
5855 window.line_height(),
5856 )
5857 };
5858
5859 EditorStyle {
5860 background: cx.theme().colors().editor_background,
5861 local_player: cx.theme().players().local(),
5862 text: TextStyle {
5863 color: cx.theme().colors().text,
5864 font_family,
5865 font_fallbacks,
5866 font_features,
5867 font_size: TextSize::Small.rems(cx).into(),
5868 font_weight,
5869 line_height: line_height.into(),
5870 ..Default::default()
5871 },
5872 syntax: cx.theme().syntax().clone(),
5873 ..Default::default()
5874 }
5875}
5876
5877struct GitPanelMessageTooltip {
5878 commit_tooltip: Option<Entity<CommitTooltip>>,
5879}
5880
5881impl GitPanelMessageTooltip {
5882 fn new(
5883 git_panel: Entity<GitPanel>,
5884 sha: SharedString,
5885 repository: Entity<Repository>,
5886 window: &mut Window,
5887 cx: &mut App,
5888 ) -> Entity<Self> {
5889 let remote_url = repository.read(cx).default_remote_url();
5890 cx.new(|cx| {
5891 cx.spawn_in(window, async move |this, cx| {
5892 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5893 (
5894 git_panel.load_commit_details(sha.to_string(), cx),
5895 git_panel.workspace.clone(),
5896 )
5897 });
5898 let details = details.await?;
5899 let provider_registry = cx
5900 .update(|_, app| GitHostingProviderRegistry::default_global(app))
5901 .ok();
5902
5903 let commit_details = crate::commit_tooltip::CommitDetails {
5904 sha: details.sha.clone(),
5905 author_name: details.author_name.clone(),
5906 author_email: details.author_email.clone(),
5907 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5908 message: Some(ParsedCommitMessage::parse(
5909 details.sha.to_string(),
5910 details.message.to_string(),
5911 remote_url.as_deref(),
5912 provider_registry,
5913 )),
5914 };
5915
5916 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5917 this.commit_tooltip = Some(cx.new(move |cx| {
5918 CommitTooltip::new(commit_details, repository, workspace, cx)
5919 }));
5920 cx.notify();
5921 })
5922 })
5923 .detach();
5924
5925 Self {
5926 commit_tooltip: None,
5927 }
5928 })
5929 }
5930}
5931
5932impl Render for GitPanelMessageTooltip {
5933 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5934 if let Some(commit_tooltip) = &self.commit_tooltip {
5935 commit_tooltip.clone().into_any_element()
5936 } else {
5937 gpui::Empty.into_any_element()
5938 }
5939 }
5940}
5941
5942#[derive(IntoElement, RegisterComponent)]
5943pub struct PanelRepoFooter {
5944 active_repository: SharedString,
5945 branch: Option<Branch>,
5946 head_commit: Option<CommitDetails>,
5947
5948 // Getting a GitPanel in previews will be difficult.
5949 //
5950 // For now just take an option here, and we won't bind handlers to buttons in previews.
5951 git_panel: Option<Entity<GitPanel>>,
5952}
5953
5954impl PanelRepoFooter {
5955 pub fn new(
5956 active_repository: SharedString,
5957 branch: Option<Branch>,
5958 head_commit: Option<CommitDetails>,
5959 git_panel: Option<Entity<GitPanel>>,
5960 ) -> Self {
5961 Self {
5962 active_repository,
5963 branch,
5964 head_commit,
5965 git_panel,
5966 }
5967 }
5968
5969 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5970 Self {
5971 active_repository,
5972 branch,
5973 head_commit: None,
5974 git_panel: None,
5975 }
5976 }
5977}
5978
5979impl RenderOnce for PanelRepoFooter {
5980 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5981 let project = self
5982 .git_panel
5983 .as_ref()
5984 .map(|panel| panel.read(cx).project.clone());
5985
5986 let (workspace, repo) = self
5987 .git_panel
5988 .as_ref()
5989 .map(|panel| {
5990 let panel = panel.read(cx);
5991 (panel.workspace.clone(), panel.active_repository.clone())
5992 })
5993 .unzip();
5994
5995 let single_repo = project
5996 .as_ref()
5997 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5998 .unwrap_or(true);
5999
6000 const MAX_BRANCH_LEN: usize = 16;
6001 const MAX_REPO_LEN: usize = 16;
6002 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
6003 const MAX_SHORT_SHA_LEN: usize = 8;
6004 let branch_name = self
6005 .branch
6006 .as_ref()
6007 .map(|branch| branch.name().to_owned())
6008 .or_else(|| {
6009 self.head_commit.as_ref().map(|commit| {
6010 commit
6011 .sha
6012 .chars()
6013 .take(MAX_SHORT_SHA_LEN)
6014 .collect::<String>()
6015 })
6016 })
6017 .unwrap_or_else(|| " (no branch)".to_owned());
6018 let show_separator = self.branch.is_some() || self.head_commit.is_some();
6019
6020 let active_repo_name = self.active_repository.clone();
6021
6022 let branch_actual_len = branch_name.len();
6023 let repo_actual_len = active_repo_name.len();
6024
6025 // ideally, show the whole branch and repo names but
6026 // when we can't, use a budget to allocate space between the two
6027 let (repo_display_len, branch_display_len) =
6028 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
6029 (repo_actual_len, branch_actual_len)
6030 } else if branch_actual_len <= MAX_BRANCH_LEN {
6031 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
6032 (repo_space, branch_actual_len)
6033 } else if repo_actual_len <= MAX_REPO_LEN {
6034 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
6035 (repo_actual_len, branch_space)
6036 } else {
6037 (MAX_REPO_LEN, MAX_BRANCH_LEN)
6038 };
6039
6040 let truncated_repo_name = if repo_actual_len <= repo_display_len {
6041 active_repo_name.to_string()
6042 } else {
6043 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
6044 };
6045
6046 let truncated_branch_name = if branch_actual_len <= branch_display_len {
6047 branch_name
6048 } else {
6049 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
6050 };
6051
6052 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
6053 .size(ButtonSize::None)
6054 .label_size(LabelSize::Small);
6055
6056 let repo_selector = PopoverMenu::new("repository-switcher")
6057 .menu({
6058 let project = project;
6059 move |window, cx| {
6060 let project = project.clone()?;
6061 Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
6062 }
6063 })
6064 .trigger_with_tooltip(
6065 repo_selector_trigger
6066 .when(single_repo, |this| this.disabled(true).color(Color::Muted))
6067 .truncate(true),
6068 move |_, cx| {
6069 if single_repo {
6070 cx.new(|_| Empty).into()
6071 } else {
6072 Tooltip::simple("Switch Active Repository", cx)
6073 }
6074 },
6075 )
6076 .anchor(Corner::BottomLeft)
6077 .offset(gpui::Point {
6078 x: px(0.0),
6079 y: px(-2.0),
6080 })
6081 .into_any_element();
6082
6083 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
6084 .size(ButtonSize::None)
6085 .label_size(LabelSize::Small)
6086 .truncate(true)
6087 .on_click(|_, window, cx| {
6088 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
6089 });
6090
6091 let branch_selector = PopoverMenu::new("popover-button")
6092 .menu(move |window, cx| {
6093 let workspace = workspace.clone()?;
6094 let repo = repo.clone().flatten();
6095 Some(branch_picker::popover(workspace, false, repo, window, cx))
6096 })
6097 .trigger_with_tooltip(
6098 branch_selector_button,
6099 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
6100 )
6101 .anchor(Corner::BottomLeft)
6102 .offset(gpui::Point {
6103 x: px(0.0),
6104 y: px(-2.0),
6105 });
6106
6107 h_flex()
6108 .h(px(36.))
6109 .w_full()
6110 .px_2()
6111 .justify_between()
6112 .gap_1()
6113 .child(
6114 h_flex()
6115 .flex_1()
6116 .overflow_hidden()
6117 .gap_px()
6118 .child(
6119 Icon::new(IconName::GitBranchAlt)
6120 .size(IconSize::Small)
6121 .color(if single_repo {
6122 Color::Disabled
6123 } else {
6124 Color::Muted
6125 }),
6126 )
6127 .child(repo_selector)
6128 .when(show_separator, |this| {
6129 this.child(
6130 div()
6131 .text_sm()
6132 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
6133 .child("/"),
6134 )
6135 })
6136 .child(branch_selector),
6137 )
6138 .children(if let Some(git_panel) = self.git_panel {
6139 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
6140 } else {
6141 None
6142 })
6143 }
6144}
6145
6146impl Component for PanelRepoFooter {
6147 fn scope() -> ComponentScope {
6148 ComponentScope::VersionControl
6149 }
6150
6151 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
6152 let unknown_upstream = None;
6153 let no_remote_upstream = Some(UpstreamTracking::Gone);
6154 let ahead_of_upstream = Some(
6155 UpstreamTrackingStatus {
6156 ahead: 2,
6157 behind: 0,
6158 }
6159 .into(),
6160 );
6161 let behind_upstream = Some(
6162 UpstreamTrackingStatus {
6163 ahead: 0,
6164 behind: 2,
6165 }
6166 .into(),
6167 );
6168 let ahead_and_behind_upstream = Some(
6169 UpstreamTrackingStatus {
6170 ahead: 3,
6171 behind: 1,
6172 }
6173 .into(),
6174 );
6175
6176 let not_ahead_or_behind_upstream = Some(
6177 UpstreamTrackingStatus {
6178 ahead: 0,
6179 behind: 0,
6180 }
6181 .into(),
6182 );
6183
6184 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6185 Branch {
6186 is_head: true,
6187 ref_name: "some-branch".into(),
6188 upstream: upstream.map(|tracking| Upstream {
6189 ref_name: "origin/some-branch".into(),
6190 tracking,
6191 }),
6192 most_recent_commit: Some(CommitSummary {
6193 sha: "abc123".into(),
6194 subject: "Modify stuff".into(),
6195 commit_timestamp: 1710932954,
6196 author_name: "John Doe".into(),
6197 has_parent: true,
6198 }),
6199 }
6200 }
6201
6202 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6203 Branch {
6204 is_head: true,
6205 ref_name: branch_name.to_string().into(),
6206 upstream: upstream.map(|tracking| Upstream {
6207 ref_name: format!("zed/{}", branch_name).into(),
6208 tracking,
6209 }),
6210 most_recent_commit: Some(CommitSummary {
6211 sha: "abc123".into(),
6212 subject: "Modify stuff".into(),
6213 commit_timestamp: 1710932954,
6214 author_name: "John Doe".into(),
6215 has_parent: true,
6216 }),
6217 }
6218 }
6219
6220 fn active_repository(id: usize) -> SharedString {
6221 format!("repo-{}", id).into()
6222 }
6223
6224 let example_width = px(340.);
6225 Some(
6226 v_flex()
6227 .gap_6()
6228 .w_full()
6229 .flex_none()
6230 .children(vec![
6231 example_group_with_title(
6232 "Action Button States",
6233 vec![
6234 single_example(
6235 "No Branch",
6236 div()
6237 .w(example_width)
6238 .overflow_hidden()
6239 .child(PanelRepoFooter::new_preview(active_repository(1), None))
6240 .into_any_element(),
6241 ),
6242 single_example(
6243 "Remote status unknown",
6244 div()
6245 .w(example_width)
6246 .overflow_hidden()
6247 .child(PanelRepoFooter::new_preview(
6248 active_repository(2),
6249 Some(branch(unknown_upstream)),
6250 ))
6251 .into_any_element(),
6252 ),
6253 single_example(
6254 "No Remote Upstream",
6255 div()
6256 .w(example_width)
6257 .overflow_hidden()
6258 .child(PanelRepoFooter::new_preview(
6259 active_repository(3),
6260 Some(branch(no_remote_upstream)),
6261 ))
6262 .into_any_element(),
6263 ),
6264 single_example(
6265 "Not Ahead or Behind",
6266 div()
6267 .w(example_width)
6268 .overflow_hidden()
6269 .child(PanelRepoFooter::new_preview(
6270 active_repository(4),
6271 Some(branch(not_ahead_or_behind_upstream)),
6272 ))
6273 .into_any_element(),
6274 ),
6275 single_example(
6276 "Behind remote",
6277 div()
6278 .w(example_width)
6279 .overflow_hidden()
6280 .child(PanelRepoFooter::new_preview(
6281 active_repository(5),
6282 Some(branch(behind_upstream)),
6283 ))
6284 .into_any_element(),
6285 ),
6286 single_example(
6287 "Ahead of remote",
6288 div()
6289 .w(example_width)
6290 .overflow_hidden()
6291 .child(PanelRepoFooter::new_preview(
6292 active_repository(6),
6293 Some(branch(ahead_of_upstream)),
6294 ))
6295 .into_any_element(),
6296 ),
6297 single_example(
6298 "Ahead and behind remote",
6299 div()
6300 .w(example_width)
6301 .overflow_hidden()
6302 .child(PanelRepoFooter::new_preview(
6303 active_repository(7),
6304 Some(branch(ahead_and_behind_upstream)),
6305 ))
6306 .into_any_element(),
6307 ),
6308 ],
6309 )
6310 .grow()
6311 .vertical(),
6312 ])
6313 .children(vec![
6314 example_group_with_title(
6315 "Labels",
6316 vec![
6317 single_example(
6318 "Short Branch & Repo",
6319 div()
6320 .w(example_width)
6321 .overflow_hidden()
6322 .child(PanelRepoFooter::new_preview(
6323 SharedString::from("zed"),
6324 Some(custom("main", behind_upstream)),
6325 ))
6326 .into_any_element(),
6327 ),
6328 single_example(
6329 "Long Branch",
6330 div()
6331 .w(example_width)
6332 .overflow_hidden()
6333 .child(PanelRepoFooter::new_preview(
6334 SharedString::from("zed"),
6335 Some(custom(
6336 "redesign-and-update-git-ui-list-entry-style",
6337 behind_upstream,
6338 )),
6339 ))
6340 .into_any_element(),
6341 ),
6342 single_example(
6343 "Long Repo",
6344 div()
6345 .w(example_width)
6346 .overflow_hidden()
6347 .child(PanelRepoFooter::new_preview(
6348 SharedString::from("zed-industries-community-examples"),
6349 Some(custom("gpui", ahead_of_upstream)),
6350 ))
6351 .into_any_element(),
6352 ),
6353 single_example(
6354 "Long Repo & Branch",
6355 div()
6356 .w(example_width)
6357 .overflow_hidden()
6358 .child(PanelRepoFooter::new_preview(
6359 SharedString::from("zed-industries-community-examples"),
6360 Some(custom(
6361 "redesign-and-update-git-ui-list-entry-style",
6362 behind_upstream,
6363 )),
6364 ))
6365 .into_any_element(),
6366 ),
6367 single_example(
6368 "Uppercase Repo",
6369 div()
6370 .w(example_width)
6371 .overflow_hidden()
6372 .child(PanelRepoFooter::new_preview(
6373 SharedString::from("LICENSES"),
6374 Some(custom("main", ahead_of_upstream)),
6375 ))
6376 .into_any_element(),
6377 ),
6378 single_example(
6379 "Uppercase Branch",
6380 div()
6381 .w(example_width)
6382 .overflow_hidden()
6383 .child(PanelRepoFooter::new_preview(
6384 SharedString::from("zed"),
6385 Some(custom("update-README", behind_upstream)),
6386 ))
6387 .into_any_element(),
6388 ),
6389 ],
6390 )
6391 .grow()
6392 .vertical(),
6393 ])
6394 .into_any_element(),
6395 )
6396 }
6397}
6398
6399fn open_output(
6400 operation: impl Into<SharedString>,
6401 workspace: &mut Workspace,
6402 output: &str,
6403 window: &mut Window,
6404 cx: &mut Context<Workspace>,
6405) {
6406 let operation = operation.into();
6407 let buffer = cx.new(|cx| Buffer::local(output, cx));
6408 buffer.update(cx, |buffer, cx| {
6409 buffer.set_capability(language::Capability::ReadOnly, cx);
6410 });
6411 let editor = cx.new(|cx| {
6412 let mut editor = Editor::for_buffer(buffer, None, window, cx);
6413 editor.buffer().update(cx, |buffer, cx| {
6414 buffer.set_title(format!("Output from git {operation}"), cx);
6415 });
6416 editor.set_read_only(true);
6417 editor
6418 });
6419
6420 workspace.add_item_to_center(Box::new(editor), window, cx);
6421}
6422
6423pub(crate) fn show_error_toast(
6424 workspace: Entity<Workspace>,
6425 action: impl Into<SharedString>,
6426 e: anyhow::Error,
6427 cx: &mut App,
6428) {
6429 let action = action.into();
6430 let message = format_git_error_toast_message(&e);
6431 if message
6432 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6433 .next()
6434 .is_some()
6435 { // Hide the cancelled by user message
6436 } else {
6437 workspace.update(cx, |workspace, cx| {
6438 let workspace_weak = cx.weak_entity();
6439 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6440 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6441 .action("View Log", move |window, cx| {
6442 let message = message.clone();
6443 let action = action.clone();
6444 workspace_weak
6445 .update(cx, move |workspace, cx| {
6446 open_output(action, workspace, &message, window, cx)
6447 })
6448 .ok();
6449 })
6450 });
6451 workspace.toggle_status_toast(toast, cx)
6452 });
6453 }
6454}
6455
6456fn rpc_error_raw_message_from_chain(error: &anyhow::Error) -> Option<&str> {
6457 error
6458 .chain()
6459 .find_map(|cause| cause.downcast_ref::<RpcError>().map(RpcError::raw_message))
6460}
6461
6462fn format_git_error_toast_message(error: &anyhow::Error) -> String {
6463 if let Some(message) = rpc_error_raw_message_from_chain(error) {
6464 message.trim().to_string()
6465 } else {
6466 error.to_string().trim().to_string()
6467 }
6468}
6469
6470#[cfg(test)]
6471mod tests {
6472 use git::{
6473 repository::repo_path,
6474 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6475 };
6476 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext, px};
6477 use indoc::indoc;
6478 use project::FakeFs;
6479 use serde_json::json;
6480 use settings::SettingsStore;
6481 use theme::LoadThemes;
6482 use util::path;
6483 use util::rel_path::rel_path;
6484
6485 use workspace::MultiWorkspace;
6486
6487 use super::*;
6488
6489 fn init_test(cx: &mut gpui::TestAppContext) {
6490 zlog::init_test();
6491
6492 cx.update(|cx| {
6493 let settings_store = SettingsStore::test(cx);
6494 cx.set_global(settings_store);
6495 theme_settings::init(LoadThemes::JustBase, cx);
6496 editor::init(cx);
6497 crate::init(cx);
6498 });
6499 }
6500
6501 #[test]
6502 fn test_format_git_error_toast_message_prefers_raw_rpc_message() {
6503 let rpc_error = RpcError::from_proto(
6504 &proto::Error {
6505 message:
6506 "Your local changes to the following files would be overwritten by merge\n"
6507 .to_string(),
6508 code: proto::ErrorCode::Internal as i32,
6509 tags: Default::default(),
6510 },
6511 "Pull",
6512 );
6513
6514 let message = format_git_error_toast_message(&rpc_error);
6515 assert_eq!(
6516 message,
6517 "Your local changes to the following files would be overwritten by merge"
6518 );
6519 }
6520
6521 #[test]
6522 fn test_format_git_error_toast_message_prefers_raw_rpc_message_when_wrapped() {
6523 let rpc_error = RpcError::from_proto(
6524 &proto::Error {
6525 message:
6526 "Your local changes to the following files would be overwritten by merge\n"
6527 .to_string(),
6528 code: proto::ErrorCode::Internal as i32,
6529 tags: Default::default(),
6530 },
6531 "Pull",
6532 );
6533 let wrapped = rpc_error.context("sending pull request");
6534
6535 let message = format_git_error_toast_message(&wrapped);
6536 assert_eq!(
6537 message,
6538 "Your local changes to the following files would be overwritten by merge"
6539 );
6540 }
6541
6542 #[gpui::test]
6543 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6544 init_test(cx);
6545 let fs = FakeFs::new(cx.background_executor.clone());
6546 fs.insert_tree(
6547 "/root",
6548 json!({
6549 "zed": {
6550 ".git": {},
6551 "crates": {
6552 "gpui": {
6553 "gpui.rs": "fn main() {}"
6554 },
6555 "util": {
6556 "util.rs": "fn do_it() {}"
6557 }
6558 }
6559 },
6560 }),
6561 )
6562 .await;
6563
6564 fs.set_status_for_repo(
6565 Path::new(path!("/root/zed/.git")),
6566 &[
6567 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6568 ("crates/util/util.rs", StatusCode::Modified.worktree()),
6569 ],
6570 );
6571
6572 let project =
6573 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6574 let window_handle =
6575 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6576 let workspace = window_handle
6577 .read_with(cx, |mw, _| mw.workspace().clone())
6578 .unwrap();
6579 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6580
6581 cx.read(|cx| {
6582 project
6583 .read(cx)
6584 .worktrees(cx)
6585 .next()
6586 .unwrap()
6587 .read(cx)
6588 .as_local()
6589 .unwrap()
6590 .scan_complete()
6591 })
6592 .await;
6593
6594 cx.executor().run_until_parked();
6595
6596 let panel = workspace.update_in(cx, GitPanel::new);
6597
6598 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6599 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6600 });
6601 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6602 handle.await;
6603
6604 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6605 pretty_assertions::assert_eq!(
6606 entries,
6607 [
6608 GitListEntry::Header(GitHeaderEntry {
6609 header: Section::Tracked
6610 }),
6611 GitListEntry::Status(GitStatusEntry {
6612 repo_path: repo_path("crates/gpui/gpui.rs"),
6613 status: StatusCode::Modified.worktree(),
6614 staging: StageStatus::Unstaged,
6615 diff_stat: Some(DiffStat {
6616 added: 1,
6617 deleted: 1,
6618 }),
6619 }),
6620 GitListEntry::Status(GitStatusEntry {
6621 repo_path: repo_path("crates/util/util.rs"),
6622 status: StatusCode::Modified.worktree(),
6623 staging: StageStatus::Unstaged,
6624 diff_stat: Some(DiffStat {
6625 added: 1,
6626 deleted: 1,
6627 }),
6628 },),
6629 ],
6630 );
6631
6632 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6633 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6634 });
6635 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6636 handle.await;
6637 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6638 pretty_assertions::assert_eq!(
6639 entries,
6640 [
6641 GitListEntry::Header(GitHeaderEntry {
6642 header: Section::Tracked
6643 }),
6644 GitListEntry::Status(GitStatusEntry {
6645 repo_path: repo_path("crates/gpui/gpui.rs"),
6646 status: StatusCode::Modified.worktree(),
6647 staging: StageStatus::Unstaged,
6648 diff_stat: Some(DiffStat {
6649 added: 1,
6650 deleted: 1,
6651 }),
6652 }),
6653 GitListEntry::Status(GitStatusEntry {
6654 repo_path: repo_path("crates/util/util.rs"),
6655 status: StatusCode::Modified.worktree(),
6656 staging: StageStatus::Unstaged,
6657 diff_stat: Some(DiffStat {
6658 added: 1,
6659 deleted: 1,
6660 }),
6661 },),
6662 ],
6663 );
6664 }
6665
6666 #[gpui::test]
6667 async fn test_bulk_staging(cx: &mut TestAppContext) {
6668 use GitListEntry::*;
6669
6670 init_test(cx);
6671 let fs = FakeFs::new(cx.background_executor.clone());
6672 fs.insert_tree(
6673 "/root",
6674 json!({
6675 "project": {
6676 ".git": {},
6677 "src": {
6678 "main.rs": "fn main() {}",
6679 "lib.rs": "pub fn hello() {}",
6680 "utils.rs": "pub fn util() {}"
6681 },
6682 "tests": {
6683 "test.rs": "fn test() {}"
6684 },
6685 "new_file.txt": "new content",
6686 "another_new.rs": "// new file",
6687 "conflict.txt": "conflicted content"
6688 }
6689 }),
6690 )
6691 .await;
6692
6693 fs.set_status_for_repo(
6694 Path::new(path!("/root/project/.git")),
6695 &[
6696 ("src/main.rs", StatusCode::Modified.worktree()),
6697 ("src/lib.rs", StatusCode::Modified.worktree()),
6698 ("tests/test.rs", StatusCode::Modified.worktree()),
6699 ("new_file.txt", FileStatus::Untracked),
6700 ("another_new.rs", FileStatus::Untracked),
6701 ("src/utils.rs", FileStatus::Untracked),
6702 (
6703 "conflict.txt",
6704 UnmergedStatus {
6705 first_head: UnmergedStatusCode::Updated,
6706 second_head: UnmergedStatusCode::Updated,
6707 }
6708 .into(),
6709 ),
6710 ],
6711 );
6712
6713 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6714 let window_handle =
6715 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6716 let workspace = window_handle
6717 .read_with(cx, |mw, _| mw.workspace().clone())
6718 .unwrap();
6719 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6720
6721 cx.read(|cx| {
6722 project
6723 .read(cx)
6724 .worktrees(cx)
6725 .next()
6726 .unwrap()
6727 .read(cx)
6728 .as_local()
6729 .unwrap()
6730 .scan_complete()
6731 })
6732 .await;
6733
6734 cx.executor().run_until_parked();
6735
6736 let panel = workspace.update_in(cx, GitPanel::new);
6737
6738 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6739 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6740 });
6741 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6742 handle.await;
6743
6744 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6745 #[rustfmt::skip]
6746 pretty_assertions::assert_matches!(
6747 entries.as_slice(),
6748 &[
6749 Header(GitHeaderEntry { header: Section::Conflict }),
6750 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6751 Header(GitHeaderEntry { header: Section::Tracked }),
6752 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6753 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6754 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6755 Header(GitHeaderEntry { header: Section::New }),
6756 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6757 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6758 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6759 ],
6760 );
6761
6762 let second_status_entry = entries[3].clone();
6763 panel.update_in(cx, |panel, window, cx| {
6764 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6765 });
6766
6767 panel.update_in(cx, |panel, window, cx| {
6768 panel.selected_entry = Some(7);
6769 panel.stage_range(&git::StageRange, window, cx);
6770 });
6771
6772 cx.read(|cx| {
6773 project
6774 .read(cx)
6775 .worktrees(cx)
6776 .next()
6777 .unwrap()
6778 .read(cx)
6779 .as_local()
6780 .unwrap()
6781 .scan_complete()
6782 })
6783 .await;
6784
6785 cx.executor().run_until_parked();
6786
6787 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6788 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6789 });
6790 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6791 handle.await;
6792
6793 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6794 #[rustfmt::skip]
6795 pretty_assertions::assert_matches!(
6796 entries.as_slice(),
6797 &[
6798 Header(GitHeaderEntry { header: Section::Conflict }),
6799 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6800 Header(GitHeaderEntry { header: Section::Tracked }),
6801 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6802 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6803 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6804 Header(GitHeaderEntry { header: Section::New }),
6805 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6806 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6807 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6808 ],
6809 );
6810
6811 let third_status_entry = entries[4].clone();
6812 panel.update_in(cx, |panel, window, cx| {
6813 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6814 });
6815
6816 panel.update_in(cx, |panel, window, cx| {
6817 panel.selected_entry = Some(9);
6818 panel.stage_range(&git::StageRange, window, cx);
6819 });
6820
6821 cx.read(|cx| {
6822 project
6823 .read(cx)
6824 .worktrees(cx)
6825 .next()
6826 .unwrap()
6827 .read(cx)
6828 .as_local()
6829 .unwrap()
6830 .scan_complete()
6831 })
6832 .await;
6833
6834 cx.executor().run_until_parked();
6835
6836 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6837 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6838 });
6839 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6840 handle.await;
6841
6842 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6843 #[rustfmt::skip]
6844 pretty_assertions::assert_matches!(
6845 entries.as_slice(),
6846 &[
6847 Header(GitHeaderEntry { header: Section::Conflict }),
6848 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6849 Header(GitHeaderEntry { header: Section::Tracked }),
6850 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6851 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6852 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6853 Header(GitHeaderEntry { header: Section::New }),
6854 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6855 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6856 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6857 ],
6858 );
6859 }
6860
6861 #[gpui::test]
6862 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6863 use GitListEntry::*;
6864
6865 init_test(cx);
6866 let fs = FakeFs::new(cx.background_executor.clone());
6867 fs.insert_tree(
6868 "/root",
6869 json!({
6870 "project": {
6871 ".git": {},
6872 "src": {
6873 "main.rs": "fn main() {}",
6874 "lib.rs": "pub fn hello() {}",
6875 "utils.rs": "pub fn util() {}"
6876 },
6877 "tests": {
6878 "test.rs": "fn test() {}"
6879 },
6880 "new_file.txt": "new content",
6881 "another_new.rs": "// new file",
6882 "conflict.txt": "conflicted content"
6883 }
6884 }),
6885 )
6886 .await;
6887
6888 fs.set_status_for_repo(
6889 Path::new(path!("/root/project/.git")),
6890 &[
6891 ("src/main.rs", StatusCode::Modified.worktree()),
6892 ("src/lib.rs", StatusCode::Modified.worktree()),
6893 ("tests/test.rs", StatusCode::Modified.worktree()),
6894 ("new_file.txt", FileStatus::Untracked),
6895 ("another_new.rs", FileStatus::Untracked),
6896 ("src/utils.rs", FileStatus::Untracked),
6897 (
6898 "conflict.txt",
6899 UnmergedStatus {
6900 first_head: UnmergedStatusCode::Updated,
6901 second_head: UnmergedStatusCode::Updated,
6902 }
6903 .into(),
6904 ),
6905 ],
6906 );
6907
6908 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6909 let window_handle =
6910 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6911 let workspace = window_handle
6912 .read_with(cx, |mw, _| mw.workspace().clone())
6913 .unwrap();
6914 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6915
6916 cx.read(|cx| {
6917 project
6918 .read(cx)
6919 .worktrees(cx)
6920 .next()
6921 .unwrap()
6922 .read(cx)
6923 .as_local()
6924 .unwrap()
6925 .scan_complete()
6926 })
6927 .await;
6928
6929 cx.executor().run_until_parked();
6930
6931 let panel = workspace.update_in(cx, GitPanel::new);
6932
6933 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6934 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6935 });
6936 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6937 handle.await;
6938
6939 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6940 #[rustfmt::skip]
6941 pretty_assertions::assert_matches!(
6942 entries.as_slice(),
6943 &[
6944 Header(GitHeaderEntry { header: Section::Conflict }),
6945 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6946 Header(GitHeaderEntry { header: Section::Tracked }),
6947 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6948 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6949 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6950 Header(GitHeaderEntry { header: Section::New }),
6951 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6952 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6953 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6954 ],
6955 );
6956
6957 assert_entry_paths(
6958 &entries,
6959 &[
6960 None,
6961 Some("conflict.txt"),
6962 None,
6963 Some("src/lib.rs"),
6964 Some("src/main.rs"),
6965 Some("tests/test.rs"),
6966 None,
6967 Some("another_new.rs"),
6968 Some("new_file.txt"),
6969 Some("src/utils.rs"),
6970 ],
6971 );
6972
6973 let second_status_entry = entries[3].clone();
6974 panel.update_in(cx, |panel, window, cx| {
6975 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6976 });
6977
6978 cx.update(|_window, cx| {
6979 SettingsStore::update_global(cx, |store, cx| {
6980 store.update_user_settings(cx, |settings| {
6981 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6982 })
6983 });
6984 });
6985
6986 panel.update_in(cx, |panel, window, cx| {
6987 panel.selected_entry = Some(7);
6988 panel.stage_range(&git::StageRange, window, cx);
6989 });
6990
6991 cx.read(|cx| {
6992 project
6993 .read(cx)
6994 .worktrees(cx)
6995 .next()
6996 .unwrap()
6997 .read(cx)
6998 .as_local()
6999 .unwrap()
7000 .scan_complete()
7001 })
7002 .await;
7003
7004 cx.executor().run_until_parked();
7005
7006 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7007 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7008 });
7009 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7010 handle.await;
7011
7012 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7013 #[rustfmt::skip]
7014 pretty_assertions::assert_matches!(
7015 entries.as_slice(),
7016 &[
7017 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7018 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7019 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7020 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7021 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7022 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7023 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7024 ],
7025 );
7026
7027 assert_entry_paths(
7028 &entries,
7029 &[
7030 Some("another_new.rs"),
7031 Some("conflict.txt"),
7032 Some("new_file.txt"),
7033 Some("src/lib.rs"),
7034 Some("src/main.rs"),
7035 Some("src/utils.rs"),
7036 Some("tests/test.rs"),
7037 ],
7038 );
7039
7040 let third_status_entry = entries[4].clone();
7041 panel.update_in(cx, |panel, window, cx| {
7042 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
7043 });
7044
7045 panel.update_in(cx, |panel, window, cx| {
7046 panel.selected_entry = Some(9);
7047 panel.stage_range(&git::StageRange, window, cx);
7048 });
7049
7050 cx.read(|cx| {
7051 project
7052 .read(cx)
7053 .worktrees(cx)
7054 .next()
7055 .unwrap()
7056 .read(cx)
7057 .as_local()
7058 .unwrap()
7059 .scan_complete()
7060 })
7061 .await;
7062
7063 cx.executor().run_until_parked();
7064
7065 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7066 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7067 });
7068 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7069 handle.await;
7070
7071 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7072 #[rustfmt::skip]
7073 pretty_assertions::assert_matches!(
7074 entries.as_slice(),
7075 &[
7076 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7077 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
7078 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7079 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7080 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
7081 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
7082 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
7083 ],
7084 );
7085
7086 assert_entry_paths(
7087 &entries,
7088 &[
7089 Some("another_new.rs"),
7090 Some("conflict.txt"),
7091 Some("new_file.txt"),
7092 Some("src/lib.rs"),
7093 Some("src/main.rs"),
7094 Some("src/utils.rs"),
7095 Some("tests/test.rs"),
7096 ],
7097 );
7098 }
7099
7100 #[gpui::test]
7101 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
7102 init_test(cx);
7103 let fs = FakeFs::new(cx.background_executor.clone());
7104 fs.insert_tree(
7105 "/root",
7106 json!({
7107 "project": {
7108 ".git": {},
7109 "src": {
7110 "main.rs": "fn main() {}"
7111 }
7112 }
7113 }),
7114 )
7115 .await;
7116
7117 fs.set_status_for_repo(
7118 Path::new(path!("/root/project/.git")),
7119 &[("src/main.rs", StatusCode::Modified.worktree())],
7120 );
7121
7122 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7123 let window_handle =
7124 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7125 let workspace = window_handle
7126 .read_with(cx, |mw, _| mw.workspace().clone())
7127 .unwrap();
7128 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7129
7130 let panel = workspace.update_in(cx, GitPanel::new);
7131
7132 // Test: User has commit message, enables amend (saves message), then disables (restores message)
7133 panel.update(cx, |panel, cx| {
7134 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7135 let start = buffer.anchor_before(0);
7136 let end = buffer.anchor_after(buffer.len());
7137 buffer.edit([(start..end, "Initial commit message")], None, cx);
7138 });
7139
7140 panel.set_amend_pending(true, cx);
7141 assert!(panel.original_commit_message.is_some());
7142
7143 panel.set_amend_pending(false, cx);
7144 let current_message = panel.commit_message_buffer(cx).read(cx).text();
7145 assert_eq!(current_message, "Initial commit message");
7146 assert!(panel.original_commit_message.is_none());
7147 });
7148
7149 // Test: User has empty commit message, enables amend, then disables (clears message)
7150 panel.update(cx, |panel, cx| {
7151 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7152 let start = buffer.anchor_before(0);
7153 let end = buffer.anchor_after(buffer.len());
7154 buffer.edit([(start..end, "")], None, cx);
7155 });
7156
7157 panel.set_amend_pending(true, cx);
7158 assert!(panel.original_commit_message.is_none());
7159
7160 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7161 let start = buffer.anchor_before(0);
7162 let end = buffer.anchor_after(buffer.len());
7163 buffer.edit([(start..end, "Previous commit message")], None, cx);
7164 });
7165
7166 panel.set_amend_pending(false, cx);
7167 let current_message = panel.commit_message_buffer(cx).read(cx).text();
7168 assert_eq!(current_message, "");
7169 });
7170 }
7171
7172 #[gpui::test]
7173 async fn test_amend(cx: &mut TestAppContext) {
7174 init_test(cx);
7175 let fs = FakeFs::new(cx.background_executor.clone());
7176 fs.insert_tree(
7177 "/root",
7178 json!({
7179 "project": {
7180 ".git": {},
7181 "src": {
7182 "main.rs": "fn main() {}"
7183 }
7184 }
7185 }),
7186 )
7187 .await;
7188
7189 fs.set_status_for_repo(
7190 Path::new(path!("/root/project/.git")),
7191 &[("src/main.rs", StatusCode::Modified.worktree())],
7192 );
7193
7194 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
7195 let window_handle =
7196 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7197 let workspace = window_handle
7198 .read_with(cx, |mw, _| mw.workspace().clone())
7199 .unwrap();
7200 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7201
7202 // Wait for the project scanning to finish so that `head_commit(cx)` is
7203 // actually set, otherwise no head commit would be available from which
7204 // to fetch the latest commit message from.
7205 cx.executor().run_until_parked();
7206
7207 let panel = workspace.update_in(cx, GitPanel::new);
7208 panel.read_with(cx, |panel, cx| {
7209 assert!(panel.active_repository.is_some());
7210 assert!(panel.head_commit(cx).is_some());
7211 });
7212
7213 panel.update_in(cx, |panel, window, cx| {
7214 // Update the commit editor's message to ensure that its contents
7215 // are later restored, after amending is finished.
7216 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
7217 buffer.set_text("refactor: update main.rs", cx);
7218 });
7219
7220 // Start amending the previous commit.
7221 panel.focus_editor(&Default::default(), window, cx);
7222 panel.on_amend(&Amend, window, cx);
7223 });
7224
7225 // Since `GitPanel.amend` attempts to fetch the latest commit message in
7226 // a background task, we need to wait for it to complete before being
7227 // able to assert that the commit message editor's state has been
7228 // updated.
7229 cx.run_until_parked();
7230
7231 panel.update_in(cx, |panel, window, cx| {
7232 assert_eq!(
7233 panel.commit_message_buffer(cx).read(cx).text(),
7234 "initial commit"
7235 );
7236 assert_eq!(
7237 panel.original_commit_message,
7238 Some("refactor: update main.rs".to_string())
7239 );
7240
7241 // Finish amending the previous commit.
7242 panel.focus_editor(&Default::default(), window, cx);
7243 panel.on_amend(&Amend, window, cx);
7244 });
7245
7246 // Since the actual commit logic is run in a background task, we need to
7247 // await its completion to actually ensure that the commit message
7248 // editor's contents are set to the original message and haven't been
7249 // cleared.
7250 cx.run_until_parked();
7251
7252 panel.update_in(cx, |panel, _window, cx| {
7253 // After amending, the commit editor's message should be restored to
7254 // the original message.
7255 assert_eq!(
7256 panel.commit_message_buffer(cx).read(cx).text(),
7257 "refactor: update main.rs"
7258 );
7259 assert!(panel.original_commit_message.is_none());
7260 });
7261 }
7262
7263 #[gpui::test]
7264 async fn test_open_diff(cx: &mut TestAppContext) {
7265 init_test(cx);
7266
7267 let fs = FakeFs::new(cx.background_executor.clone());
7268 fs.insert_tree(
7269 path!("/project"),
7270 json!({
7271 ".git": {},
7272 "tracked": "tracked\n",
7273 "untracked": "\n",
7274 }),
7275 )
7276 .await;
7277
7278 fs.set_head_and_index_for_repo(
7279 path!("/project/.git").as_ref(),
7280 &[("tracked", "old tracked\n".into())],
7281 );
7282
7283 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7284 let window_handle =
7285 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7286 let workspace = window_handle
7287 .read_with(cx, |mw, _| mw.workspace().clone())
7288 .unwrap();
7289 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7290 let panel = workspace.update_in(cx, GitPanel::new);
7291
7292 // Enable the `sort_by_path` setting and wait for entries to be updated,
7293 // as there should no longer be separators between Tracked and Untracked
7294 // files.
7295 cx.update(|_window, cx| {
7296 SettingsStore::update_global(cx, |store, cx| {
7297 store.update_user_settings(cx, |settings| {
7298 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7299 })
7300 });
7301 });
7302
7303 cx.update_window_entity(&panel, |panel, _, _| {
7304 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7305 })
7306 .await;
7307
7308 // Confirm that `Open Diff` still works for the untracked file, updating
7309 // the Project Diff's active path.
7310 panel.update_in(cx, |panel, window, cx| {
7311 panel.selected_entry = Some(1);
7312 panel.open_diff(&menu::Confirm, window, cx);
7313 });
7314 cx.run_until_parked();
7315
7316 workspace.update_in(cx, |workspace, _window, cx| {
7317 let active_path = workspace
7318 .item_of_type::<ProjectDiff>(cx)
7319 .expect("ProjectDiff should exist")
7320 .read(cx)
7321 .active_path(cx)
7322 .expect("active_path should exist");
7323
7324 assert_eq!(active_path.path, rel_path("untracked").into_arc());
7325 });
7326 }
7327
7328 #[gpui::test]
7329 async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7330 cx: &mut TestAppContext,
7331 ) {
7332 init_test(cx);
7333
7334 let fs = FakeFs::new(cx.background_executor.clone());
7335 fs.insert_tree(
7336 path!("/project"),
7337 json!({
7338 ".git": {},
7339 "src": {
7340 "a": {
7341 "foo.rs": "fn foo() {}",
7342 },
7343 "b": {
7344 "bar.rs": "fn bar() {}",
7345 },
7346 },
7347 }),
7348 )
7349 .await;
7350
7351 fs.set_status_for_repo(
7352 path!("/project/.git").as_ref(),
7353 &[
7354 ("src/a/foo.rs", StatusCode::Modified.worktree()),
7355 ("src/b/bar.rs", StatusCode::Modified.worktree()),
7356 ],
7357 );
7358
7359 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7360 let window_handle =
7361 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7362 let workspace = window_handle
7363 .read_with(cx, |mw, _| mw.workspace().clone())
7364 .unwrap();
7365 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7366
7367 cx.read(|cx| {
7368 project
7369 .read(cx)
7370 .worktrees(cx)
7371 .next()
7372 .unwrap()
7373 .read(cx)
7374 .as_local()
7375 .unwrap()
7376 .scan_complete()
7377 })
7378 .await;
7379
7380 cx.executor().run_until_parked();
7381
7382 cx.update(|_window, cx| {
7383 SettingsStore::update_global(cx, |store, cx| {
7384 store.update_user_settings(cx, |settings| {
7385 settings.git_panel.get_or_insert_default().tree_view = Some(true);
7386 })
7387 });
7388 });
7389
7390 let panel = workspace.update_in(cx, GitPanel::new);
7391
7392 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7393 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7394 });
7395 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7396 handle.await;
7397
7398 let src_key = panel.read_with(cx, |panel, _| {
7399 panel
7400 .entries
7401 .iter()
7402 .find_map(|entry| match entry {
7403 GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7404 Some(dir.key.clone())
7405 }
7406 _ => None,
7407 })
7408 .expect("src directory should exist in tree view")
7409 });
7410
7411 panel.update_in(cx, |panel, window, cx| {
7412 panel.toggle_directory(&src_key, window, cx);
7413 });
7414
7415 panel.read_with(cx, |panel, _| {
7416 let state = panel
7417 .view_mode
7418 .tree_state()
7419 .expect("tree view state should exist");
7420 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7421 });
7422
7423 let worktree_id =
7424 cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7425 let project_path = ProjectPath {
7426 worktree_id,
7427 path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7428 };
7429
7430 panel.update_in(cx, |panel, window, cx| {
7431 panel.select_entry_by_path(project_path, window, cx);
7432 });
7433
7434 panel.read_with(cx, |panel, _| {
7435 let state = panel
7436 .view_mode
7437 .tree_state()
7438 .expect("tree view state should exist");
7439 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7440
7441 let selected_ix = panel.selected_entry.expect("selection should be set");
7442 assert!(state.logical_indices.contains(&selected_ix));
7443
7444 let selected_entry = panel
7445 .entries
7446 .get(selected_ix)
7447 .and_then(|entry| entry.status_entry())
7448 .expect("selected entry should be a status entry");
7449 assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7450 });
7451 }
7452
7453 #[gpui::test]
7454 async fn test_tree_view_select_next_at_last_visible_collapsed_directory(
7455 cx: &mut TestAppContext,
7456 ) {
7457 init_test(cx);
7458
7459 let fs = FakeFs::new(cx.background_executor.clone());
7460 fs.insert_tree(
7461 path!("/project"),
7462 json!({
7463 ".git": {},
7464 "bar": {
7465 "bar1.py": "print('bar1')",
7466 "bar2.py": "print('bar2')",
7467 },
7468 "foo": {
7469 "foo1.py": "print('foo1')",
7470 "foo2.py": "print('foo2')",
7471 },
7472 "foobar.py": "print('foobar')",
7473 }),
7474 )
7475 .await;
7476
7477 fs.set_status_for_repo(
7478 path!("/project/.git").as_ref(),
7479 &[
7480 ("bar/bar1.py", StatusCode::Modified.worktree()),
7481 ("bar/bar2.py", StatusCode::Modified.worktree()),
7482 ("foo/foo1.py", StatusCode::Modified.worktree()),
7483 ("foo/foo2.py", StatusCode::Modified.worktree()),
7484 ("foobar.py", FileStatus::Untracked),
7485 ],
7486 );
7487
7488 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7489 let window_handle =
7490 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7491 let workspace = window_handle
7492 .read_with(cx, |mw, _| mw.workspace().clone())
7493 .unwrap();
7494 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7495
7496 cx.read(|cx| {
7497 project
7498 .read(cx)
7499 .worktrees(cx)
7500 .next()
7501 .unwrap()
7502 .read(cx)
7503 .as_local()
7504 .unwrap()
7505 .scan_complete()
7506 })
7507 .await;
7508
7509 cx.executor().run_until_parked();
7510 cx.update(|_window, cx| {
7511 SettingsStore::update_global(cx, |store, cx| {
7512 store.update_user_settings(cx, |settings| {
7513 settings.git_panel.get_or_insert_default().tree_view = Some(true);
7514 })
7515 });
7516 });
7517
7518 let panel = workspace.update_in(cx, GitPanel::new);
7519 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7520 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7521 });
7522
7523 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7524 handle.await;
7525
7526 let foo_key = panel.read_with(cx, |panel, _| {
7527 panel
7528 .entries
7529 .iter()
7530 .find_map(|entry| match entry {
7531 GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => {
7532 Some(dir.key.clone())
7533 }
7534 _ => None,
7535 })
7536 .expect("foo directory should exist in tree view")
7537 });
7538
7539 panel.update_in(cx, |panel, window, cx| {
7540 panel.toggle_directory(&foo_key, window, cx);
7541 });
7542
7543 let foo_idx = panel.read_with(cx, |panel, _| {
7544 let state = panel
7545 .view_mode
7546 .tree_state()
7547 .expect("tree view state should exist");
7548 assert_eq!(state.expanded_dirs.get(&foo_key).copied(), Some(false));
7549
7550 let foo_idx = panel
7551 .entries
7552 .iter()
7553 .enumerate()
7554 .find_map(|(index, entry)| match entry {
7555 GitListEntry::Directory(dir) if dir.key.path == repo_path("foo") => Some(index),
7556 _ => None,
7557 })
7558 .expect("foo directory should exist in tree view");
7559
7560 let foo_logical_idx = state
7561 .logical_indices
7562 .iter()
7563 .position(|&index| index == foo_idx)
7564 .expect("foo directory should be visible");
7565 let next_logical_idx = state.logical_indices[foo_logical_idx + 1];
7566 assert!(matches!(
7567 panel.entries.get(next_logical_idx),
7568 Some(GitListEntry::Header(GitHeaderEntry {
7569 header: Section::New
7570 }))
7571 ));
7572
7573 foo_idx
7574 });
7575
7576 panel.update_in(cx, |panel, window, cx| {
7577 panel.selected_entry = Some(foo_idx);
7578 panel.select_next(&menu::SelectNext, window, cx);
7579 });
7580
7581 panel.read_with(cx, |panel, _| {
7582 let selected_idx = panel.selected_entry.expect("selection should be set");
7583 let selected_entry = panel
7584 .entries
7585 .get(selected_idx)
7586 .and_then(|entry| entry.status_entry())
7587 .expect("selected entry should be a status entry");
7588 assert_eq!(selected_entry.repo_path, repo_path("foobar.py"));
7589 });
7590 }
7591
7592 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7593 assert_eq!(entries.len(), expected_paths.len());
7594 for (entry, expected_path) in entries.iter().zip(expected_paths) {
7595 assert_eq!(
7596 entry.status_entry().map(|status| status
7597 .repo_path
7598 .as_ref()
7599 .as_std_path()
7600 .to_string_lossy()
7601 .to_string()),
7602 expected_path.map(|s| s.to_string())
7603 );
7604 }
7605 }
7606
7607 #[test]
7608 fn test_compress_diff_no_truncation() {
7609 let diff = indoc! {"
7610 --- a/file.txt
7611 +++ b/file.txt
7612 @@ -1,2 +1,2 @@
7613 -old
7614 +new
7615 "};
7616 let result = GitPanel::compress_commit_diff(diff, 1000);
7617 assert_eq!(result, diff);
7618 }
7619
7620 #[test]
7621 fn test_compress_diff_truncate_long_lines() {
7622 let long_line = "🦀".repeat(300);
7623 let diff = indoc::formatdoc! {"
7624 --- a/file.txt
7625 +++ b/file.txt
7626 @@ -1,2 +1,3 @@
7627 context
7628 +{}
7629 more context
7630 ", long_line};
7631 let result = GitPanel::compress_commit_diff(&diff, 100);
7632 assert!(result.contains("...[truncated]"));
7633 assert!(result.len() < diff.len());
7634 }
7635
7636 #[test]
7637 fn test_compress_diff_truncate_hunks() {
7638 let diff = indoc! {"
7639 --- a/file.txt
7640 +++ b/file.txt
7641 @@ -1,2 +1,2 @@
7642 context
7643 -old1
7644 +new1
7645 @@ -5,2 +5,2 @@
7646 context 2
7647 -old2
7648 +new2
7649 @@ -10,2 +10,2 @@
7650 context 3
7651 -old3
7652 +new3
7653 "};
7654 let result = GitPanel::compress_commit_diff(diff, 100);
7655 let expected = indoc! {"
7656 --- a/file.txt
7657 +++ b/file.txt
7658 @@ -1,2 +1,2 @@
7659 context
7660 -old1
7661 +new1
7662 [...skipped 2 hunks...]
7663 "};
7664 assert_eq!(result, expected);
7665 }
7666
7667 #[gpui::test]
7668 async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7669 init_test(cx);
7670
7671 let fs = FakeFs::new(cx.background_executor.clone());
7672 fs.insert_tree(
7673 path!("/project"),
7674 json!({
7675 ".git": {},
7676 "tracked": "tracked\n",
7677 "untracked": "\n",
7678 }),
7679 )
7680 .await;
7681
7682 fs.set_head_and_index_for_repo(
7683 path!("/project/.git").as_ref(),
7684 &[("tracked", "old tracked\n".into())],
7685 );
7686
7687 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7688 let window_handle =
7689 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7690 let workspace = window_handle
7691 .read_with(cx, |mw, _| mw.workspace().clone())
7692 .unwrap();
7693 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7694 let panel = workspace.update_in(cx, GitPanel::new);
7695
7696 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7697 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7698 });
7699 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7700 handle.await;
7701
7702 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7703
7704 // GitPanel
7705 // - Tracked:
7706 // - [] tracked
7707 // - Untracked
7708 // - [] untracked
7709 //
7710 // The commit message should now read:
7711 // "Update tracked"
7712 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7713 assert_eq!(message, Some("Update tracked".to_string()));
7714
7715 let first_status_entry = entries[1].clone();
7716 panel.update_in(cx, |panel, window, cx| {
7717 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7718 });
7719
7720 cx.read(|cx| {
7721 project
7722 .read(cx)
7723 .worktrees(cx)
7724 .next()
7725 .unwrap()
7726 .read(cx)
7727 .as_local()
7728 .unwrap()
7729 .scan_complete()
7730 })
7731 .await;
7732
7733 cx.executor().run_until_parked();
7734
7735 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7736 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7737 });
7738 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7739 handle.await;
7740
7741 // GitPanel
7742 // - Tracked:
7743 // - [x] tracked
7744 // - Untracked
7745 // - [] untracked
7746 //
7747 // The commit message should still read:
7748 // "Update tracked"
7749 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7750 assert_eq!(message, Some("Update tracked".to_string()));
7751
7752 let second_status_entry = entries[3].clone();
7753 panel.update_in(cx, |panel, window, cx| {
7754 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7755 });
7756
7757 cx.read(|cx| {
7758 project
7759 .read(cx)
7760 .worktrees(cx)
7761 .next()
7762 .unwrap()
7763 .read(cx)
7764 .as_local()
7765 .unwrap()
7766 .scan_complete()
7767 })
7768 .await;
7769
7770 cx.executor().run_until_parked();
7771
7772 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7773 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7774 });
7775 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7776 handle.await;
7777
7778 // GitPanel
7779 // - Tracked:
7780 // - [x] tracked
7781 // - Untracked
7782 // - [x] untracked
7783 //
7784 // The commit message should now read:
7785 // "Enter commit message"
7786 // (which means we should see None returned).
7787 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7788 assert!(message.is_none());
7789
7790 panel.update_in(cx, |panel, window, cx| {
7791 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7792 });
7793
7794 cx.read(|cx| {
7795 project
7796 .read(cx)
7797 .worktrees(cx)
7798 .next()
7799 .unwrap()
7800 .read(cx)
7801 .as_local()
7802 .unwrap()
7803 .scan_complete()
7804 })
7805 .await;
7806
7807 cx.executor().run_until_parked();
7808
7809 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7810 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7811 });
7812 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7813 handle.await;
7814
7815 // GitPanel
7816 // - Tracked:
7817 // - [] tracked
7818 // - Untracked
7819 // - [x] untracked
7820 //
7821 // The commit message should now read:
7822 // "Update untracked"
7823 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7824 assert_eq!(message, Some("Create untracked".to_string()));
7825
7826 panel.update_in(cx, |panel, window, cx| {
7827 panel.toggle_staged_for_entry(&second_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 // - [] untracked
7856 //
7857 // The commit message should now read:
7858 // "Update tracked"
7859 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7860 assert_eq!(message, Some("Update tracked".to_string()));
7861 }
7862
7863 #[gpui::test]
7864 async fn test_dispatch_context_with_focus_states(cx: &mut TestAppContext) {
7865 init_test(cx);
7866
7867 let fs = FakeFs::new(cx.background_executor.clone());
7868 fs.insert_tree(
7869 path!("/project"),
7870 json!({
7871 ".git": {},
7872 "tracked": "tracked\n",
7873 }),
7874 )
7875 .await;
7876
7877 fs.set_head_and_index_for_repo(
7878 path!("/project/.git").as_ref(),
7879 &[("tracked", "old tracked\n".into())],
7880 );
7881
7882 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7883 let window_handle =
7884 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7885 let workspace = window_handle
7886 .read_with(cx, |mw, _| mw.workspace().clone())
7887 .unwrap();
7888 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7889 let panel = workspace.update_in(cx, GitPanel::new);
7890
7891 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7892 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7893 });
7894 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7895 handle.await;
7896
7897 // Case 1: Focus the commit editor — should have "CommitEditor" but NOT "menu"/"ChangesList"
7898 panel.update_in(cx, |panel, window, cx| {
7899 panel.focus_editor(&FocusEditor, window, cx);
7900 let editor_is_focused = panel.commit_editor.read(cx).is_focused(window);
7901 assert!(
7902 editor_is_focused,
7903 "commit editor should be focused after focus_editor action"
7904 );
7905 let context = panel.dispatch_context(window, cx);
7906 assert!(
7907 context.contains("GitPanel"),
7908 "should always have GitPanel context"
7909 );
7910 assert!(
7911 context.contains("CommitEditor"),
7912 "should have CommitEditor context when commit editor is focused"
7913 );
7914 assert!(
7915 !context.contains("menu"),
7916 "should not have menu context when commit editor is focused"
7917 );
7918 assert!(
7919 !context.contains("ChangesList"),
7920 "should not have ChangesList context when commit editor is focused"
7921 );
7922 });
7923
7924 // Case 2: Focus the panel's focus handle directly — should have "menu" and "ChangesList".
7925 // We force a draw via simulate_resize to ensure the dispatch tree is populated,
7926 // since contains_focused() depends on the rendered dispatch tree.
7927 panel.update_in(cx, |panel, window, cx| {
7928 panel.focus_handle.focus(window, cx);
7929 });
7930 cx.simulate_resize(gpui::size(px(800.), px(600.)));
7931
7932 panel.update_in(cx, |panel, window, cx| {
7933 let context = panel.dispatch_context(window, cx);
7934 assert!(
7935 context.contains("GitPanel"),
7936 "should always have GitPanel context"
7937 );
7938 assert!(
7939 context.contains("menu"),
7940 "should have menu context when changes list is focused"
7941 );
7942 assert!(
7943 context.contains("ChangesList"),
7944 "should have ChangesList context when changes list is focused"
7945 );
7946 assert!(
7947 !context.contains("CommitEditor"),
7948 "should not have CommitEditor context when changes list is focused"
7949 );
7950 });
7951
7952 // Case 3: Switch back to commit editor and verify context switches correctly
7953 panel.update_in(cx, |panel, window, cx| {
7954 panel.focus_editor(&FocusEditor, window, cx);
7955 });
7956
7957 panel.update_in(cx, |panel, window, cx| {
7958 let context = panel.dispatch_context(window, cx);
7959 assert!(
7960 context.contains("CommitEditor"),
7961 "should have CommitEditor after switching focus back to editor"
7962 );
7963 assert!(
7964 !context.contains("menu"),
7965 "should not have menu after switching focus back to editor"
7966 );
7967 });
7968
7969 // Case 4: Re-focus changes list and verify it transitions back correctly
7970 panel.update_in(cx, |panel, window, cx| {
7971 panel.focus_handle.focus(window, cx);
7972 });
7973 cx.simulate_resize(gpui::size(px(800.), px(600.)));
7974
7975 panel.update_in(cx, |panel, window, cx| {
7976 assert!(
7977 panel.focus_handle.contains_focused(window, cx),
7978 "panel focus handle should report contains_focused when directly focused"
7979 );
7980 let context = panel.dispatch_context(window, cx);
7981 assert!(
7982 context.contains("menu"),
7983 "should have menu context after re-focusing changes list"
7984 );
7985 assert!(
7986 context.contains("ChangesList"),
7987 "should have ChangesList context after re-focusing changes list"
7988 );
7989 });
7990 }
7991}