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