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