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