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