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