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