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, 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 h_flex().h_full().flex_grow().justify_center().child(
4570 v_flex()
4571 .gap_2()
4572 .child(h_flex().w_full().justify_around().child(
4573 if self.active_repository.is_some() {
4574 "No changes to commit"
4575 } else {
4576 "No Git repositories"
4577 },
4578 ))
4579 .children({
4580 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4581 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
4582 h_flex().w_full().justify_around().child(
4583 panel_filled_button("Initialize Repository")
4584 .tooltip(Tooltip::for_action_title_in(
4585 "git init",
4586 &git::Init,
4587 &self.focus_handle,
4588 ))
4589 .on_click(move |_, _, cx| {
4590 cx.defer(move |cx| {
4591 cx.dispatch_action(&git::Init);
4592 })
4593 }),
4594 )
4595 })
4596 })
4597 .text_ui_sm(cx)
4598 .mx_auto()
4599 .text_color(Color::Placeholder.color(cx)),
4600 )
4601 }
4602
4603 fn render_buffer_header_controls(
4604 &self,
4605 entity: &Entity<Self>,
4606 file: &Arc<dyn File>,
4607 _: &Window,
4608 cx: &App,
4609 ) -> Option<AnyElement> {
4610 let repo = self.active_repository.as_ref()?.read(cx);
4611 let project_path = (file.worktree_id(cx), file.path().clone()).into();
4612 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4613 let ix = self.entry_by_path(&repo_path)?;
4614 let entry = self.entries.get(ix)?;
4615
4616 let is_staging_or_staged = repo
4617 .pending_ops_for_path(&repo_path)
4618 .map(|ops| ops.staging() || ops.staged())
4619 .or_else(|| {
4620 repo.status_for_path(&repo_path)
4621 .and_then(|status| status.status.staging().as_bool())
4622 })
4623 .or_else(|| {
4624 entry
4625 .status_entry()
4626 .and_then(|entry| entry.staging.as_bool())
4627 });
4628
4629 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4630 .disabled(!self.has_write_access(cx))
4631 .fill()
4632 .elevation(ElevationIndex::Surface)
4633 .on_click({
4634 let entry = entry.clone();
4635 let git_panel = entity.downgrade();
4636 move |_, window, cx| {
4637 git_panel
4638 .update(cx, |this, cx| {
4639 this.toggle_staged_for_entry(&entry, window, cx);
4640 cx.stop_propagation();
4641 })
4642 .ok();
4643 }
4644 });
4645 Some(
4646 h_flex()
4647 .id("start-slot")
4648 .text_lg()
4649 .child(checkbox)
4650 .on_mouse_down(MouseButton::Left, |_, _, cx| {
4651 // prevent the list item active state triggering when toggling checkbox
4652 cx.stop_propagation();
4653 })
4654 .into_any_element(),
4655 )
4656 }
4657
4658 fn render_entries(
4659 &self,
4660 has_write_access: bool,
4661 repo: Entity<Repository>,
4662 window: &mut Window,
4663 cx: &mut Context<Self>,
4664 ) -> impl IntoElement {
4665 let (is_tree_view, entry_count) = match &self.view_mode {
4666 GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4667 GitPanelViewMode::Flat => (false, self.entries.len()),
4668 };
4669 let repo = repo.downgrade();
4670
4671 v_flex()
4672 .flex_1()
4673 .size_full()
4674 .overflow_hidden()
4675 .relative()
4676 .child(
4677 h_flex()
4678 .flex_1()
4679 .size_full()
4680 .relative()
4681 .overflow_hidden()
4682 .child(
4683 uniform_list(
4684 "entries",
4685 entry_count,
4686 cx.processor(move |this, range: Range<usize>, window, cx| {
4687 let Some(repo) = repo.upgrade() else {
4688 return Vec::new();
4689 };
4690 let repo = repo.read(cx);
4691
4692 let mut items = Vec::with_capacity(range.end - range.start);
4693
4694 for ix in range.into_iter().map(|ix| match &this.view_mode {
4695 GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4696 GitPanelViewMode::Flat => ix,
4697 }) {
4698 match &this.entries.get(ix) {
4699 Some(GitListEntry::Status(entry)) => {
4700 items.push(this.render_status_entry(
4701 ix,
4702 entry,
4703 0,
4704 has_write_access,
4705 repo,
4706 window,
4707 cx,
4708 ));
4709 }
4710 Some(GitListEntry::TreeStatus(entry)) => {
4711 items.push(this.render_status_entry(
4712 ix,
4713 &entry.entry,
4714 entry.depth,
4715 has_write_access,
4716 repo,
4717 window,
4718 cx,
4719 ));
4720 }
4721 Some(GitListEntry::Directory(entry)) => {
4722 items.push(this.render_directory_entry(
4723 ix,
4724 entry,
4725 has_write_access,
4726 window,
4727 cx,
4728 ));
4729 }
4730 Some(GitListEntry::Header(header)) => {
4731 items.push(this.render_list_header(
4732 ix,
4733 header,
4734 has_write_access,
4735 window,
4736 cx,
4737 ));
4738 }
4739 None => {}
4740 }
4741 }
4742
4743 items
4744 }),
4745 )
4746 .when(is_tree_view, |list| {
4747 let indent_size = px(TREE_INDENT);
4748 list.with_decoration(
4749 ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4750 .with_compute_indents_fn(
4751 cx.entity(),
4752 |this, range, _window, _cx| {
4753 this.compute_visible_depths(range)
4754 },
4755 )
4756 .with_render_fn(cx.entity(), |_, params, _, _| {
4757 // Magic number to align the tree item is 3 here
4758 // because we're using 12px as the left-side padding
4759 // and 3 makes the alignment work with the bounding box of the icon
4760 let left_offset = px(TREE_INDENT + 3_f32);
4761 let indent_size = params.indent_size;
4762 let item_height = params.item_height;
4763
4764 params
4765 .indent_guides
4766 .into_iter()
4767 .map(|layout| {
4768 let bounds = Bounds::new(
4769 point(
4770 layout.offset.x * indent_size + left_offset,
4771 layout.offset.y * item_height,
4772 ),
4773 size(px(1.), layout.length * item_height),
4774 );
4775 RenderedIndentGuide {
4776 bounds,
4777 layout,
4778 is_active: false,
4779 hitbox: None,
4780 }
4781 })
4782 .collect()
4783 }),
4784 )
4785 })
4786 .size_full()
4787 .flex_grow()
4788 .with_width_from_item(self.max_width_item_index)
4789 .track_scroll(&self.scroll_handle),
4790 )
4791 .on_mouse_down(
4792 MouseButton::Right,
4793 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4794 this.deploy_panel_context_menu(event.position, window, cx)
4795 }),
4796 )
4797 .custom_scrollbars(
4798 Scrollbars::for_settings::<GitPanelSettings>()
4799 .tracked_scroll_handle(&self.scroll_handle)
4800 .with_track_along(
4801 ScrollAxes::Horizontal,
4802 cx.theme().colors().panel_background,
4803 ),
4804 window,
4805 cx,
4806 ),
4807 )
4808 }
4809
4810 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4811 Label::new(label.into()).color(color)
4812 }
4813
4814 fn list_item_height(&self) -> Rems {
4815 rems(1.75)
4816 }
4817
4818 fn render_list_header(
4819 &self,
4820 ix: usize,
4821 header: &GitHeaderEntry,
4822 _: bool,
4823 _: &Window,
4824 _: &Context<Self>,
4825 ) -> AnyElement {
4826 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4827
4828 h_flex()
4829 .id(id)
4830 .h(self.list_item_height())
4831 .w_full()
4832 .items_end()
4833 .px_3()
4834 .pb_1()
4835 .child(
4836 Label::new(header.title())
4837 .color(Color::Muted)
4838 .size(LabelSize::Small)
4839 .line_height_style(LineHeightStyle::UiLabel)
4840 .single_line(),
4841 )
4842 .into_any_element()
4843 }
4844
4845 pub fn load_commit_details(
4846 &self,
4847 sha: String,
4848 cx: &mut Context<Self>,
4849 ) -> Task<anyhow::Result<CommitDetails>> {
4850 let Some(repo) = self.active_repository.clone() else {
4851 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4852 };
4853 repo.update(cx, |repo, cx| {
4854 let show = repo.show(sha);
4855 cx.spawn(async move |_, _| show.await?)
4856 })
4857 }
4858
4859 fn deploy_entry_context_menu(
4860 &mut self,
4861 position: Point<Pixels>,
4862 ix: usize,
4863 window: &mut Window,
4864 cx: &mut Context<Self>,
4865 ) {
4866 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4867 return;
4868 };
4869 let stage_title = if entry.status.staging().is_fully_staged() {
4870 "Unstage File"
4871 } else {
4872 "Stage File"
4873 };
4874 let restore_title = if entry.status.is_created() {
4875 "Trash File"
4876 } else {
4877 "Discard Changes"
4878 };
4879 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4880 let is_created = entry.status.is_created();
4881 context_menu
4882 .context(self.focus_handle.clone())
4883 .action(stage_title, ToggleStaged.boxed_clone())
4884 .action(restore_title, git::RestoreFile::default().boxed_clone())
4885 .action_disabled_when(
4886 !is_created,
4887 "Add to .gitignore",
4888 git::AddToGitignore.boxed_clone(),
4889 )
4890 .separator()
4891 .action("Open Diff", menu::Confirm.boxed_clone())
4892 .action("Open File", menu::SecondaryConfirm.boxed_clone())
4893 .separator()
4894 .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4895 });
4896 self.selected_entry = Some(ix);
4897 self.set_context_menu(context_menu, position, window, cx);
4898 }
4899
4900 fn deploy_panel_context_menu(
4901 &mut self,
4902 position: Point<Pixels>,
4903 window: &mut Window,
4904 cx: &mut Context<Self>,
4905 ) {
4906 let context_menu = git_panel_context_menu(
4907 self.focus_handle.clone(),
4908 GitMenuState {
4909 has_tracked_changes: self.has_tracked_changes(),
4910 has_staged_changes: self.has_staged_changes(),
4911 has_unstaged_changes: self.has_unstaged_changes(),
4912 has_new_changes: self.new_count > 0,
4913 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4914 has_stash_items: self.stash_entries.entries.len() > 0,
4915 tree_view: GitPanelSettings::get_global(cx).tree_view,
4916 },
4917 window,
4918 cx,
4919 );
4920 self.set_context_menu(context_menu, position, window, cx);
4921 }
4922
4923 fn set_context_menu(
4924 &mut self,
4925 context_menu: Entity<ContextMenu>,
4926 position: Point<Pixels>,
4927 window: &Window,
4928 cx: &mut Context<Self>,
4929 ) {
4930 let subscription = cx.subscribe_in(
4931 &context_menu,
4932 window,
4933 |this, _, _: &DismissEvent, window, cx| {
4934 if this.context_menu.as_ref().is_some_and(|context_menu| {
4935 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4936 }) {
4937 cx.focus_self(window);
4938 }
4939 this.context_menu.take();
4940 cx.notify();
4941 },
4942 );
4943 self.context_menu = Some((context_menu, position, subscription));
4944 cx.notify();
4945 }
4946
4947 fn render_status_entry(
4948 &self,
4949 ix: usize,
4950 entry: &GitStatusEntry,
4951 depth: usize,
4952 has_write_access: bool,
4953 repo: &Repository,
4954 window: &Window,
4955 cx: &Context<Self>,
4956 ) -> AnyElement {
4957 let tree_view = GitPanelSettings::get_global(cx).tree_view;
4958 let path_style = self.project.read(cx).path_style(cx);
4959 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
4960 let display_name = entry.display_name(path_style);
4961
4962 let selected = self.selected_entry == Some(ix);
4963 let marked = self.marked_entries.contains(&ix);
4964 let status_style = GitPanelSettings::get_global(cx).status_style;
4965 let status = entry.status;
4966
4967 let has_conflict = status.is_conflicted();
4968 let is_modified = status.is_modified();
4969 let is_deleted = status.is_deleted();
4970 let is_created = status.is_created();
4971
4972 let label_color = if status_style == StatusStyle::LabelColor {
4973 if has_conflict {
4974 Color::VersionControlConflict
4975 } else if is_created {
4976 Color::VersionControlAdded
4977 } else if is_modified {
4978 Color::VersionControlModified
4979 } else if is_deleted {
4980 // We don't want a bunch of red labels in the list
4981 Color::Disabled
4982 } else {
4983 Color::VersionControlAdded
4984 }
4985 } else {
4986 Color::Default
4987 };
4988
4989 let path_color = if status.is_deleted() {
4990 Color::Disabled
4991 } else {
4992 Color::Muted
4993 };
4994
4995 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4996 let checkbox_wrapper_id: ElementId =
4997 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4998 let checkbox_id: ElementId =
4999 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
5000
5001 let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
5002 let mut is_staged: ToggleState = match stage_status {
5003 StageStatus::Staged => ToggleState::Selected,
5004 StageStatus::Unstaged => ToggleState::Unselected,
5005 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5006 };
5007 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
5008 is_staged = ToggleState::Selected;
5009 }
5010
5011 let handle = cx.weak_entity();
5012
5013 let selected_bg_alpha = 0.08;
5014 let marked_bg_alpha = 0.12;
5015 let state_opacity_step = 0.04;
5016
5017 let info_color = cx.theme().status().info;
5018
5019 let base_bg = match (selected, marked) {
5020 (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
5021 (true, false) => info_color.alpha(selected_bg_alpha),
5022 (false, true) => info_color.alpha(marked_bg_alpha),
5023 _ => cx.theme().colors().ghost_element_background,
5024 };
5025
5026 let (hover_bg, active_bg) = if selected {
5027 (
5028 info_color.alpha(selected_bg_alpha + state_opacity_step),
5029 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5030 )
5031 } else {
5032 (
5033 cx.theme().colors().ghost_element_hover,
5034 cx.theme().colors().ghost_element_active,
5035 )
5036 };
5037
5038 let name_row = h_flex()
5039 .min_w_0()
5040 .flex_1()
5041 .gap_1()
5042 .child(git_status_icon(status))
5043 .map(|this| {
5044 if tree_view {
5045 this.pl(px(depth as f32 * TREE_INDENT)).child(
5046 self.entry_label(display_name, label_color)
5047 .when(status.is_deleted(), Label::strikethrough)
5048 .truncate(),
5049 )
5050 } else {
5051 this.child(self.path_formatted(
5052 entry.parent_dir(path_style),
5053 path_color,
5054 display_name,
5055 label_color,
5056 path_style,
5057 git_path_style,
5058 status.is_deleted(),
5059 ))
5060 }
5061 });
5062
5063 h_flex()
5064 .id(id)
5065 .h(self.list_item_height())
5066 .w_full()
5067 .pl_3()
5068 .pr_1()
5069 .gap_1p5()
5070 .border_1()
5071 .border_r_2()
5072 .when(selected && self.focus_handle.is_focused(window), |el| {
5073 el.border_color(cx.theme().colors().panel_focused_border)
5074 })
5075 .bg(base_bg)
5076 .hover(|s| s.bg(hover_bg))
5077 .active(|s| s.bg(active_bg))
5078 .child(name_row)
5079 .child(
5080 div()
5081 .id(checkbox_wrapper_id)
5082 .flex_none()
5083 .occlude()
5084 .cursor_pointer()
5085 .child(
5086 Checkbox::new(checkbox_id, is_staged)
5087 .disabled(!has_write_access)
5088 .fill()
5089 .elevation(ElevationIndex::Surface)
5090 .on_click_ext({
5091 let entry = entry.clone();
5092 let this = cx.weak_entity();
5093 move |_, click, window, cx| {
5094 this.update(cx, |this, cx| {
5095 if !has_write_access {
5096 return;
5097 }
5098 if click.modifiers().shift {
5099 this.stage_bulk(ix, cx);
5100 } else {
5101 let list_entry =
5102 if GitPanelSettings::get_global(cx).tree_view {
5103 GitListEntry::TreeStatus(GitTreeStatusEntry {
5104 entry: entry.clone(),
5105 depth,
5106 })
5107 } else {
5108 GitListEntry::Status(entry.clone())
5109 };
5110 this.toggle_staged_for_entry(&list_entry, window, cx);
5111 }
5112 cx.stop_propagation();
5113 })
5114 .ok();
5115 }
5116 })
5117 .tooltip(move |_window, cx| {
5118 let action = match stage_status {
5119 StageStatus::Staged => "Unstage",
5120 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5121 };
5122 let tooltip_name = action.to_string();
5123
5124 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5125 }),
5126 ),
5127 )
5128 .on_click({
5129 cx.listener(move |this, event: &ClickEvent, window, cx| {
5130 this.selected_entry = Some(ix);
5131 cx.notify();
5132 if event.click_count() > 1 || event.modifiers().secondary() {
5133 this.open_file(&Default::default(), window, cx)
5134 } else {
5135 this.open_diff(&Default::default(), window, cx);
5136 this.focus_handle.focus(window, cx);
5137 }
5138 })
5139 })
5140 .on_mouse_down(
5141 MouseButton::Right,
5142 move |event: &MouseDownEvent, window, cx| {
5143 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5144 if event.button != MouseButton::Right {
5145 return;
5146 }
5147
5148 let Some(this) = handle.upgrade() else {
5149 return;
5150 };
5151 this.update(cx, |this, cx| {
5152 this.deploy_entry_context_menu(event.position, ix, window, cx);
5153 });
5154 cx.stop_propagation();
5155 },
5156 )
5157 .into_any_element()
5158 }
5159
5160 fn render_directory_entry(
5161 &self,
5162 ix: usize,
5163 entry: &GitTreeDirEntry,
5164 has_write_access: bool,
5165 window: &Window,
5166 cx: &Context<Self>,
5167 ) -> AnyElement {
5168 // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5169 let selected = self.selected_entry == Some(ix);
5170 let label_color = Color::Muted;
5171
5172 let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5173 let checkbox_id: ElementId =
5174 ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5175 let checkbox_wrapper_id: ElementId =
5176 ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5177
5178 let selected_bg_alpha = 0.08;
5179 let state_opacity_step = 0.04;
5180
5181 let info_color = cx.theme().status().info;
5182 let colors = cx.theme().colors();
5183
5184 let (base_bg, hover_bg, active_bg) = if selected {
5185 (
5186 info_color.alpha(selected_bg_alpha),
5187 info_color.alpha(selected_bg_alpha + state_opacity_step),
5188 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5189 )
5190 } else {
5191 (
5192 colors.ghost_element_background,
5193 colors.ghost_element_hover,
5194 colors.ghost_element_active,
5195 )
5196 };
5197
5198 let folder_icon = if entry.expanded {
5199 IconName::FolderOpen
5200 } else {
5201 IconName::Folder
5202 };
5203
5204 let stage_status = if let Some(repo) = &self.active_repository {
5205 self.stage_status_for_directory(entry, repo.read(cx))
5206 } else {
5207 util::debug_panic!(
5208 "Won't have entries to render without an active repository in Git Panel"
5209 );
5210 StageStatus::PartiallyStaged
5211 };
5212
5213 let toggle_state: ToggleState = match stage_status {
5214 StageStatus::Staged => ToggleState::Selected,
5215 StageStatus::Unstaged => ToggleState::Unselected,
5216 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5217 };
5218
5219 let name_row = h_flex()
5220 .min_w_0()
5221 .gap_1()
5222 .pl(px(entry.depth as f32 * TREE_INDENT))
5223 .child(
5224 Icon::new(folder_icon)
5225 .size(IconSize::Small)
5226 .color(Color::Muted),
5227 )
5228 .child(self.entry_label(entry.name.clone(), label_color).truncate());
5229
5230 h_flex()
5231 .id(id)
5232 .h(self.list_item_height())
5233 .min_w_0()
5234 .w_full()
5235 .pl_3()
5236 .pr_1()
5237 .gap_1p5()
5238 .justify_between()
5239 .border_1()
5240 .border_r_2()
5241 .when(selected && self.focus_handle.is_focused(window), |el| {
5242 el.border_color(cx.theme().colors().panel_focused_border)
5243 })
5244 .bg(base_bg)
5245 .hover(|s| s.bg(hover_bg))
5246 .active(|s| s.bg(active_bg))
5247 .child(name_row)
5248 .child(
5249 div()
5250 .id(checkbox_wrapper_id)
5251 .flex_none()
5252 .occlude()
5253 .cursor_pointer()
5254 .child(
5255 Checkbox::new(checkbox_id, toggle_state)
5256 .disabled(!has_write_access)
5257 .fill()
5258 .elevation(ElevationIndex::Surface)
5259 .on_click({
5260 let entry = entry.clone();
5261 let this = cx.weak_entity();
5262 move |_, window, cx| {
5263 this.update(cx, |this, cx| {
5264 if !has_write_access {
5265 return;
5266 }
5267 this.toggle_staged_for_entry(
5268 &GitListEntry::Directory(entry.clone()),
5269 window,
5270 cx,
5271 );
5272 cx.stop_propagation();
5273 })
5274 .ok();
5275 }
5276 })
5277 .tooltip(move |_window, cx| {
5278 let action = match stage_status {
5279 StageStatus::Staged => "Unstage",
5280 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5281 };
5282 Tooltip::simple(format!("{action} folder"), cx)
5283 }),
5284 ),
5285 )
5286 .on_click({
5287 let key = entry.key.clone();
5288 cx.listener(move |this, _event: &ClickEvent, window, cx| {
5289 this.selected_entry = Some(ix);
5290 this.toggle_directory(&key, window, cx);
5291 })
5292 })
5293 .into_any_element()
5294 }
5295
5296 fn path_formatted(
5297 &self,
5298 directory: Option<String>,
5299 path_color: Color,
5300 file_name: String,
5301 label_color: Color,
5302 path_style: PathStyle,
5303 git_path_style: GitPathStyle,
5304 strikethrough: bool,
5305 ) -> Div {
5306 let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5307 let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5308
5309 let file_name = format!("{} ", file_name);
5310
5311 h_flex()
5312 .min_w_0()
5313 .overflow_hidden()
5314 .when(file_path_first, |this| this.flex_row_reverse())
5315 .child(
5316 div().flex_none().child(
5317 self.entry_label(file_name, label_color)
5318 .when(strikethrough, Label::strikethrough),
5319 ),
5320 )
5321 .when_some(directory, |this, dir| {
5322 let path_name = if file_name_first {
5323 dir
5324 } else {
5325 format!("{dir}{}", path_style.primary_separator())
5326 };
5327
5328 this.child(
5329 self.entry_label(path_name, path_color)
5330 .truncate_start()
5331 .when(strikethrough, Label::strikethrough),
5332 )
5333 })
5334 }
5335
5336 fn has_write_access(&self, cx: &App) -> bool {
5337 !self.project.read(cx).is_read_only(cx)
5338 }
5339
5340 pub fn amend_pending(&self) -> bool {
5341 self.amend_pending
5342 }
5343
5344 /// Sets the pending amend state, ensuring that the original commit message
5345 /// is either saved, when `value` is `true` and there's no pending amend, or
5346 /// restored, when `value` is `false` and there's a pending amend.
5347 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5348 if value && !self.amend_pending {
5349 let current_message = self.commit_message_buffer(cx).read(cx).text();
5350 self.original_commit_message = if current_message.trim().is_empty() {
5351 None
5352 } else {
5353 Some(current_message)
5354 };
5355 } else if !value && self.amend_pending {
5356 let message = self.original_commit_message.take().unwrap_or_default();
5357 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5358 let start = buffer.anchor_before(0);
5359 let end = buffer.anchor_after(buffer.len());
5360 buffer.edit([(start..end, message)], None, cx);
5361 });
5362 }
5363
5364 self.amend_pending = value;
5365 self.serialize(cx);
5366 cx.notify();
5367 }
5368
5369 pub fn signoff_enabled(&self) -> bool {
5370 self.signoff_enabled
5371 }
5372
5373 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5374 self.signoff_enabled = value;
5375 self.serialize(cx);
5376 cx.notify();
5377 }
5378
5379 pub fn toggle_signoff_enabled(
5380 &mut self,
5381 _: &Signoff,
5382 _window: &mut Window,
5383 cx: &mut Context<Self>,
5384 ) {
5385 self.set_signoff_enabled(!self.signoff_enabled, cx);
5386 }
5387
5388 pub async fn load(
5389 workspace: WeakEntity<Workspace>,
5390 mut cx: AsyncWindowContext,
5391 ) -> anyhow::Result<Entity<Self>> {
5392 let serialized_panel = match workspace
5393 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
5394 .ok()
5395 .flatten()
5396 {
5397 Some(serialization_key) => cx
5398 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
5399 .await
5400 .context("loading git panel")
5401 .log_err()
5402 .flatten()
5403 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5404 .transpose()
5405 .log_err()
5406 .flatten(),
5407 None => None,
5408 };
5409
5410 workspace.update_in(&mut cx, |workspace, window, cx| {
5411 let panel = GitPanel::new(workspace, window, cx);
5412
5413 if let Some(serialized_panel) = serialized_panel {
5414 panel.update(cx, |panel, cx| {
5415 panel.width = serialized_panel.width;
5416 panel.amend_pending = serialized_panel.amend_pending;
5417 panel.signoff_enabled = serialized_panel.signoff_enabled;
5418 cx.notify();
5419 })
5420 }
5421
5422 panel
5423 })
5424 }
5425
5426 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5427 let Some(op) = self.bulk_staging.as_ref() else {
5428 return;
5429 };
5430 let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5431 return;
5432 };
5433 if let Some(entry) = self.entries.get(index)
5434 && let Some(entry) = entry.status_entry()
5435 {
5436 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5437 }
5438 if index < anchor_index {
5439 std::mem::swap(&mut index, &mut anchor_index);
5440 }
5441 let entries = self
5442 .entries
5443 .get(anchor_index..=index)
5444 .unwrap_or_default()
5445 .iter()
5446 .filter_map(|entry| entry.status_entry().cloned())
5447 .collect::<Vec<_>>();
5448 self.change_file_stage(true, entries, cx);
5449 }
5450
5451 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5452 let Some(repo) = self.active_repository.as_ref() else {
5453 return;
5454 };
5455 self.bulk_staging = Some(BulkStaging {
5456 repo_id: repo.read(cx).id,
5457 anchor: path,
5458 });
5459 }
5460
5461 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5462 self.set_amend_pending(!self.amend_pending, cx);
5463 if self.amend_pending {
5464 self.load_last_commit_message(cx);
5465 }
5466 }
5467}
5468
5469impl Render for GitPanel {
5470 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5471 let project = self.project.read(cx);
5472 let has_entries = !self.entries.is_empty();
5473 let room = self
5474 .workspace
5475 .upgrade()
5476 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
5477
5478 let has_write_access = self.has_write_access(cx);
5479
5480 let has_co_authors = room.is_some_and(|room| {
5481 self.load_local_committer(cx);
5482 let room = room.read(cx);
5483 room.remote_participants()
5484 .values()
5485 .any(|remote_participant| remote_participant.can_write())
5486 });
5487
5488 v_flex()
5489 .id("git_panel")
5490 .key_context(self.dispatch_context(window, cx))
5491 .track_focus(&self.focus_handle)
5492 .when(has_write_access && !project.is_read_only(cx), |this| {
5493 this.on_action(cx.listener(Self::toggle_staged_for_selected))
5494 .on_action(cx.listener(Self::stage_range))
5495 .on_action(cx.listener(GitPanel::on_commit))
5496 .on_action(cx.listener(GitPanel::on_amend))
5497 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5498 .on_action(cx.listener(Self::stage_all))
5499 .on_action(cx.listener(Self::unstage_all))
5500 .on_action(cx.listener(Self::stage_selected))
5501 .on_action(cx.listener(Self::unstage_selected))
5502 .on_action(cx.listener(Self::restore_tracked_files))
5503 .on_action(cx.listener(Self::revert_selected))
5504 .on_action(cx.listener(Self::add_to_gitignore))
5505 .on_action(cx.listener(Self::clean_all))
5506 .on_action(cx.listener(Self::generate_commit_message_action))
5507 .on_action(cx.listener(Self::stash_all))
5508 .on_action(cx.listener(Self::stash_pop))
5509 })
5510 .on_action(cx.listener(Self::collapse_selected_entry))
5511 .on_action(cx.listener(Self::expand_selected_entry))
5512 .on_action(cx.listener(Self::select_first))
5513 .on_action(cx.listener(Self::select_next))
5514 .on_action(cx.listener(Self::select_previous))
5515 .on_action(cx.listener(Self::select_last))
5516 .on_action(cx.listener(Self::first_entry))
5517 .on_action(cx.listener(Self::next_entry))
5518 .on_action(cx.listener(Self::previous_entry))
5519 .on_action(cx.listener(Self::last_entry))
5520 .on_action(cx.listener(Self::close_panel))
5521 .on_action(cx.listener(Self::open_diff))
5522 .on_action(cx.listener(Self::open_file))
5523 .on_action(cx.listener(Self::file_history))
5524 .on_action(cx.listener(Self::focus_changes_list))
5525 .on_action(cx.listener(Self::focus_editor))
5526 .on_action(cx.listener(Self::expand_commit_editor))
5527 .when(has_write_access && has_co_authors, |git_panel| {
5528 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5529 })
5530 .on_action(cx.listener(Self::toggle_sort_by_path))
5531 .on_action(cx.listener(Self::toggle_tree_view))
5532 .size_full()
5533 .overflow_hidden()
5534 .bg(cx.theme().colors().panel_background)
5535 .child(
5536 v_flex()
5537 .size_full()
5538 .children(self.render_panel_header(window, cx))
5539 .map(|this| {
5540 if let Some(repo) = self.active_repository.clone()
5541 && has_entries
5542 {
5543 this.child(self.render_entries(has_write_access, repo, window, cx))
5544 } else {
5545 this.child(self.render_empty_state(cx).into_any_element())
5546 }
5547 })
5548 .children(self.render_footer(window, cx))
5549 .when(self.amend_pending, |this| {
5550 this.child(self.render_pending_amend(cx))
5551 })
5552 .when(!self.amend_pending, |this| {
5553 this.children(self.render_previous_commit(window, cx))
5554 })
5555 .into_any_element(),
5556 )
5557 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5558 deferred(
5559 anchored()
5560 .position(*position)
5561 .anchor(Corner::TopLeft)
5562 .child(menu.clone()),
5563 )
5564 .with_priority(1)
5565 }))
5566 }
5567}
5568
5569impl Focusable for GitPanel {
5570 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5571 if self.entries.is_empty() {
5572 self.commit_editor.focus_handle(cx)
5573 } else {
5574 self.focus_handle.clone()
5575 }
5576 }
5577}
5578
5579impl EventEmitter<Event> for GitPanel {}
5580
5581impl EventEmitter<PanelEvent> for GitPanel {}
5582
5583pub(crate) struct GitPanelAddon {
5584 pub(crate) workspace: WeakEntity<Workspace>,
5585}
5586
5587impl editor::Addon for GitPanelAddon {
5588 fn to_any(&self) -> &dyn std::any::Any {
5589 self
5590 }
5591
5592 fn render_buffer_header_controls(
5593 &self,
5594 excerpt_info: &ExcerptInfo,
5595 window: &Window,
5596 cx: &App,
5597 ) -> Option<AnyElement> {
5598 let file = excerpt_info.buffer.file()?;
5599 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5600
5601 git_panel
5602 .read(cx)
5603 .render_buffer_header_controls(&git_panel, file, window, cx)
5604 }
5605}
5606
5607impl Panel for GitPanel {
5608 fn persistent_name() -> &'static str {
5609 "GitPanel"
5610 }
5611
5612 fn panel_key() -> &'static str {
5613 GIT_PANEL_KEY
5614 }
5615
5616 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5617 GitPanelSettings::get_global(cx).dock
5618 }
5619
5620 fn position_is_valid(&self, position: DockPosition) -> bool {
5621 matches!(position, DockPosition::Left | DockPosition::Right)
5622 }
5623
5624 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5625 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5626 settings.git_panel.get_or_insert_default().dock = Some(position.into())
5627 });
5628 }
5629
5630 fn size(&self, _: &Window, cx: &App) -> Pixels {
5631 self.width
5632 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
5633 }
5634
5635 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
5636 self.width = size;
5637 self.serialize(cx);
5638 cx.notify();
5639 }
5640
5641 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5642 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5643 }
5644
5645 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5646 Some("Git Panel")
5647 }
5648
5649 fn toggle_action(&self) -> Box<dyn Action> {
5650 Box::new(ToggleFocus)
5651 }
5652
5653 fn activation_priority(&self) -> u32 {
5654 2
5655 }
5656}
5657
5658impl PanelHeader for GitPanel {}
5659
5660pub fn panel_editor_container(_window: &mut Window, cx: &mut App) -> Div {
5661 v_flex()
5662 .size_full()
5663 .gap(px(8.))
5664 .p_2()
5665 .bg(cx.theme().colors().editor_background)
5666}
5667
5668pub(crate) fn panel_editor_style(monospace: bool, window: &Window, cx: &App) -> EditorStyle {
5669 let settings = ThemeSettings::get_global(cx);
5670
5671 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
5672
5673 let (font_family, font_fallbacks, font_features, font_weight, line_height) = if monospace {
5674 (
5675 settings.buffer_font.family.clone(),
5676 settings.buffer_font.fallbacks.clone(),
5677 settings.buffer_font.features.clone(),
5678 settings.buffer_font.weight,
5679 font_size * settings.buffer_line_height.value(),
5680 )
5681 } else {
5682 (
5683 settings.ui_font.family.clone(),
5684 settings.ui_font.fallbacks.clone(),
5685 settings.ui_font.features.clone(),
5686 settings.ui_font.weight,
5687 window.line_height(),
5688 )
5689 };
5690
5691 EditorStyle {
5692 background: cx.theme().colors().editor_background,
5693 local_player: cx.theme().players().local(),
5694 text: TextStyle {
5695 color: cx.theme().colors().text,
5696 font_family,
5697 font_fallbacks,
5698 font_features,
5699 font_size: TextSize::Small.rems(cx).into(),
5700 font_weight,
5701 line_height: line_height.into(),
5702 ..Default::default()
5703 },
5704 syntax: cx.theme().syntax().clone(),
5705 ..Default::default()
5706 }
5707}
5708
5709struct GitPanelMessageTooltip {
5710 commit_tooltip: Option<Entity<CommitTooltip>>,
5711}
5712
5713impl GitPanelMessageTooltip {
5714 fn new(
5715 git_panel: Entity<GitPanel>,
5716 sha: SharedString,
5717 repository: Entity<Repository>,
5718 window: &mut Window,
5719 cx: &mut App,
5720 ) -> Entity<Self> {
5721 let remote_url = repository.read(cx).default_remote_url();
5722 cx.new(|cx| {
5723 cx.spawn_in(window, async move |this, cx| {
5724 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5725 (
5726 git_panel.load_commit_details(sha.to_string(), cx),
5727 git_panel.workspace.clone(),
5728 )
5729 });
5730 let details = details.await?;
5731 let provider_registry = cx
5732 .update(|_, app| GitHostingProviderRegistry::default_global(app))
5733 .ok();
5734
5735 let commit_details = crate::commit_tooltip::CommitDetails {
5736 sha: details.sha.clone(),
5737 author_name: details.author_name.clone(),
5738 author_email: details.author_email.clone(),
5739 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5740 message: Some(ParsedCommitMessage::parse(
5741 details.sha.to_string(),
5742 details.message.to_string(),
5743 remote_url.as_deref(),
5744 provider_registry,
5745 )),
5746 };
5747
5748 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5749 this.commit_tooltip = Some(cx.new(move |cx| {
5750 CommitTooltip::new(commit_details, repository, workspace, cx)
5751 }));
5752 cx.notify();
5753 })
5754 })
5755 .detach();
5756
5757 Self {
5758 commit_tooltip: None,
5759 }
5760 })
5761 }
5762}
5763
5764impl Render for GitPanelMessageTooltip {
5765 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5766 if let Some(commit_tooltip) = &self.commit_tooltip {
5767 commit_tooltip.clone().into_any_element()
5768 } else {
5769 gpui::Empty.into_any_element()
5770 }
5771 }
5772}
5773
5774#[derive(IntoElement, RegisterComponent)]
5775pub struct PanelRepoFooter {
5776 active_repository: SharedString,
5777 branch: Option<Branch>,
5778 head_commit: Option<CommitDetails>,
5779
5780 // Getting a GitPanel in previews will be difficult.
5781 //
5782 // For now just take an option here, and we won't bind handlers to buttons in previews.
5783 git_panel: Option<Entity<GitPanel>>,
5784}
5785
5786impl PanelRepoFooter {
5787 pub fn new(
5788 active_repository: SharedString,
5789 branch: Option<Branch>,
5790 head_commit: Option<CommitDetails>,
5791 git_panel: Option<Entity<GitPanel>>,
5792 ) -> Self {
5793 Self {
5794 active_repository,
5795 branch,
5796 head_commit,
5797 git_panel,
5798 }
5799 }
5800
5801 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5802 Self {
5803 active_repository,
5804 branch,
5805 head_commit: None,
5806 git_panel: None,
5807 }
5808 }
5809}
5810
5811impl RenderOnce for PanelRepoFooter {
5812 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5813 let project = self
5814 .git_panel
5815 .as_ref()
5816 .map(|panel| panel.read(cx).project.clone());
5817
5818 let (workspace, repo) = self
5819 .git_panel
5820 .as_ref()
5821 .map(|panel| {
5822 let panel = panel.read(cx);
5823 (panel.workspace.clone(), panel.active_repository.clone())
5824 })
5825 .unzip();
5826
5827 let single_repo = project
5828 .as_ref()
5829 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5830 .unwrap_or(true);
5831
5832 const MAX_BRANCH_LEN: usize = 16;
5833 const MAX_REPO_LEN: usize = 16;
5834 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
5835 const MAX_SHORT_SHA_LEN: usize = 8;
5836 let branch_name = self
5837 .branch
5838 .as_ref()
5839 .map(|branch| branch.name().to_owned())
5840 .or_else(|| {
5841 self.head_commit.as_ref().map(|commit| {
5842 commit
5843 .sha
5844 .chars()
5845 .take(MAX_SHORT_SHA_LEN)
5846 .collect::<String>()
5847 })
5848 })
5849 .unwrap_or_else(|| " (no branch)".to_owned());
5850 let show_separator = self.branch.is_some() || self.head_commit.is_some();
5851
5852 let active_repo_name = self.active_repository.clone();
5853
5854 let branch_actual_len = branch_name.len();
5855 let repo_actual_len = active_repo_name.len();
5856
5857 // ideally, show the whole branch and repo names but
5858 // when we can't, use a budget to allocate space between the two
5859 let (repo_display_len, branch_display_len) =
5860 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
5861 (repo_actual_len, branch_actual_len)
5862 } else if branch_actual_len <= MAX_BRANCH_LEN {
5863 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
5864 (repo_space, branch_actual_len)
5865 } else if repo_actual_len <= MAX_REPO_LEN {
5866 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
5867 (repo_actual_len, branch_space)
5868 } else {
5869 (MAX_REPO_LEN, MAX_BRANCH_LEN)
5870 };
5871
5872 let truncated_repo_name = if repo_actual_len <= repo_display_len {
5873 active_repo_name.to_string()
5874 } else {
5875 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
5876 };
5877
5878 let truncated_branch_name = if branch_actual_len <= branch_display_len {
5879 branch_name
5880 } else {
5881 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
5882 };
5883
5884 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
5885 .size(ButtonSize::None)
5886 .label_size(LabelSize::Small);
5887
5888 let repo_selector = PopoverMenu::new("repository-switcher")
5889 .menu({
5890 let project = project;
5891 move |window, cx| {
5892 let project = project.clone()?;
5893 Some(cx.new(|cx| RepositorySelector::new(project, rems(20.), window, cx)))
5894 }
5895 })
5896 .trigger_with_tooltip(
5897 repo_selector_trigger
5898 .when(single_repo, |this| this.disabled(true).color(Color::Muted))
5899 .truncate(true),
5900 move |_, cx| {
5901 if single_repo {
5902 cx.new(|_| Empty).into()
5903 } else {
5904 Tooltip::simple("Switch Active Repository", cx)
5905 }
5906 },
5907 )
5908 .anchor(Corner::BottomLeft)
5909 .offset(gpui::Point {
5910 x: px(0.0),
5911 y: px(-2.0),
5912 })
5913 .into_any_element();
5914
5915 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
5916 .size(ButtonSize::None)
5917 .label_size(LabelSize::Small)
5918 .truncate(true)
5919 .on_click(|_, window, cx| {
5920 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
5921 });
5922
5923 let branch_selector = PopoverMenu::new("popover-button")
5924 .menu(move |window, cx| {
5925 let workspace = workspace.clone()?;
5926 let repo = repo.clone().flatten();
5927 Some(branch_picker::popover(workspace, false, repo, window, cx))
5928 })
5929 .trigger_with_tooltip(
5930 branch_selector_button,
5931 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
5932 )
5933 .anchor(Corner::BottomLeft)
5934 .offset(gpui::Point {
5935 x: px(0.0),
5936 y: px(-2.0),
5937 });
5938
5939 h_flex()
5940 .h(px(36.))
5941 .w_full()
5942 .px_2()
5943 .justify_between()
5944 .gap_1()
5945 .child(
5946 h_flex()
5947 .flex_1()
5948 .overflow_hidden()
5949 .gap_px()
5950 .child(
5951 Icon::new(IconName::GitBranchAlt)
5952 .size(IconSize::Small)
5953 .color(if single_repo {
5954 Color::Disabled
5955 } else {
5956 Color::Muted
5957 }),
5958 )
5959 .child(repo_selector)
5960 .when(show_separator, |this| {
5961 this.child(
5962 div()
5963 .text_sm()
5964 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
5965 .child("/"),
5966 )
5967 })
5968 .child(branch_selector),
5969 )
5970 .children(if let Some(git_panel) = self.git_panel {
5971 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
5972 } else {
5973 None
5974 })
5975 }
5976}
5977
5978impl Component for PanelRepoFooter {
5979 fn scope() -> ComponentScope {
5980 ComponentScope::VersionControl
5981 }
5982
5983 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
5984 let unknown_upstream = None;
5985 let no_remote_upstream = Some(UpstreamTracking::Gone);
5986 let ahead_of_upstream = Some(
5987 UpstreamTrackingStatus {
5988 ahead: 2,
5989 behind: 0,
5990 }
5991 .into(),
5992 );
5993 let behind_upstream = Some(
5994 UpstreamTrackingStatus {
5995 ahead: 0,
5996 behind: 2,
5997 }
5998 .into(),
5999 );
6000 let ahead_and_behind_upstream = Some(
6001 UpstreamTrackingStatus {
6002 ahead: 3,
6003 behind: 1,
6004 }
6005 .into(),
6006 );
6007
6008 let not_ahead_or_behind_upstream = Some(
6009 UpstreamTrackingStatus {
6010 ahead: 0,
6011 behind: 0,
6012 }
6013 .into(),
6014 );
6015
6016 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
6017 Branch {
6018 is_head: true,
6019 ref_name: "some-branch".into(),
6020 upstream: upstream.map(|tracking| Upstream {
6021 ref_name: "origin/some-branch".into(),
6022 tracking,
6023 }),
6024 most_recent_commit: Some(CommitSummary {
6025 sha: "abc123".into(),
6026 subject: "Modify stuff".into(),
6027 commit_timestamp: 1710932954,
6028 author_name: "John Doe".into(),
6029 has_parent: true,
6030 }),
6031 }
6032 }
6033
6034 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
6035 Branch {
6036 is_head: true,
6037 ref_name: branch_name.to_string().into(),
6038 upstream: upstream.map(|tracking| Upstream {
6039 ref_name: format!("zed/{}", branch_name).into(),
6040 tracking,
6041 }),
6042 most_recent_commit: Some(CommitSummary {
6043 sha: "abc123".into(),
6044 subject: "Modify stuff".into(),
6045 commit_timestamp: 1710932954,
6046 author_name: "John Doe".into(),
6047 has_parent: true,
6048 }),
6049 }
6050 }
6051
6052 fn active_repository(id: usize) -> SharedString {
6053 format!("repo-{}", id).into()
6054 }
6055
6056 let example_width = px(340.);
6057 Some(
6058 v_flex()
6059 .gap_6()
6060 .w_full()
6061 .flex_none()
6062 .children(vec![
6063 example_group_with_title(
6064 "Action Button States",
6065 vec![
6066 single_example(
6067 "No Branch",
6068 div()
6069 .w(example_width)
6070 .overflow_hidden()
6071 .child(PanelRepoFooter::new_preview(active_repository(1), None))
6072 .into_any_element(),
6073 ),
6074 single_example(
6075 "Remote status unknown",
6076 div()
6077 .w(example_width)
6078 .overflow_hidden()
6079 .child(PanelRepoFooter::new_preview(
6080 active_repository(2),
6081 Some(branch(unknown_upstream)),
6082 ))
6083 .into_any_element(),
6084 ),
6085 single_example(
6086 "No Remote Upstream",
6087 div()
6088 .w(example_width)
6089 .overflow_hidden()
6090 .child(PanelRepoFooter::new_preview(
6091 active_repository(3),
6092 Some(branch(no_remote_upstream)),
6093 ))
6094 .into_any_element(),
6095 ),
6096 single_example(
6097 "Not Ahead or Behind",
6098 div()
6099 .w(example_width)
6100 .overflow_hidden()
6101 .child(PanelRepoFooter::new_preview(
6102 active_repository(4),
6103 Some(branch(not_ahead_or_behind_upstream)),
6104 ))
6105 .into_any_element(),
6106 ),
6107 single_example(
6108 "Behind remote",
6109 div()
6110 .w(example_width)
6111 .overflow_hidden()
6112 .child(PanelRepoFooter::new_preview(
6113 active_repository(5),
6114 Some(branch(behind_upstream)),
6115 ))
6116 .into_any_element(),
6117 ),
6118 single_example(
6119 "Ahead of remote",
6120 div()
6121 .w(example_width)
6122 .overflow_hidden()
6123 .child(PanelRepoFooter::new_preview(
6124 active_repository(6),
6125 Some(branch(ahead_of_upstream)),
6126 ))
6127 .into_any_element(),
6128 ),
6129 single_example(
6130 "Ahead and behind remote",
6131 div()
6132 .w(example_width)
6133 .overflow_hidden()
6134 .child(PanelRepoFooter::new_preview(
6135 active_repository(7),
6136 Some(branch(ahead_and_behind_upstream)),
6137 ))
6138 .into_any_element(),
6139 ),
6140 ],
6141 )
6142 .grow()
6143 .vertical(),
6144 ])
6145 .children(vec![
6146 example_group_with_title(
6147 "Labels",
6148 vec![
6149 single_example(
6150 "Short Branch & Repo",
6151 div()
6152 .w(example_width)
6153 .overflow_hidden()
6154 .child(PanelRepoFooter::new_preview(
6155 SharedString::from("zed"),
6156 Some(custom("main", behind_upstream)),
6157 ))
6158 .into_any_element(),
6159 ),
6160 single_example(
6161 "Long Branch",
6162 div()
6163 .w(example_width)
6164 .overflow_hidden()
6165 .child(PanelRepoFooter::new_preview(
6166 SharedString::from("zed"),
6167 Some(custom(
6168 "redesign-and-update-git-ui-list-entry-style",
6169 behind_upstream,
6170 )),
6171 ))
6172 .into_any_element(),
6173 ),
6174 single_example(
6175 "Long Repo",
6176 div()
6177 .w(example_width)
6178 .overflow_hidden()
6179 .child(PanelRepoFooter::new_preview(
6180 SharedString::from("zed-industries-community-examples"),
6181 Some(custom("gpui", ahead_of_upstream)),
6182 ))
6183 .into_any_element(),
6184 ),
6185 single_example(
6186 "Long Repo & Branch",
6187 div()
6188 .w(example_width)
6189 .overflow_hidden()
6190 .child(PanelRepoFooter::new_preview(
6191 SharedString::from("zed-industries-community-examples"),
6192 Some(custom(
6193 "redesign-and-update-git-ui-list-entry-style",
6194 behind_upstream,
6195 )),
6196 ))
6197 .into_any_element(),
6198 ),
6199 single_example(
6200 "Uppercase Repo",
6201 div()
6202 .w(example_width)
6203 .overflow_hidden()
6204 .child(PanelRepoFooter::new_preview(
6205 SharedString::from("LICENSES"),
6206 Some(custom("main", ahead_of_upstream)),
6207 ))
6208 .into_any_element(),
6209 ),
6210 single_example(
6211 "Uppercase Branch",
6212 div()
6213 .w(example_width)
6214 .overflow_hidden()
6215 .child(PanelRepoFooter::new_preview(
6216 SharedString::from("zed"),
6217 Some(custom("update-README", behind_upstream)),
6218 ))
6219 .into_any_element(),
6220 ),
6221 ],
6222 )
6223 .grow()
6224 .vertical(),
6225 ])
6226 .into_any_element(),
6227 )
6228 }
6229}
6230
6231fn open_output(
6232 operation: impl Into<SharedString>,
6233 workspace: &mut Workspace,
6234 output: &str,
6235 window: &mut Window,
6236 cx: &mut Context<Workspace>,
6237) {
6238 let operation = operation.into();
6239 let buffer = cx.new(|cx| Buffer::local(output, cx));
6240 buffer.update(cx, |buffer, cx| {
6241 buffer.set_capability(language::Capability::ReadOnly, cx);
6242 });
6243 let editor = cx.new(|cx| {
6244 let mut editor = Editor::for_buffer(buffer, None, window, cx);
6245 editor.buffer().update(cx, |buffer, cx| {
6246 buffer.set_title(format!("Output from git {operation}"), cx);
6247 });
6248 editor.set_read_only(true);
6249 editor
6250 });
6251
6252 workspace.add_item_to_center(Box::new(editor), window, cx);
6253}
6254
6255pub(crate) fn show_error_toast(
6256 workspace: Entity<Workspace>,
6257 action: impl Into<SharedString>,
6258 e: anyhow::Error,
6259 cx: &mut App,
6260) {
6261 let action = action.into();
6262 let message = e.to_string().trim().to_string();
6263 if message
6264 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6265 .next()
6266 .is_some()
6267 { // Hide the cancelled by user message
6268 } else {
6269 workspace.update(cx, |workspace, cx| {
6270 let workspace_weak = cx.weak_entity();
6271 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6272 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6273 .action("View Log", move |window, cx| {
6274 let message = message.clone();
6275 let action = action.clone();
6276 workspace_weak
6277 .update(cx, move |workspace, cx| {
6278 open_output(action, workspace, &message, window, cx)
6279 })
6280 .ok();
6281 })
6282 });
6283 workspace.toggle_status_toast(toast, cx)
6284 });
6285 }
6286}
6287
6288#[cfg(test)]
6289mod tests {
6290 use git::{
6291 repository::repo_path,
6292 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6293 };
6294 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
6295 use indoc::indoc;
6296 use project::FakeFs;
6297 use serde_json::json;
6298 use settings::SettingsStore;
6299 use theme::LoadThemes;
6300 use util::path;
6301 use util::rel_path::rel_path;
6302
6303 use workspace::MultiWorkspace;
6304
6305 use super::*;
6306
6307 fn init_test(cx: &mut gpui::TestAppContext) {
6308 zlog::init_test();
6309
6310 cx.update(|cx| {
6311 let settings_store = SettingsStore::test(cx);
6312 cx.set_global(settings_store);
6313 theme::init(LoadThemes::JustBase, cx);
6314 editor::init(cx);
6315 crate::init(cx);
6316 });
6317 }
6318
6319 #[gpui::test]
6320 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6321 init_test(cx);
6322 let fs = FakeFs::new(cx.background_executor.clone());
6323 fs.insert_tree(
6324 "/root",
6325 json!({
6326 "zed": {
6327 ".git": {},
6328 "crates": {
6329 "gpui": {
6330 "gpui.rs": "fn main() {}"
6331 },
6332 "util": {
6333 "util.rs": "fn do_it() {}"
6334 }
6335 }
6336 },
6337 }),
6338 )
6339 .await;
6340
6341 fs.set_status_for_repo(
6342 Path::new(path!("/root/zed/.git")),
6343 &[
6344 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6345 ("crates/util/util.rs", StatusCode::Modified.worktree()),
6346 ],
6347 );
6348
6349 let project =
6350 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6351 let window_handle =
6352 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6353 let workspace = window_handle
6354 .read_with(cx, |mw, _| mw.workspace().clone())
6355 .unwrap();
6356 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6357
6358 cx.read(|cx| {
6359 project
6360 .read(cx)
6361 .worktrees(cx)
6362 .next()
6363 .unwrap()
6364 .read(cx)
6365 .as_local()
6366 .unwrap()
6367 .scan_complete()
6368 })
6369 .await;
6370
6371 cx.executor().run_until_parked();
6372
6373 let panel = workspace.update_in(cx, GitPanel::new);
6374
6375 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6376 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6377 });
6378 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6379 handle.await;
6380
6381 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6382 pretty_assertions::assert_eq!(
6383 entries,
6384 [
6385 GitListEntry::Header(GitHeaderEntry {
6386 header: Section::Tracked
6387 }),
6388 GitListEntry::Status(GitStatusEntry {
6389 repo_path: repo_path("crates/gpui/gpui.rs"),
6390 status: StatusCode::Modified.worktree(),
6391 staging: StageStatus::Unstaged,
6392 }),
6393 GitListEntry::Status(GitStatusEntry {
6394 repo_path: repo_path("crates/util/util.rs"),
6395 status: StatusCode::Modified.worktree(),
6396 staging: StageStatus::Unstaged,
6397 },),
6398 ],
6399 );
6400
6401 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6402 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6403 });
6404 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6405 handle.await;
6406 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6407 pretty_assertions::assert_eq!(
6408 entries,
6409 [
6410 GitListEntry::Header(GitHeaderEntry {
6411 header: Section::Tracked
6412 }),
6413 GitListEntry::Status(GitStatusEntry {
6414 repo_path: repo_path("crates/gpui/gpui.rs"),
6415 status: StatusCode::Modified.worktree(),
6416 staging: StageStatus::Unstaged,
6417 }),
6418 GitListEntry::Status(GitStatusEntry {
6419 repo_path: repo_path("crates/util/util.rs"),
6420 status: StatusCode::Modified.worktree(),
6421 staging: StageStatus::Unstaged,
6422 },),
6423 ],
6424 );
6425 }
6426
6427 #[gpui::test]
6428 async fn test_bulk_staging(cx: &mut TestAppContext) {
6429 use GitListEntry::*;
6430
6431 init_test(cx);
6432 let fs = FakeFs::new(cx.background_executor.clone());
6433 fs.insert_tree(
6434 "/root",
6435 json!({
6436 "project": {
6437 ".git": {},
6438 "src": {
6439 "main.rs": "fn main() {}",
6440 "lib.rs": "pub fn hello() {}",
6441 "utils.rs": "pub fn util() {}"
6442 },
6443 "tests": {
6444 "test.rs": "fn test() {}"
6445 },
6446 "new_file.txt": "new content",
6447 "another_new.rs": "// new file",
6448 "conflict.txt": "conflicted content"
6449 }
6450 }),
6451 )
6452 .await;
6453
6454 fs.set_status_for_repo(
6455 Path::new(path!("/root/project/.git")),
6456 &[
6457 ("src/main.rs", StatusCode::Modified.worktree()),
6458 ("src/lib.rs", StatusCode::Modified.worktree()),
6459 ("tests/test.rs", StatusCode::Modified.worktree()),
6460 ("new_file.txt", FileStatus::Untracked),
6461 ("another_new.rs", FileStatus::Untracked),
6462 ("src/utils.rs", FileStatus::Untracked),
6463 (
6464 "conflict.txt",
6465 UnmergedStatus {
6466 first_head: UnmergedStatusCode::Updated,
6467 second_head: UnmergedStatusCode::Updated,
6468 }
6469 .into(),
6470 ),
6471 ],
6472 );
6473
6474 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6475 let window_handle =
6476 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6477 let workspace = window_handle
6478 .read_with(cx, |mw, _| mw.workspace().clone())
6479 .unwrap();
6480 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6481
6482 cx.read(|cx| {
6483 project
6484 .read(cx)
6485 .worktrees(cx)
6486 .next()
6487 .unwrap()
6488 .read(cx)
6489 .as_local()
6490 .unwrap()
6491 .scan_complete()
6492 })
6493 .await;
6494
6495 cx.executor().run_until_parked();
6496
6497 let panel = workspace.update_in(cx, GitPanel::new);
6498
6499 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6500 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6501 });
6502 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6503 handle.await;
6504
6505 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6506 #[rustfmt::skip]
6507 pretty_assertions::assert_matches!(
6508 entries.as_slice(),
6509 &[
6510 Header(GitHeaderEntry { header: Section::Conflict }),
6511 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6512 Header(GitHeaderEntry { header: Section::Tracked }),
6513 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6514 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6515 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6516 Header(GitHeaderEntry { header: Section::New }),
6517 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6518 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6519 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6520 ],
6521 );
6522
6523 let second_status_entry = entries[3].clone();
6524 panel.update_in(cx, |panel, window, cx| {
6525 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6526 });
6527
6528 panel.update_in(cx, |panel, window, cx| {
6529 panel.selected_entry = Some(7);
6530 panel.stage_range(&git::StageRange, window, cx);
6531 });
6532
6533 cx.read(|cx| {
6534 project
6535 .read(cx)
6536 .worktrees(cx)
6537 .next()
6538 .unwrap()
6539 .read(cx)
6540 .as_local()
6541 .unwrap()
6542 .scan_complete()
6543 })
6544 .await;
6545
6546 cx.executor().run_until_parked();
6547
6548 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6549 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6550 });
6551 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6552 handle.await;
6553
6554 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6555 #[rustfmt::skip]
6556 pretty_assertions::assert_matches!(
6557 entries.as_slice(),
6558 &[
6559 Header(GitHeaderEntry { header: Section::Conflict }),
6560 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6561 Header(GitHeaderEntry { header: Section::Tracked }),
6562 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6563 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6564 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6565 Header(GitHeaderEntry { header: Section::New }),
6566 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6567 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6568 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6569 ],
6570 );
6571
6572 let third_status_entry = entries[4].clone();
6573 panel.update_in(cx, |panel, window, cx| {
6574 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6575 });
6576
6577 panel.update_in(cx, |panel, window, cx| {
6578 panel.selected_entry = Some(9);
6579 panel.stage_range(&git::StageRange, window, cx);
6580 });
6581
6582 cx.read(|cx| {
6583 project
6584 .read(cx)
6585 .worktrees(cx)
6586 .next()
6587 .unwrap()
6588 .read(cx)
6589 .as_local()
6590 .unwrap()
6591 .scan_complete()
6592 })
6593 .await;
6594
6595 cx.executor().run_until_parked();
6596
6597 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6598 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6599 });
6600 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6601 handle.await;
6602
6603 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6604 #[rustfmt::skip]
6605 pretty_assertions::assert_matches!(
6606 entries.as_slice(),
6607 &[
6608 Header(GitHeaderEntry { header: Section::Conflict }),
6609 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6610 Header(GitHeaderEntry { header: Section::Tracked }),
6611 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6612 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6613 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6614 Header(GitHeaderEntry { header: Section::New }),
6615 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6616 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6617 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6618 ],
6619 );
6620 }
6621
6622 #[gpui::test]
6623 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6624 use GitListEntry::*;
6625
6626 init_test(cx);
6627 let fs = FakeFs::new(cx.background_executor.clone());
6628 fs.insert_tree(
6629 "/root",
6630 json!({
6631 "project": {
6632 ".git": {},
6633 "src": {
6634 "main.rs": "fn main() {}",
6635 "lib.rs": "pub fn hello() {}",
6636 "utils.rs": "pub fn util() {}"
6637 },
6638 "tests": {
6639 "test.rs": "fn test() {}"
6640 },
6641 "new_file.txt": "new content",
6642 "another_new.rs": "// new file",
6643 "conflict.txt": "conflicted content"
6644 }
6645 }),
6646 )
6647 .await;
6648
6649 fs.set_status_for_repo(
6650 Path::new(path!("/root/project/.git")),
6651 &[
6652 ("src/main.rs", StatusCode::Modified.worktree()),
6653 ("src/lib.rs", StatusCode::Modified.worktree()),
6654 ("tests/test.rs", StatusCode::Modified.worktree()),
6655 ("new_file.txt", FileStatus::Untracked),
6656 ("another_new.rs", FileStatus::Untracked),
6657 ("src/utils.rs", FileStatus::Untracked),
6658 (
6659 "conflict.txt",
6660 UnmergedStatus {
6661 first_head: UnmergedStatusCode::Updated,
6662 second_head: UnmergedStatusCode::Updated,
6663 }
6664 .into(),
6665 ),
6666 ],
6667 );
6668
6669 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6670 let window_handle =
6671 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6672 let workspace = window_handle
6673 .read_with(cx, |mw, _| mw.workspace().clone())
6674 .unwrap();
6675 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6676
6677 cx.read(|cx| {
6678 project
6679 .read(cx)
6680 .worktrees(cx)
6681 .next()
6682 .unwrap()
6683 .read(cx)
6684 .as_local()
6685 .unwrap()
6686 .scan_complete()
6687 })
6688 .await;
6689
6690 cx.executor().run_until_parked();
6691
6692 let panel = workspace.update_in(cx, GitPanel::new);
6693
6694 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6695 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6696 });
6697 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6698 handle.await;
6699
6700 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6701 #[rustfmt::skip]
6702 pretty_assertions::assert_matches!(
6703 entries.as_slice(),
6704 &[
6705 Header(GitHeaderEntry { header: Section::Conflict }),
6706 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6707 Header(GitHeaderEntry { header: Section::Tracked }),
6708 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6709 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6710 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6711 Header(GitHeaderEntry { header: Section::New }),
6712 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6713 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6714 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6715 ],
6716 );
6717
6718 assert_entry_paths(
6719 &entries,
6720 &[
6721 None,
6722 Some("conflict.txt"),
6723 None,
6724 Some("src/lib.rs"),
6725 Some("src/main.rs"),
6726 Some("tests/test.rs"),
6727 None,
6728 Some("another_new.rs"),
6729 Some("new_file.txt"),
6730 Some("src/utils.rs"),
6731 ],
6732 );
6733
6734 let second_status_entry = entries[3].clone();
6735 panel.update_in(cx, |panel, window, cx| {
6736 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6737 });
6738
6739 cx.update(|_window, cx| {
6740 SettingsStore::update_global(cx, |store, cx| {
6741 store.update_user_settings(cx, |settings| {
6742 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6743 })
6744 });
6745 });
6746
6747 panel.update_in(cx, |panel, window, cx| {
6748 panel.selected_entry = Some(7);
6749 panel.stage_range(&git::StageRange, window, cx);
6750 });
6751
6752 cx.read(|cx| {
6753 project
6754 .read(cx)
6755 .worktrees(cx)
6756 .next()
6757 .unwrap()
6758 .read(cx)
6759 .as_local()
6760 .unwrap()
6761 .scan_complete()
6762 })
6763 .await;
6764
6765 cx.executor().run_until_parked();
6766
6767 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6768 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6769 });
6770 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6771 handle.await;
6772
6773 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6774 #[rustfmt::skip]
6775 pretty_assertions::assert_matches!(
6776 entries.as_slice(),
6777 &[
6778 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6779 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6780 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6781 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6782 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6783 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6784 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6785 ],
6786 );
6787
6788 assert_entry_paths(
6789 &entries,
6790 &[
6791 Some("another_new.rs"),
6792 Some("conflict.txt"),
6793 Some("new_file.txt"),
6794 Some("src/lib.rs"),
6795 Some("src/main.rs"),
6796 Some("src/utils.rs"),
6797 Some("tests/test.rs"),
6798 ],
6799 );
6800
6801 let third_status_entry = entries[4].clone();
6802 panel.update_in(cx, |panel, window, cx| {
6803 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6804 });
6805
6806 panel.update_in(cx, |panel, window, cx| {
6807 panel.selected_entry = Some(9);
6808 panel.stage_range(&git::StageRange, window, cx);
6809 });
6810
6811 cx.read(|cx| {
6812 project
6813 .read(cx)
6814 .worktrees(cx)
6815 .next()
6816 .unwrap()
6817 .read(cx)
6818 .as_local()
6819 .unwrap()
6820 .scan_complete()
6821 })
6822 .await;
6823
6824 cx.executor().run_until_parked();
6825
6826 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6827 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6828 });
6829 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6830 handle.await;
6831
6832 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6833 #[rustfmt::skip]
6834 pretty_assertions::assert_matches!(
6835 entries.as_slice(),
6836 &[
6837 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6838 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6839 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6840 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6841 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6842 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6843 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6844 ],
6845 );
6846
6847 assert_entry_paths(
6848 &entries,
6849 &[
6850 Some("another_new.rs"),
6851 Some("conflict.txt"),
6852 Some("new_file.txt"),
6853 Some("src/lib.rs"),
6854 Some("src/main.rs"),
6855 Some("src/utils.rs"),
6856 Some("tests/test.rs"),
6857 ],
6858 );
6859 }
6860
6861 #[gpui::test]
6862 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
6863 init_test(cx);
6864 let fs = FakeFs::new(cx.background_executor.clone());
6865 fs.insert_tree(
6866 "/root",
6867 json!({
6868 "project": {
6869 ".git": {},
6870 "src": {
6871 "main.rs": "fn main() {}"
6872 }
6873 }
6874 }),
6875 )
6876 .await;
6877
6878 fs.set_status_for_repo(
6879 Path::new(path!("/root/project/.git")),
6880 &[("src/main.rs", StatusCode::Modified.worktree())],
6881 );
6882
6883 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6884 let window_handle =
6885 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6886 let workspace = window_handle
6887 .read_with(cx, |mw, _| mw.workspace().clone())
6888 .unwrap();
6889 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6890
6891 let panel = workspace.update_in(cx, GitPanel::new);
6892
6893 // Test: User has commit message, enables amend (saves message), then disables (restores message)
6894 panel.update(cx, |panel, cx| {
6895 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6896 let start = buffer.anchor_before(0);
6897 let end = buffer.anchor_after(buffer.len());
6898 buffer.edit([(start..end, "Initial commit message")], None, cx);
6899 });
6900
6901 panel.set_amend_pending(true, cx);
6902 assert!(panel.original_commit_message.is_some());
6903
6904 panel.set_amend_pending(false, cx);
6905 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6906 assert_eq!(current_message, "Initial commit message");
6907 assert!(panel.original_commit_message.is_none());
6908 });
6909
6910 // Test: User has empty commit message, enables amend, then disables (clears message)
6911 panel.update(cx, |panel, cx| {
6912 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6913 let start = buffer.anchor_before(0);
6914 let end = buffer.anchor_after(buffer.len());
6915 buffer.edit([(start..end, "")], None, cx);
6916 });
6917
6918 panel.set_amend_pending(true, cx);
6919 assert!(panel.original_commit_message.is_none());
6920
6921 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6922 let start = buffer.anchor_before(0);
6923 let end = buffer.anchor_after(buffer.len());
6924 buffer.edit([(start..end, "Previous commit message")], None, cx);
6925 });
6926
6927 panel.set_amend_pending(false, cx);
6928 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6929 assert_eq!(current_message, "");
6930 });
6931 }
6932
6933 #[gpui::test]
6934 async fn test_amend(cx: &mut TestAppContext) {
6935 init_test(cx);
6936 let fs = FakeFs::new(cx.background_executor.clone());
6937 fs.insert_tree(
6938 "/root",
6939 json!({
6940 "project": {
6941 ".git": {},
6942 "src": {
6943 "main.rs": "fn main() {}"
6944 }
6945 }
6946 }),
6947 )
6948 .await;
6949
6950 fs.set_status_for_repo(
6951 Path::new(path!("/root/project/.git")),
6952 &[("src/main.rs", StatusCode::Modified.worktree())],
6953 );
6954
6955 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6956 let window_handle =
6957 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6958 let workspace = window_handle
6959 .read_with(cx, |mw, _| mw.workspace().clone())
6960 .unwrap();
6961 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
6962
6963 // Wait for the project scanning to finish so that `head_commit(cx)` is
6964 // actually set, otherwise no head commit would be available from which
6965 // to fetch the latest commit message from.
6966 cx.executor().run_until_parked();
6967
6968 let panel = workspace.update_in(cx, GitPanel::new);
6969 panel.read_with(cx, |panel, cx| {
6970 assert!(panel.active_repository.is_some());
6971 assert!(panel.head_commit(cx).is_some());
6972 });
6973
6974 panel.update_in(cx, |panel, window, cx| {
6975 // Update the commit editor's message to ensure that its contents
6976 // are later restored, after amending is finished.
6977 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6978 buffer.set_text("refactor: update main.rs", cx);
6979 });
6980
6981 // Start amending the previous commit.
6982 panel.focus_editor(&Default::default(), window, cx);
6983 panel.on_amend(&Amend, window, cx);
6984 });
6985
6986 // Since `GitPanel.amend` attempts to fetch the latest commit message in
6987 // a background task, we need to wait for it to complete before being
6988 // able to assert that the commit message editor's state has been
6989 // updated.
6990 cx.run_until_parked();
6991
6992 panel.update_in(cx, |panel, window, cx| {
6993 assert_eq!(
6994 panel.commit_message_buffer(cx).read(cx).text(),
6995 "initial commit"
6996 );
6997 assert_eq!(
6998 panel.original_commit_message,
6999 Some("refactor: update main.rs".to_string())
7000 );
7001
7002 // Finish amending the previous commit.
7003 panel.focus_editor(&Default::default(), window, cx);
7004 panel.on_amend(&Amend, window, cx);
7005 });
7006
7007 // Since the actual commit logic is run in a background task, we need to
7008 // await its completion to actually ensure that the commit message
7009 // editor's contents are set to the original message and haven't been
7010 // cleared.
7011 cx.run_until_parked();
7012
7013 panel.update_in(cx, |panel, _window, cx| {
7014 // After amending, the commit editor's message should be restored to
7015 // the original message.
7016 assert_eq!(
7017 panel.commit_message_buffer(cx).read(cx).text(),
7018 "refactor: update main.rs"
7019 );
7020 assert!(panel.original_commit_message.is_none());
7021 });
7022 }
7023
7024 #[gpui::test]
7025 async fn test_open_diff(cx: &mut TestAppContext) {
7026 init_test(cx);
7027
7028 let fs = FakeFs::new(cx.background_executor.clone());
7029 fs.insert_tree(
7030 path!("/project"),
7031 json!({
7032 ".git": {},
7033 "tracked": "tracked\n",
7034 "untracked": "\n",
7035 }),
7036 )
7037 .await;
7038
7039 fs.set_head_and_index_for_repo(
7040 path!("/project/.git").as_ref(),
7041 &[("tracked", "old tracked\n".into())],
7042 );
7043
7044 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7045 let window_handle =
7046 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7047 let workspace = window_handle
7048 .read_with(cx, |mw, _| mw.workspace().clone())
7049 .unwrap();
7050 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7051 let panel = workspace.update_in(cx, GitPanel::new);
7052
7053 // Enable the `sort_by_path` setting and wait for entries to be updated,
7054 // as there should no longer be separators between Tracked and Untracked
7055 // files.
7056 cx.update(|_window, cx| {
7057 SettingsStore::update_global(cx, |store, cx| {
7058 store.update_user_settings(cx, |settings| {
7059 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
7060 })
7061 });
7062 });
7063
7064 cx.update_window_entity(&panel, |panel, _, _| {
7065 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7066 })
7067 .await;
7068
7069 // Confirm that `Open Diff` still works for the untracked file, updating
7070 // the Project Diff's active path.
7071 panel.update_in(cx, |panel, window, cx| {
7072 panel.selected_entry = Some(1);
7073 panel.open_diff(&menu::Confirm, window, cx);
7074 });
7075 cx.run_until_parked();
7076
7077 workspace.update_in(cx, |workspace, _window, cx| {
7078 let active_path = workspace
7079 .item_of_type::<ProjectDiff>(cx)
7080 .expect("ProjectDiff should exist")
7081 .read(cx)
7082 .active_path(cx)
7083 .expect("active_path should exist");
7084
7085 assert_eq!(active_path.path, rel_path("untracked").into_arc());
7086 });
7087 }
7088
7089 #[gpui::test]
7090 async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
7091 cx: &mut TestAppContext,
7092 ) {
7093 init_test(cx);
7094
7095 let fs = FakeFs::new(cx.background_executor.clone());
7096 fs.insert_tree(
7097 path!("/project"),
7098 json!({
7099 ".git": {},
7100 "src": {
7101 "a": {
7102 "foo.rs": "fn foo() {}",
7103 },
7104 "b": {
7105 "bar.rs": "fn bar() {}",
7106 },
7107 },
7108 }),
7109 )
7110 .await;
7111
7112 fs.set_status_for_repo(
7113 path!("/project/.git").as_ref(),
7114 &[
7115 ("src/a/foo.rs", StatusCode::Modified.worktree()),
7116 ("src/b/bar.rs", StatusCode::Modified.worktree()),
7117 ],
7118 );
7119
7120 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7121 let window_handle =
7122 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7123 let workspace = window_handle
7124 .read_with(cx, |mw, _| mw.workspace().clone())
7125 .unwrap();
7126 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7127
7128 cx.read(|cx| {
7129 project
7130 .read(cx)
7131 .worktrees(cx)
7132 .next()
7133 .unwrap()
7134 .read(cx)
7135 .as_local()
7136 .unwrap()
7137 .scan_complete()
7138 })
7139 .await;
7140
7141 cx.executor().run_until_parked();
7142
7143 cx.update(|_window, cx| {
7144 SettingsStore::update_global(cx, |store, cx| {
7145 store.update_user_settings(cx, |settings| {
7146 settings.git_panel.get_or_insert_default().tree_view = Some(true);
7147 })
7148 });
7149 });
7150
7151 let panel = workspace.update_in(cx, GitPanel::new);
7152
7153 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7154 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7155 });
7156 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7157 handle.await;
7158
7159 let src_key = panel.read_with(cx, |panel, _| {
7160 panel
7161 .entries
7162 .iter()
7163 .find_map(|entry| match entry {
7164 GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7165 Some(dir.key.clone())
7166 }
7167 _ => None,
7168 })
7169 .expect("src directory should exist in tree view")
7170 });
7171
7172 panel.update_in(cx, |panel, window, cx| {
7173 panel.toggle_directory(&src_key, window, cx);
7174 });
7175
7176 panel.read_with(cx, |panel, _| {
7177 let state = panel
7178 .view_mode
7179 .tree_state()
7180 .expect("tree view state should exist");
7181 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7182 });
7183
7184 let worktree_id =
7185 cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7186 let project_path = ProjectPath {
7187 worktree_id,
7188 path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7189 };
7190
7191 panel.update_in(cx, |panel, window, cx| {
7192 panel.select_entry_by_path(project_path, window, cx);
7193 });
7194
7195 panel.read_with(cx, |panel, _| {
7196 let state = panel
7197 .view_mode
7198 .tree_state()
7199 .expect("tree view state should exist");
7200 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7201
7202 let selected_ix = panel.selected_entry.expect("selection should be set");
7203 assert!(state.logical_indices.contains(&selected_ix));
7204
7205 let selected_entry = panel
7206 .entries
7207 .get(selected_ix)
7208 .and_then(|entry| entry.status_entry())
7209 .expect("selected entry should be a status entry");
7210 assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7211 });
7212 }
7213
7214 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7215 assert_eq!(entries.len(), expected_paths.len());
7216 for (entry, expected_path) in entries.iter().zip(expected_paths) {
7217 assert_eq!(
7218 entry.status_entry().map(|status| status
7219 .repo_path
7220 .as_ref()
7221 .as_std_path()
7222 .to_string_lossy()
7223 .to_string()),
7224 expected_path.map(|s| s.to_string())
7225 );
7226 }
7227 }
7228
7229 #[test]
7230 fn test_compress_diff_no_truncation() {
7231 let diff = indoc! {"
7232 --- a/file.txt
7233 +++ b/file.txt
7234 @@ -1,2 +1,2 @@
7235 -old
7236 +new
7237 "};
7238 let result = GitPanel::compress_commit_diff(diff, 1000);
7239 assert_eq!(result, diff);
7240 }
7241
7242 #[test]
7243 fn test_compress_diff_truncate_long_lines() {
7244 let long_line = "🦀".repeat(300);
7245 let diff = indoc::formatdoc! {"
7246 --- a/file.txt
7247 +++ b/file.txt
7248 @@ -1,2 +1,3 @@
7249 context
7250 +{}
7251 more context
7252 ", long_line};
7253 let result = GitPanel::compress_commit_diff(&diff, 100);
7254 assert!(result.contains("...[truncated]"));
7255 assert!(result.len() < diff.len());
7256 }
7257
7258 #[test]
7259 fn test_compress_diff_truncate_hunks() {
7260 let diff = indoc! {"
7261 --- a/file.txt
7262 +++ b/file.txt
7263 @@ -1,2 +1,2 @@
7264 context
7265 -old1
7266 +new1
7267 @@ -5,2 +5,2 @@
7268 context 2
7269 -old2
7270 +new2
7271 @@ -10,2 +10,2 @@
7272 context 3
7273 -old3
7274 +new3
7275 "};
7276 let result = GitPanel::compress_commit_diff(diff, 100);
7277 let expected = indoc! {"
7278 --- a/file.txt
7279 +++ b/file.txt
7280 @@ -1,2 +1,2 @@
7281 context
7282 -old1
7283 +new1
7284 [...skipped 2 hunks...]
7285 "};
7286 assert_eq!(result, expected);
7287 }
7288
7289 #[gpui::test]
7290 async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7291 init_test(cx);
7292
7293 let fs = FakeFs::new(cx.background_executor.clone());
7294 fs.insert_tree(
7295 path!("/project"),
7296 json!({
7297 ".git": {},
7298 "tracked": "tracked\n",
7299 "untracked": "\n",
7300 }),
7301 )
7302 .await;
7303
7304 fs.set_head_and_index_for_repo(
7305 path!("/project/.git").as_ref(),
7306 &[("tracked", "old tracked\n".into())],
7307 );
7308
7309 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7310 let window_handle =
7311 cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
7312 let workspace = window_handle
7313 .read_with(cx, |mw, _| mw.workspace().clone())
7314 .unwrap();
7315 let cx = &mut VisualTestContext::from_window(window_handle.into(), cx);
7316 let panel = workspace.update_in(cx, GitPanel::new);
7317
7318 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7319 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7320 });
7321 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7322 handle.await;
7323
7324 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7325
7326 // GitPanel
7327 // - Tracked:
7328 // - [] tracked
7329 // - Untracked
7330 // - [] untracked
7331 //
7332 // The commit message should now read:
7333 // "Update tracked"
7334 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7335 assert_eq!(message, Some("Update tracked".to_string()));
7336
7337 let first_status_entry = entries[1].clone();
7338 panel.update_in(cx, |panel, window, cx| {
7339 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7340 });
7341
7342 cx.read(|cx| {
7343 project
7344 .read(cx)
7345 .worktrees(cx)
7346 .next()
7347 .unwrap()
7348 .read(cx)
7349 .as_local()
7350 .unwrap()
7351 .scan_complete()
7352 })
7353 .await;
7354
7355 cx.executor().run_until_parked();
7356
7357 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7358 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7359 });
7360 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7361 handle.await;
7362
7363 // GitPanel
7364 // - Tracked:
7365 // - [x] tracked
7366 // - Untracked
7367 // - [] untracked
7368 //
7369 // The commit message should still read:
7370 // "Update tracked"
7371 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7372 assert_eq!(message, Some("Update tracked".to_string()));
7373
7374 let second_status_entry = entries[3].clone();
7375 panel.update_in(cx, |panel, window, cx| {
7376 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7377 });
7378
7379 cx.read(|cx| {
7380 project
7381 .read(cx)
7382 .worktrees(cx)
7383 .next()
7384 .unwrap()
7385 .read(cx)
7386 .as_local()
7387 .unwrap()
7388 .scan_complete()
7389 })
7390 .await;
7391
7392 cx.executor().run_until_parked();
7393
7394 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7395 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7396 });
7397 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7398 handle.await;
7399
7400 // GitPanel
7401 // - Tracked:
7402 // - [x] tracked
7403 // - Untracked
7404 // - [x] untracked
7405 //
7406 // The commit message should now read:
7407 // "Enter commit message"
7408 // (which means we should see None returned).
7409 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7410 assert!(message.is_none());
7411
7412 panel.update_in(cx, |panel, window, cx| {
7413 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7414 });
7415
7416 cx.read(|cx| {
7417 project
7418 .read(cx)
7419 .worktrees(cx)
7420 .next()
7421 .unwrap()
7422 .read(cx)
7423 .as_local()
7424 .unwrap()
7425 .scan_complete()
7426 })
7427 .await;
7428
7429 cx.executor().run_until_parked();
7430
7431 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7432 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7433 });
7434 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7435 handle.await;
7436
7437 // GitPanel
7438 // - Tracked:
7439 // - [] tracked
7440 // - Untracked
7441 // - [x] untracked
7442 //
7443 // The commit message should now read:
7444 // "Update untracked"
7445 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7446 assert_eq!(message, Some("Create untracked".to_string()));
7447
7448 panel.update_in(cx, |panel, window, cx| {
7449 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7450 });
7451
7452 cx.read(|cx| {
7453 project
7454 .read(cx)
7455 .worktrees(cx)
7456 .next()
7457 .unwrap()
7458 .read(cx)
7459 .as_local()
7460 .unwrap()
7461 .scan_complete()
7462 })
7463 .await;
7464
7465 cx.executor().run_until_parked();
7466
7467 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7468 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7469 });
7470 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7471 handle.await;
7472
7473 // GitPanel
7474 // - Tracked:
7475 // - [] tracked
7476 // - Untracked
7477 // - [] untracked
7478 //
7479 // The commit message should now read:
7480 // "Update tracked"
7481 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7482 assert_eq!(message, Some("Update tracked".to_string()));
7483 }
7484}