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