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