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