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 };
2695
2696 let stream = model.stream_completion_text(request, cx);
2697 match stream.await {
2698 Ok(mut messages) => {
2699 if !text_empty {
2700 this.update(cx, |this, cx| {
2701 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2702 let insert_position = buffer.anchor_before(buffer.len());
2703 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
2704 });
2705 })?;
2706 }
2707
2708 while let Some(message) = messages.stream.next().await {
2709 match message {
2710 Ok(text) => {
2711 this.update(cx, |this, cx| {
2712 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
2713 let insert_position = buffer.anchor_before(buffer.len());
2714 buffer.edit([(insert_position..insert_position, text)], None, cx);
2715 });
2716 })?;
2717 }
2718 Err(e) => {
2719 Self::show_commit_message_error(&this, &e, cx);
2720 break;
2721 }
2722 }
2723 }
2724 }
2725 Err(e) => {
2726 Self::show_commit_message_error(&this, &e, cx);
2727 }
2728 }
2729
2730 anyhow::Ok(())
2731 }
2732 .log_err().await
2733 }));
2734 }
2735
2736 fn get_fetch_options(
2737 &self,
2738 window: &mut Window,
2739 cx: &mut Context<Self>,
2740 ) -> Task<Option<FetchOptions>> {
2741 let repo = self.active_repository.clone();
2742 let workspace = self.workspace.clone();
2743
2744 cx.spawn_in(window, async move |_, cx| {
2745 let repo = repo?;
2746 let remotes = repo
2747 .update(cx, |repo, _| repo.get_remotes(None, false))
2748 .await
2749 .ok()?
2750 .log_err()?;
2751
2752 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2753 if remotes.len() > 1 {
2754 remotes.push(FetchOptions::All);
2755 }
2756 let selection = cx
2757 .update(|window, cx| {
2758 picker_prompt::prompt(
2759 "Pick which remote to fetch",
2760 remotes.iter().map(|r| r.name()).collect(),
2761 workspace,
2762 window,
2763 cx,
2764 )
2765 })
2766 .ok()?
2767 .await?;
2768 remotes.get(selection).cloned()
2769 })
2770 }
2771
2772 pub(crate) fn fetch(
2773 &mut self,
2774 is_fetch_all: bool,
2775 window: &mut Window,
2776 cx: &mut Context<Self>,
2777 ) {
2778 if !self.can_push_and_pull(cx) {
2779 return;
2780 }
2781
2782 let Some(repo) = self.active_repository.clone() else {
2783 return;
2784 };
2785 telemetry::event!("Git Fetched");
2786 let askpass = self.askpass_delegate("git fetch", window, cx);
2787 let this = cx.weak_entity();
2788
2789 let fetch_options = if is_fetch_all {
2790 Task::ready(Some(FetchOptions::All))
2791 } else {
2792 self.get_fetch_options(window, cx)
2793 };
2794
2795 window
2796 .spawn(cx, async move |cx| {
2797 let Some(fetch_options) = fetch_options.await else {
2798 return Ok(());
2799 };
2800 let fetch = repo.update(cx, |repo, cx| {
2801 repo.fetch(fetch_options.clone(), askpass, cx)
2802 });
2803
2804 let remote_message = fetch.await?;
2805 this.update(cx, |this, cx| {
2806 let action = match fetch_options {
2807 FetchOptions::All => RemoteAction::Fetch(None),
2808 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2809 };
2810 match remote_message {
2811 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2812 Err(e) => {
2813 log::error!("Error while fetching {:?}", e);
2814 this.show_error_toast(action.name(), e, cx)
2815 }
2816 }
2817
2818 anyhow::Ok(())
2819 })
2820 .ok();
2821 anyhow::Ok(())
2822 })
2823 .detach_and_log_err(cx);
2824 }
2825
2826 pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2827 let workspace = self.workspace.clone();
2828
2829 crate::clone::clone_and_open(
2830 repo.into(),
2831 workspace,
2832 window,
2833 cx,
2834 Arc::new(|_workspace: &mut workspace::Workspace, _window, _cx| {}),
2835 );
2836 }
2837
2838 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2839 let worktrees = self
2840 .project
2841 .read(cx)
2842 .visible_worktrees(cx)
2843 .collect::<Vec<_>>();
2844
2845 let worktree = if worktrees.len() == 1 {
2846 Task::ready(Some(worktrees.first().unwrap().clone()))
2847 } else if worktrees.is_empty() {
2848 let result = window.prompt(
2849 PromptLevel::Warning,
2850 "Unable to initialize a git repository",
2851 Some("Open a directory first"),
2852 &["Ok"],
2853 cx,
2854 );
2855 cx.background_executor()
2856 .spawn(async move {
2857 result.await.ok();
2858 })
2859 .detach();
2860 return;
2861 } else {
2862 let worktree_directories = worktrees
2863 .iter()
2864 .map(|worktree| worktree.read(cx).abs_path())
2865 .map(|worktree_abs_path| {
2866 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2867 Path::new("~")
2868 .join(path)
2869 .to_string_lossy()
2870 .to_string()
2871 .into()
2872 } else {
2873 worktree_abs_path.to_string_lossy().into_owned().into()
2874 }
2875 })
2876 .collect_vec();
2877 let prompt = picker_prompt::prompt(
2878 "Where would you like to initialize this git repository?",
2879 worktree_directories,
2880 self.workspace.clone(),
2881 window,
2882 cx,
2883 );
2884
2885 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2886 };
2887
2888 cx.spawn_in(window, async move |this, cx| {
2889 let worktree = match worktree.await {
2890 Some(worktree) => worktree,
2891 None => {
2892 return;
2893 }
2894 };
2895
2896 let Ok(result) = this.update(cx, |this, cx| {
2897 let fallback_branch_name = GitPanelSettings::get_global(cx)
2898 .fallback_branch_name
2899 .clone();
2900 this.project.read(cx).git_init(
2901 worktree.read(cx).abs_path(),
2902 fallback_branch_name,
2903 cx,
2904 )
2905 }) else {
2906 return;
2907 };
2908
2909 let result = result.await;
2910
2911 this.update_in(cx, |this, _, cx| match result {
2912 Ok(()) => {}
2913 Err(e) => this.show_error_toast("init", e, cx),
2914 })
2915 .ok();
2916 })
2917 .detach();
2918 }
2919
2920 pub(crate) fn pull(&mut self, rebase: bool, window: &mut Window, cx: &mut Context<Self>) {
2921 if !self.can_push_and_pull(cx) {
2922 return;
2923 }
2924 let Some(repo) = self.active_repository.clone() else {
2925 return;
2926 };
2927 let Some(branch) = repo.read(cx).branch.as_ref() else {
2928 return;
2929 };
2930 telemetry::event!("Git Pulled");
2931 let branch = branch.clone();
2932 let remote = self.get_remote(false, false, window, cx);
2933 cx.spawn_in(window, async move |this, cx| {
2934 let remote = match remote.await {
2935 Ok(Some(remote)) => remote,
2936 Ok(None) => {
2937 return Ok(());
2938 }
2939 Err(e) => {
2940 log::error!("Failed to get current remote: {}", e);
2941 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2942 .ok();
2943 return Ok(());
2944 }
2945 };
2946
2947 let askpass = this.update_in(cx, |this, window, cx| {
2948 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2949 })?;
2950
2951 let branch_name = branch
2952 .upstream
2953 .is_none()
2954 .then(|| branch.name().to_owned().into());
2955
2956 let pull = repo.update(cx, |repo, cx| {
2957 repo.pull(branch_name, remote.name.clone(), rebase, askpass, cx)
2958 });
2959
2960 let remote_message = pull.await?;
2961
2962 let action = RemoteAction::Pull(remote);
2963 this.update(cx, |this, cx| match remote_message {
2964 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2965 Err(e) => {
2966 log::error!("Error while pulling {:?}", e);
2967 this.show_error_toast(action.name(), e, cx)
2968 }
2969 })
2970 .ok();
2971
2972 anyhow::Ok(())
2973 })
2974 .detach_and_log_err(cx);
2975 }
2976
2977 pub(crate) fn push(
2978 &mut self,
2979 force_push: bool,
2980 select_remote: bool,
2981 window: &mut Window,
2982 cx: &mut Context<Self>,
2983 ) {
2984 if !self.can_push_and_pull(cx) {
2985 return;
2986 }
2987 let Some(repo) = self.active_repository.clone() else {
2988 return;
2989 };
2990 let Some(branch) = repo.read(cx).branch.as_ref() else {
2991 return;
2992 };
2993 telemetry::event!("Git Pushed");
2994 let branch = branch.clone();
2995
2996 let options = if force_push {
2997 Some(PushOptions::Force)
2998 } else {
2999 match branch.upstream {
3000 Some(Upstream {
3001 tracking: UpstreamTracking::Gone,
3002 ..
3003 })
3004 | None => Some(PushOptions::SetUpstream),
3005 _ => None,
3006 }
3007 };
3008 let remote = self.get_remote(select_remote, true, window, cx);
3009
3010 cx.spawn_in(window, async move |this, cx| {
3011 let remote = match remote.await {
3012 Ok(Some(remote)) => remote,
3013 Ok(None) => {
3014 return Ok(());
3015 }
3016 Err(e) => {
3017 log::error!("Failed to get current remote: {}", e);
3018 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
3019 .ok();
3020 return Ok(());
3021 }
3022 };
3023
3024 let askpass_delegate = this.update_in(cx, |this, window, cx| {
3025 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
3026 })?;
3027
3028 let push = repo.update(cx, |repo, cx| {
3029 repo.push(
3030 branch.name().to_owned().into(),
3031 branch
3032 .upstream
3033 .as_ref()
3034 .filter(|u| matches!(u.tracking, UpstreamTracking::Tracked(_)))
3035 .and_then(|u| u.branch_name())
3036 .unwrap_or_else(|| branch.name())
3037 .to_owned()
3038 .into(),
3039 remote.name.clone(),
3040 options,
3041 askpass_delegate,
3042 cx,
3043 )
3044 });
3045
3046 let remote_output = push.await?;
3047
3048 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
3049 this.update(cx, |this, cx| match remote_output {
3050 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
3051 Err(e) => {
3052 log::error!("Error while pushing {:?}", e);
3053 this.show_error_toast(action.name(), e, cx)
3054 }
3055 })?;
3056
3057 anyhow::Ok(())
3058 })
3059 .detach_and_log_err(cx);
3060 }
3061
3062 pub fn create_pull_request(&self, window: &mut Window, cx: &mut Context<Self>) {
3063 let result = (|| -> anyhow::Result<()> {
3064 let repo = self
3065 .active_repository
3066 .clone()
3067 .ok_or_else(|| anyhow::anyhow!("No active repository"))?;
3068
3069 let (branch, remote_origin, remote_upstream) = {
3070 let repository = repo.read(cx);
3071 (
3072 repository.branch.clone(),
3073 repository.remote_origin_url.clone(),
3074 repository.remote_upstream_url.clone(),
3075 )
3076 };
3077
3078 let branch = branch.ok_or_else(|| anyhow::anyhow!("No active branch"))?;
3079 let source_branch = branch
3080 .upstream
3081 .as_ref()
3082 .filter(|upstream| matches!(upstream.tracking, UpstreamTracking::Tracked(_)))
3083 .and_then(|upstream| upstream.branch_name())
3084 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3085 let source_branch = source_branch.to_string();
3086
3087 let remote_url = branch
3088 .upstream
3089 .as_ref()
3090 .and_then(|upstream| match upstream.remote_name() {
3091 Some("upstream") => remote_upstream.as_deref(),
3092 Some(_) => remote_origin.as_deref(),
3093 None => None,
3094 })
3095 .or(remote_origin.as_deref())
3096 .or(remote_upstream.as_deref())
3097 .ok_or_else(|| anyhow::anyhow!("No remote configured for repository"))?;
3098 let remote_url = remote_url.to_string();
3099
3100 let provider_registry = GitHostingProviderRegistry::global(cx);
3101 let Some((provider, parsed_remote)) =
3102 git::parse_git_remote_url(provider_registry, &remote_url)
3103 else {
3104 return Err(anyhow::anyhow!("Unsupported remote URL: {}", remote_url));
3105 };
3106
3107 let Some(url) = provider.build_create_pull_request_url(&parsed_remote, &source_branch)
3108 else {
3109 return Err(anyhow::anyhow!("Unable to construct pull request URL"));
3110 };
3111
3112 cx.open_url(url.as_str());
3113 Ok(())
3114 })();
3115
3116 if let Err(err) = result {
3117 log::error!("Error while creating pull request {:?}", err);
3118 cx.defer_in(window, |panel, _window, cx| {
3119 panel.show_error_toast("create pull request", err, cx);
3120 });
3121 }
3122 }
3123
3124 fn askpass_delegate(
3125 &self,
3126 operation: impl Into<SharedString>,
3127 window: &mut Window,
3128 cx: &mut Context<Self>,
3129 ) -> AskPassDelegate {
3130 let this = cx.weak_entity();
3131 let operation = operation.into();
3132 let window = window.window_handle();
3133 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
3134 window
3135 .update(cx, |_, window, cx| {
3136 this.update(cx, |this, cx| {
3137 this.workspace.update(cx, |workspace, cx| {
3138 workspace.toggle_modal(window, cx, |window, cx| {
3139 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
3140 });
3141 })
3142 })
3143 })
3144 .ok();
3145 })
3146 }
3147
3148 fn can_push_and_pull(&self, cx: &App) -> bool {
3149 !self.project.read(cx).is_via_collab()
3150 }
3151
3152 fn get_remote(
3153 &mut self,
3154 always_select: bool,
3155 is_push: bool,
3156 window: &mut Window,
3157 cx: &mut Context<Self>,
3158 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
3159 let repo = self.active_repository.clone();
3160 let workspace = self.workspace.clone();
3161 let mut cx = window.to_async(cx);
3162
3163 async move {
3164 let repo = repo.context("No active repository")?;
3165 let current_remotes: Vec<Remote> = repo
3166 .update(&mut cx, |repo, _| {
3167 let current_branch = if always_select {
3168 None
3169 } else {
3170 let current_branch = repo.branch.as_ref().context("No active branch")?;
3171 Some(current_branch.name().to_string())
3172 };
3173 anyhow::Ok(repo.get_remotes(current_branch, is_push))
3174 })?
3175 .await??;
3176
3177 let current_remotes: Vec<_> = current_remotes
3178 .into_iter()
3179 .map(|remotes| remotes.name)
3180 .collect();
3181 let selection = cx
3182 .update(|window, cx| {
3183 picker_prompt::prompt(
3184 "Pick which remote to push to",
3185 current_remotes.clone(),
3186 workspace,
3187 window,
3188 cx,
3189 )
3190 })?
3191 .await;
3192
3193 Ok(selection.map(|selection| Remote {
3194 name: current_remotes[selection].clone(),
3195 }))
3196 }
3197 }
3198
3199 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
3200 if self.local_committer_task.is_none() {
3201 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
3202 let committer = get_git_committer(cx).await;
3203 this.update(cx, |this, cx| {
3204 this.local_committer = Some(committer);
3205 cx.notify()
3206 })
3207 .ok();
3208 }));
3209 }
3210 }
3211
3212 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
3213 let mut new_co_authors = Vec::new();
3214 let project = self.project.read(cx);
3215
3216 let Some(room) = self
3217 .workspace
3218 .upgrade()
3219 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
3220 else {
3221 return Vec::default();
3222 };
3223
3224 let room = room.read(cx);
3225
3226 for (peer_id, collaborator) in project.collaborators() {
3227 if collaborator.is_host {
3228 continue;
3229 }
3230
3231 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
3232 continue;
3233 };
3234 if !participant.can_write() {
3235 continue;
3236 }
3237 if let Some(email) = &collaborator.committer_email {
3238 let name = collaborator
3239 .committer_name
3240 .clone()
3241 .or_else(|| participant.user.name.clone())
3242 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
3243 new_co_authors.push((name.clone(), email.clone()))
3244 }
3245 }
3246 if !project.is_local()
3247 && !project.is_read_only(cx)
3248 && let Some(local_committer) = self.local_committer(room, cx)
3249 {
3250 new_co_authors.push(local_committer);
3251 }
3252 new_co_authors
3253 }
3254
3255 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
3256 let user = room.local_participant_user(cx)?;
3257 let committer = self.local_committer.as_ref()?;
3258 let email = committer.email.clone()?;
3259 let name = committer
3260 .name
3261 .clone()
3262 .or_else(|| user.name.clone())
3263 .unwrap_or_else(|| user.github_login.clone().to_string());
3264 Some((name, email))
3265 }
3266
3267 fn toggle_fill_co_authors(
3268 &mut self,
3269 _: &ToggleFillCoAuthors,
3270 _: &mut Window,
3271 cx: &mut Context<Self>,
3272 ) {
3273 self.add_coauthors = !self.add_coauthors;
3274 cx.notify();
3275 }
3276
3277 fn toggle_sort_by_path(
3278 &mut self,
3279 _: &ToggleSortByPath,
3280 _: &mut Window,
3281 cx: &mut Context<Self>,
3282 ) {
3283 let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
3284 if let Some(workspace) = self.workspace.upgrade() {
3285 let workspace = workspace.read(cx);
3286 let fs = workspace.app_state().fs.clone();
3287 cx.update_global::<SettingsStore, _>(|store, _cx| {
3288 store.update_settings_file(fs, move |settings, _cx| {
3289 settings.git_panel.get_or_insert_default().sort_by_path =
3290 Some(!current_setting);
3291 });
3292 });
3293 }
3294 }
3295
3296 fn toggle_tree_view(&mut self, _: &ToggleTreeView, _: &mut Window, cx: &mut Context<Self>) {
3297 let current_setting = GitPanelSettings::get_global(cx).tree_view;
3298 if let Some(workspace) = self.workspace.upgrade() {
3299 let workspace = workspace.read(cx);
3300 let fs = workspace.app_state().fs.clone();
3301 cx.update_global::<SettingsStore, _>(|store, _cx| {
3302 store.update_settings_file(fs, move |settings, _cx| {
3303 settings.git_panel.get_or_insert_default().tree_view = Some(!current_setting);
3304 });
3305 })
3306 }
3307 }
3308
3309 fn toggle_directory(&mut self, key: &TreeKey, window: &mut Window, cx: &mut Context<Self>) {
3310 if let Some(state) = self.view_mode.tree_state_mut() {
3311 let expanded = state.expanded_dirs.entry(key.clone()).or_insert(true);
3312 *expanded = !*expanded;
3313 self.update_visible_entries(window, cx);
3314 } else {
3315 util::debug_panic!("Attempted to toggle directory in flat Git Panel state");
3316 }
3317 }
3318
3319 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
3320 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
3321
3322 let existing_text = message.to_ascii_lowercase();
3323 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
3324 let mut ends_with_co_authors = false;
3325 let existing_co_authors = existing_text
3326 .lines()
3327 .filter_map(|line| {
3328 let line = line.trim();
3329 if line.starts_with(&lowercase_co_author_prefix) {
3330 ends_with_co_authors = true;
3331 Some(line)
3332 } else {
3333 ends_with_co_authors = false;
3334 None
3335 }
3336 })
3337 .collect::<HashSet<_>>();
3338
3339 let new_co_authors = self
3340 .potential_co_authors(cx)
3341 .into_iter()
3342 .filter(|(_, email)| {
3343 !existing_co_authors
3344 .iter()
3345 .any(|existing| existing.contains(email.as_str()))
3346 })
3347 .collect::<Vec<_>>();
3348
3349 if new_co_authors.is_empty() {
3350 return;
3351 }
3352
3353 if !ends_with_co_authors {
3354 message.push('\n');
3355 }
3356 for (name, email) in new_co_authors {
3357 message.push('\n');
3358 message.push_str(CO_AUTHOR_PREFIX);
3359 message.push_str(&name);
3360 message.push_str(" <");
3361 message.push_str(&email);
3362 message.push('>');
3363 }
3364 message.push('\n');
3365 }
3366
3367 fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3368 let handle = cx.entity().downgrade();
3369 self.reopen_commit_buffer(window, cx);
3370 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
3371 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
3372 if let Some(git_panel) = handle.upgrade() {
3373 git_panel
3374 .update_in(cx, |git_panel, window, cx| {
3375 git_panel.update_visible_entries(window, cx);
3376 })
3377 .ok();
3378 }
3379 });
3380 }
3381
3382 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3383 let Some(active_repo) = self.active_repository.as_ref() else {
3384 return;
3385 };
3386 let load_buffer = active_repo.update(cx, |active_repo, cx| {
3387 let project = self.project.read(cx);
3388 active_repo.open_commit_buffer(
3389 Some(project.languages().clone()),
3390 project.buffer_store().clone(),
3391 cx,
3392 )
3393 });
3394
3395 cx.spawn_in(window, async move |git_panel, cx| {
3396 let buffer = load_buffer.await?;
3397 git_panel.update_in(cx, |git_panel, window, cx| {
3398 if git_panel
3399 .commit_editor
3400 .read(cx)
3401 .buffer()
3402 .read(cx)
3403 .as_singleton()
3404 .as_ref()
3405 != Some(&buffer)
3406 {
3407 git_panel.commit_editor = cx.new(|cx| {
3408 commit_message_editor(
3409 buffer,
3410 git_panel.suggest_commit_message(cx).map(SharedString::from),
3411 git_panel.project.clone(),
3412 true,
3413 window,
3414 cx,
3415 )
3416 });
3417 }
3418 })
3419 })
3420 .detach_and_log_err(cx);
3421 }
3422
3423 fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3424 let path_style = self.project.read(cx).path_style(cx);
3425 let bulk_staging = self.bulk_staging.take();
3426 let last_staged_path_prev_index = bulk_staging
3427 .as_ref()
3428 .and_then(|op| self.entry_by_path(&op.anchor));
3429
3430 self.entries.clear();
3431 self.entries_indices.clear();
3432 self.single_staged_entry.take();
3433 self.single_tracked_entry.take();
3434 self.conflicted_count = 0;
3435 self.conflicted_staged_count = 0;
3436 self.changes_count = 0;
3437 self.new_count = 0;
3438 self.tracked_count = 0;
3439 self.new_staged_count = 0;
3440 self.tracked_staged_count = 0;
3441 self.entry_count = 0;
3442 self.max_width_item_index = None;
3443
3444 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
3445 let is_tree_view = matches!(self.view_mode, GitPanelViewMode::Tree(_));
3446 let group_by_status = is_tree_view || !sort_by_path;
3447
3448 let mut changed_entries = Vec::new();
3449 let mut new_entries = Vec::new();
3450 let mut conflict_entries = Vec::new();
3451 let mut single_staged_entry = None;
3452 let mut staged_count = 0;
3453 let mut seen_directories = HashSet::default();
3454 let mut max_width_estimate = 0usize;
3455 let mut max_width_item_index = None;
3456
3457 let Some(repo) = self.active_repository.as_ref() else {
3458 // Just clear entries if no repository is active.
3459 cx.notify();
3460 return;
3461 };
3462
3463 let repo = repo.read(cx);
3464
3465 self.stash_entries = repo.cached_stash();
3466
3467 for entry in repo.cached_status() {
3468 self.changes_count += 1;
3469 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
3470 let is_new = entry.status.is_created();
3471 let staging = entry.status.staging();
3472
3473 if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
3474 && pending
3475 .ops
3476 .iter()
3477 .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
3478 {
3479 continue;
3480 }
3481
3482 let entry = GitStatusEntry {
3483 repo_path: entry.repo_path.clone(),
3484 status: entry.status,
3485 staging,
3486 };
3487
3488 if staging.has_staged() {
3489 staged_count += 1;
3490 single_staged_entry = Some(entry.clone());
3491 }
3492
3493 if group_by_status && is_conflict {
3494 conflict_entries.push(entry);
3495 } else if group_by_status && is_new {
3496 new_entries.push(entry);
3497 } else {
3498 changed_entries.push(entry);
3499 }
3500 }
3501
3502 if conflict_entries.is_empty() {
3503 if staged_count == 1
3504 && let Some(entry) = single_staged_entry.as_ref()
3505 {
3506 if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
3507 if ops.staged() {
3508 self.single_staged_entry = single_staged_entry;
3509 }
3510 } else {
3511 self.single_staged_entry = single_staged_entry;
3512 }
3513 } else if repo.pending_ops_summary().item_summary.staging_count == 1
3514 && let Some(ops) = repo.pending_ops().find(|ops| ops.staging())
3515 {
3516 self.single_staged_entry =
3517 repo.status_for_path(&ops.repo_path)
3518 .map(|status| GitStatusEntry {
3519 repo_path: ops.repo_path.clone(),
3520 status: status.status,
3521 staging: StageStatus::Staged,
3522 });
3523 }
3524 }
3525
3526 if conflict_entries.is_empty() && changed_entries.len() == 1 {
3527 self.single_tracked_entry = changed_entries.first().cloned();
3528 }
3529
3530 let mut push_entry =
3531 |this: &mut Self,
3532 entry: GitListEntry,
3533 is_visible: bool,
3534 logical_indices: Option<&mut Vec<usize>>| {
3535 if let Some(estimate) =
3536 this.width_estimate_for_list_entry(is_tree_view, &entry, path_style)
3537 {
3538 if estimate > max_width_estimate {
3539 max_width_estimate = estimate;
3540 max_width_item_index = Some(this.entries.len());
3541 }
3542 }
3543
3544 if let Some(repo_path) = entry.status_entry().map(|status| status.repo_path.clone())
3545 {
3546 this.entries_indices.insert(repo_path, this.entries.len());
3547 }
3548
3549 if let (Some(indices), true) = (logical_indices, is_visible) {
3550 indices.push(this.entries.len());
3551 }
3552
3553 this.entries.push(entry);
3554 };
3555
3556 macro_rules! take_section_entries {
3557 () => {
3558 [
3559 (Section::Conflict, std::mem::take(&mut conflict_entries)),
3560 (Section::Tracked, std::mem::take(&mut changed_entries)),
3561 (Section::New, std::mem::take(&mut new_entries)),
3562 ]
3563 };
3564 }
3565
3566 match &mut self.view_mode {
3567 GitPanelViewMode::Tree(tree_state) => {
3568 tree_state.logical_indices.clear();
3569 tree_state.directory_descendants.clear();
3570
3571 // This is just to get around the borrow checker
3572 // because push_entry mutably borrows self
3573 let mut tree_state = std::mem::take(tree_state);
3574
3575 for (section, entries) in take_section_entries!() {
3576 if entries.is_empty() {
3577 continue;
3578 }
3579
3580 push_entry(
3581 self,
3582 GitListEntry::Header(GitHeaderEntry { header: section }),
3583 true,
3584 Some(&mut tree_state.logical_indices),
3585 );
3586
3587 for (entry, is_visible) in
3588 tree_state.build_tree_entries(section, entries, &mut seen_directories)
3589 {
3590 push_entry(
3591 self,
3592 entry,
3593 is_visible,
3594 Some(&mut tree_state.logical_indices),
3595 );
3596 }
3597 }
3598
3599 tree_state
3600 .expanded_dirs
3601 .retain(|key, _| seen_directories.contains(key));
3602 self.view_mode = GitPanelViewMode::Tree(tree_state);
3603 }
3604 GitPanelViewMode::Flat => {
3605 for (section, entries) in take_section_entries!() {
3606 if entries.is_empty() {
3607 continue;
3608 }
3609
3610 if section != Section::Tracked || !sort_by_path {
3611 push_entry(
3612 self,
3613 GitListEntry::Header(GitHeaderEntry { header: section }),
3614 true,
3615 None,
3616 );
3617 }
3618
3619 for entry in entries {
3620 push_entry(self, GitListEntry::Status(entry), true, None);
3621 }
3622 }
3623 }
3624 }
3625
3626 self.max_width_item_index = max_width_item_index;
3627
3628 self.update_counts(repo);
3629
3630 let bulk_staging_anchor_new_index = bulk_staging
3631 .as_ref()
3632 .filter(|op| op.repo_id == repo.id)
3633 .and_then(|op| self.entry_by_path(&op.anchor));
3634 if bulk_staging_anchor_new_index == last_staged_path_prev_index
3635 && let Some(index) = bulk_staging_anchor_new_index
3636 && let Some(entry) = self.entries.get(index)
3637 && let Some(entry) = entry.status_entry()
3638 && GitPanel::stage_status_for_entry(entry, &repo)
3639 .as_bool()
3640 .unwrap_or(false)
3641 {
3642 self.bulk_staging = bulk_staging;
3643 }
3644
3645 self.select_first_entry_if_none(window, cx);
3646
3647 let suggested_commit_message = self.suggest_commit_message(cx);
3648 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
3649
3650 self.commit_editor.update(cx, |editor, cx| {
3651 editor.set_placeholder_text(&placeholder_text, window, cx)
3652 });
3653
3654 cx.notify();
3655 }
3656
3657 fn header_state(&self, header_type: Section) -> ToggleState {
3658 let (staged_count, count) = match header_type {
3659 Section::New => (self.new_staged_count, self.new_count),
3660 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
3661 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
3662 };
3663 if staged_count == 0 {
3664 ToggleState::Unselected
3665 } else if count == staged_count {
3666 ToggleState::Selected
3667 } else {
3668 ToggleState::Indeterminate
3669 }
3670 }
3671
3672 fn update_counts(&mut self, repo: &Repository) {
3673 self.show_placeholders = false;
3674 self.conflicted_count = 0;
3675 self.conflicted_staged_count = 0;
3676 self.new_count = 0;
3677 self.tracked_count = 0;
3678 self.new_staged_count = 0;
3679 self.tracked_staged_count = 0;
3680 self.entry_count = 0;
3681
3682 for status_entry in self.entries.iter().filter_map(|entry| entry.status_entry()) {
3683 self.entry_count += 1;
3684 let is_staging_or_staged = GitPanel::stage_status_for_entry(status_entry, repo)
3685 .as_bool()
3686 .unwrap_or(true);
3687
3688 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
3689 self.conflicted_count += 1;
3690 if is_staging_or_staged {
3691 self.conflicted_staged_count += 1;
3692 }
3693 } else if status_entry.status.is_created() {
3694 self.new_count += 1;
3695 if is_staging_or_staged {
3696 self.new_staged_count += 1;
3697 }
3698 } else {
3699 self.tracked_count += 1;
3700 if is_staging_or_staged {
3701 self.tracked_staged_count += 1;
3702 }
3703 }
3704 }
3705 }
3706
3707 pub(crate) fn has_staged_changes(&self) -> bool {
3708 self.tracked_staged_count > 0
3709 || self.new_staged_count > 0
3710 || self.conflicted_staged_count > 0
3711 }
3712
3713 pub(crate) fn has_unstaged_changes(&self) -> bool {
3714 self.tracked_count > self.tracked_staged_count
3715 || self.new_count > self.new_staged_count
3716 || self.conflicted_count > self.conflicted_staged_count
3717 }
3718
3719 fn has_tracked_changes(&self) -> bool {
3720 self.tracked_count > 0
3721 }
3722
3723 pub fn has_unstaged_conflicts(&self) -> bool {
3724 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
3725 }
3726
3727 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
3728 let Some(workspace) = self.workspace.upgrade() else {
3729 return;
3730 };
3731 show_error_toast(workspace, action, e, cx)
3732 }
3733
3734 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3735 where
3736 E: std::fmt::Debug + std::fmt::Display,
3737 {
3738 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3739 let _ = workspace.update(cx, |workspace, cx| {
3740 struct CommitMessageError;
3741 let notification_id = NotificationId::unique::<CommitMessageError>();
3742 workspace.show_notification(notification_id, cx, |cx| {
3743 cx.new(|cx| {
3744 ErrorMessagePrompt::new(
3745 format!("Failed to generate commit message: {err}"),
3746 cx,
3747 )
3748 })
3749 });
3750 });
3751 }
3752 }
3753
3754 fn show_remote_output(
3755 &mut self,
3756 action: RemoteAction,
3757 info: RemoteCommandOutput,
3758 cx: &mut Context<Self>,
3759 ) {
3760 let Some(workspace) = self.workspace.upgrade() else {
3761 return;
3762 };
3763
3764 workspace.update(cx, |workspace, cx| {
3765 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3766 let workspace_weak = cx.weak_entity();
3767 let operation = action.name();
3768
3769 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3770 use remote_output::SuccessStyle::*;
3771 match style {
3772 Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3773 ToastWithLog { output } => this
3774 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3775 .action("View Log", move |window, cx| {
3776 let output = output.clone();
3777 let output =
3778 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3779 workspace_weak
3780 .update(cx, move |workspace, cx| {
3781 open_output(operation, workspace, &output, window, cx)
3782 })
3783 .ok();
3784 }),
3785 PushPrLink { text, link } => this
3786 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3787 .action(text, move |_, cx| cx.open_url(&link)),
3788 }
3789 .dismiss_button(true)
3790 });
3791 workspace.toggle_status_toast(status_toast, cx)
3792 });
3793 }
3794
3795 pub fn can_commit(&self) -> bool {
3796 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3797 }
3798
3799 pub fn can_stage_all(&self) -> bool {
3800 self.has_unstaged_changes()
3801 }
3802
3803 pub fn can_unstage_all(&self) -> bool {
3804 self.has_staged_changes()
3805 }
3806
3807 fn status_width_estimate(
3808 tree_view: bool,
3809 entry: &GitStatusEntry,
3810 path_style: PathStyle,
3811 depth: usize,
3812 ) -> usize {
3813 if tree_view {
3814 Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3815 } else {
3816 Self::item_width_estimate(
3817 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3818 entry.display_name(path_style).len(),
3819 0,
3820 )
3821 }
3822 }
3823
3824 fn width_estimate_for_list_entry(
3825 &self,
3826 tree_view: bool,
3827 entry: &GitListEntry,
3828 path_style: PathStyle,
3829 ) -> Option<usize> {
3830 match entry {
3831 GitListEntry::Status(status) => Some(Self::status_width_estimate(
3832 tree_view, status, path_style, 0,
3833 )),
3834 GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3835 tree_view,
3836 &status.entry,
3837 path_style,
3838 status.depth,
3839 )),
3840 GitListEntry::Directory(dir) => {
3841 Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3842 }
3843 GitListEntry::Header(_) => None,
3844 }
3845 }
3846
3847 fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3848 path + file_name + depth * 2
3849 }
3850
3851 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3852 let focus_handle = self.focus_handle.clone();
3853 let has_tracked_changes = self.has_tracked_changes();
3854 let has_staged_changes = self.has_staged_changes();
3855 let has_unstaged_changes = self.has_unstaged_changes();
3856 let has_new_changes = self.new_count > 0;
3857 let has_stash_items = self.stash_entries.entries.len() > 0;
3858
3859 PopoverMenu::new(id.into())
3860 .trigger(
3861 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3862 .icon_size(IconSize::Small)
3863 .icon_color(Color::Muted),
3864 )
3865 .menu(move |window, cx| {
3866 Some(git_panel_context_menu(
3867 focus_handle.clone(),
3868 GitMenuState {
3869 has_tracked_changes,
3870 has_staged_changes,
3871 has_unstaged_changes,
3872 has_new_changes,
3873 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3874 has_stash_items,
3875 tree_view: GitPanelSettings::get_global(cx).tree_view,
3876 },
3877 window,
3878 cx,
3879 ))
3880 })
3881 .anchor(Corner::TopRight)
3882 }
3883
3884 pub(crate) fn render_generate_commit_message_button(
3885 &self,
3886 cx: &Context<Self>,
3887 ) -> Option<AnyElement> {
3888 if !agent_settings::AgentSettings::get_global(cx).enabled(cx) {
3889 return None;
3890 }
3891
3892 if self.generate_commit_message_task.is_some() {
3893 return Some(
3894 h_flex()
3895 .gap_1()
3896 .child(
3897 Icon::new(IconName::ArrowCircle)
3898 .size(IconSize::XSmall)
3899 .color(Color::Info)
3900 .with_rotate_animation(2),
3901 )
3902 .child(
3903 Label::new("Generating Commit…")
3904 .size(LabelSize::Small)
3905 .color(Color::Muted),
3906 )
3907 .into_any_element(),
3908 );
3909 }
3910
3911 let model_registry = LanguageModelRegistry::read_global(cx);
3912 let has_commit_model_configuration_error = model_registry
3913 .configuration_error(model_registry.commit_message_model(), cx)
3914 .is_some();
3915 let can_commit = self.can_commit();
3916
3917 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3918
3919 Some(
3920 IconButton::new("generate-commit-message", IconName::AiEdit)
3921 .shape(ui::IconButtonShape::Square)
3922 .icon_color(if has_commit_model_configuration_error {
3923 Color::Disabled
3924 } else {
3925 Color::Muted
3926 })
3927 .tooltip(move |_window, cx| {
3928 if !can_commit {
3929 Tooltip::simple("No Changes to Commit", cx)
3930 } else if has_commit_model_configuration_error {
3931 Tooltip::simple("Configure an LLM provider to generate commit messages", cx)
3932 } else {
3933 Tooltip::for_action_in(
3934 "Generate Commit Message",
3935 &git::GenerateCommitMessage,
3936 &editor_focus_handle,
3937 cx,
3938 )
3939 }
3940 })
3941 .disabled(!can_commit || has_commit_model_configuration_error)
3942 .on_click(cx.listener(move |this, _event, _window, cx| {
3943 this.generate_commit_message(cx);
3944 }))
3945 .into_any_element(),
3946 )
3947 }
3948
3949 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3950 let potential_co_authors = self.potential_co_authors(cx);
3951
3952 let (tooltip_label, icon) = if self.add_coauthors {
3953 ("Remove co-authored-by", IconName::Person)
3954 } else {
3955 ("Add co-authored-by", IconName::UserCheck)
3956 };
3957
3958 if potential_co_authors.is_empty() {
3959 None
3960 } else {
3961 Some(
3962 IconButton::new("co-authors", icon)
3963 .shape(ui::IconButtonShape::Square)
3964 .icon_color(Color::Disabled)
3965 .selected_icon_color(Color::Selected)
3966 .toggle_state(self.add_coauthors)
3967 .tooltip(move |_, cx| {
3968 let title = format!(
3969 "{}:{}{}",
3970 tooltip_label,
3971 if potential_co_authors.len() == 1 {
3972 ""
3973 } else {
3974 "\n"
3975 },
3976 potential_co_authors
3977 .iter()
3978 .map(|(name, email)| format!(" {} <{}>", name, email))
3979 .join("\n")
3980 );
3981 Tooltip::simple(title, cx)
3982 })
3983 .on_click(cx.listener(|this, _, _, cx| {
3984 this.add_coauthors = !this.add_coauthors;
3985 cx.notify();
3986 }))
3987 .into_any_element(),
3988 )
3989 }
3990 }
3991
3992 fn render_git_commit_menu(
3993 &self,
3994 id: impl Into<ElementId>,
3995 keybinding_target: Option<FocusHandle>,
3996 cx: &mut Context<Self>,
3997 ) -> impl IntoElement {
3998 PopoverMenu::new(id.into())
3999 .trigger(
4000 ui::ButtonLike::new_rounded_right("commit-split-button-right")
4001 .layer(ui::ElevationIndex::ModalSurface)
4002 .size(ButtonSize::None)
4003 .child(
4004 h_flex()
4005 .px_1()
4006 .h_full()
4007 .justify_center()
4008 .border_l_1()
4009 .border_color(cx.theme().colors().border)
4010 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
4011 ),
4012 )
4013 .menu({
4014 let git_panel = cx.entity();
4015 let has_previous_commit = self.head_commit(cx).is_some();
4016 let amend = self.amend_pending();
4017 let signoff = self.signoff_enabled;
4018
4019 move |window, cx| {
4020 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
4021 context_menu
4022 .when_some(keybinding_target.clone(), |el, keybinding_target| {
4023 el.context(keybinding_target)
4024 })
4025 .when(has_previous_commit, |this| {
4026 this.toggleable_entry(
4027 "Amend",
4028 amend,
4029 IconPosition::Start,
4030 Some(Box::new(Amend)),
4031 {
4032 let git_panel = git_panel.downgrade();
4033 move |_, cx| {
4034 git_panel
4035 .update(cx, |git_panel, cx| {
4036 git_panel.toggle_amend_pending(cx);
4037 })
4038 .ok();
4039 }
4040 },
4041 )
4042 })
4043 .toggleable_entry(
4044 "Signoff",
4045 signoff,
4046 IconPosition::Start,
4047 Some(Box::new(Signoff)),
4048 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
4049 )
4050 }))
4051 }
4052 })
4053 .anchor(Corner::TopRight)
4054 }
4055
4056 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
4057 if self.has_unstaged_conflicts() {
4058 (false, "You must resolve conflicts before committing")
4059 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
4060 (false, "No changes to commit")
4061 } else if self.pending_commit.is_some() {
4062 (false, "Commit in progress")
4063 } else if !self.has_commit_message(cx) {
4064 (false, "No commit message")
4065 } else if !self.has_write_access(cx) {
4066 (false, "You do not have write access to this project")
4067 } else {
4068 (true, self.commit_button_title())
4069 }
4070 }
4071
4072 pub fn commit_button_title(&self) -> &'static str {
4073 if self.amend_pending {
4074 if self.has_staged_changes() {
4075 "Amend"
4076 } else if self.has_tracked_changes() {
4077 "Amend Tracked"
4078 } else {
4079 "Amend"
4080 }
4081 } else if self.has_staged_changes() {
4082 "Commit"
4083 } else {
4084 "Commit Tracked"
4085 }
4086 }
4087
4088 fn expand_commit_editor(
4089 &mut self,
4090 _: &git::ExpandCommitEditor,
4091 window: &mut Window,
4092 cx: &mut Context<Self>,
4093 ) {
4094 let workspace = self.workspace.clone();
4095 window.defer(cx, move |window, cx| {
4096 workspace
4097 .update(cx, |workspace, cx| {
4098 CommitModal::toggle(workspace, None, window, cx)
4099 })
4100 .ok();
4101 })
4102 }
4103
4104 fn render_panel_header(
4105 &self,
4106 window: &mut Window,
4107 cx: &mut Context<Self>,
4108 ) -> Option<impl IntoElement> {
4109 self.active_repository.as_ref()?;
4110
4111 let (text, action, stage, tooltip) =
4112 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
4113 ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
4114 } else {
4115 ("Stage All", StageAll.boxed_clone(), true, "git add --all")
4116 };
4117
4118 let change_string = match self.changes_count {
4119 0 => "No Changes".to_string(),
4120 1 => "1 Change".to_string(),
4121 count => format!("{} Changes", count),
4122 };
4123
4124 Some(
4125 self.panel_header_container(window, cx)
4126 .px_2()
4127 .justify_between()
4128 .child(
4129 panel_button(change_string)
4130 .color(Color::Muted)
4131 .tooltip(Tooltip::for_action_title_in(
4132 "Open Diff",
4133 &Diff,
4134 &self.focus_handle,
4135 ))
4136 .on_click(|_, _, cx| {
4137 cx.defer(|cx| {
4138 cx.dispatch_action(&Diff);
4139 })
4140 }),
4141 )
4142 .child(
4143 h_flex()
4144 .gap_1()
4145 .child(self.render_overflow_menu("overflow_menu"))
4146 .child(
4147 panel_filled_button(text)
4148 .tooltip(Tooltip::for_action_title_in(
4149 tooltip,
4150 action.as_ref(),
4151 &self.focus_handle,
4152 ))
4153 .disabled(self.entry_count == 0)
4154 .on_click({
4155 let git_panel = cx.weak_entity();
4156 move |_, _, cx| {
4157 git_panel
4158 .update(cx, |git_panel, cx| {
4159 git_panel.change_all_files_stage(stage, cx);
4160 })
4161 .ok();
4162 }
4163 }),
4164 ),
4165 ),
4166 )
4167 }
4168
4169 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
4170 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
4171 if !self.can_push_and_pull(cx) {
4172 return None;
4173 }
4174 Some(
4175 h_flex()
4176 .gap_1()
4177 .flex_shrink_0()
4178 .when_some(branch, |this, branch| {
4179 let focus_handle = Some(self.focus_handle(cx));
4180
4181 this.children(render_remote_button(
4182 "remote-button",
4183 &branch,
4184 focus_handle,
4185 true,
4186 ))
4187 })
4188 .into_any_element(),
4189 )
4190 }
4191
4192 pub fn render_footer(
4193 &self,
4194 window: &mut Window,
4195 cx: &mut Context<Self>,
4196 ) -> Option<impl IntoElement> {
4197 let active_repository = self.active_repository.clone()?;
4198 let panel_editor_style = panel_editor_style(true, window, cx);
4199 let enable_coauthors = self.render_co_authors(cx);
4200
4201 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4202 let expand_tooltip_focus_handle = editor_focus_handle;
4203
4204 let branch = active_repository.read(cx).branch.clone();
4205 let head_commit = active_repository.read(cx).head_commit.clone();
4206
4207 let footer_size = px(32.);
4208 let gap = px(9.0);
4209 let max_height = panel_editor_style
4210 .text
4211 .line_height_in_pixels(window.rem_size())
4212 * MAX_PANEL_EDITOR_LINES
4213 + gap;
4214
4215 let git_panel = cx.entity();
4216 let display_name = SharedString::from(Arc::from(
4217 active_repository
4218 .read(cx)
4219 .display_name()
4220 .trim_end_matches("/"),
4221 ));
4222 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4223 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4224 });
4225
4226 let footer = v_flex()
4227 .child(PanelRepoFooter::new(
4228 display_name,
4229 branch,
4230 head_commit,
4231 Some(git_panel),
4232 ))
4233 .child(
4234 panel_editor_container(window, cx)
4235 .id("commit-editor-container")
4236 .relative()
4237 .w_full()
4238 .h(max_height + footer_size)
4239 .border_t_1()
4240 .border_color(cx.theme().colors().border)
4241 .cursor_text()
4242 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4243 window.focus(&this.commit_editor.focus_handle(cx), cx);
4244 }))
4245 .child(
4246 h_flex()
4247 .id("commit-footer")
4248 .border_t_1()
4249 .when(editor_is_long, |el| {
4250 el.border_color(cx.theme().colors().border_variant)
4251 })
4252 .absolute()
4253 .bottom_0()
4254 .left_0()
4255 .w_full()
4256 .px_2()
4257 .h(footer_size)
4258 .flex_none()
4259 .justify_between()
4260 .child(
4261 self.render_generate_commit_message_button(cx)
4262 .unwrap_or_else(|| div().into_any_element()),
4263 )
4264 .child(
4265 h_flex()
4266 .gap_0p5()
4267 .children(enable_coauthors)
4268 .child(self.render_commit_button(cx)),
4269 ),
4270 )
4271 .child(
4272 div()
4273 .pr_2p5()
4274 .on_action(|&editor::actions::MoveUp, _, cx| {
4275 cx.stop_propagation();
4276 })
4277 .on_action(|&editor::actions::MoveDown, _, cx| {
4278 cx.stop_propagation();
4279 })
4280 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4281 )
4282 .child(
4283 h_flex()
4284 .absolute()
4285 .top_2()
4286 .right_2()
4287 .opacity(0.5)
4288 .hover(|this| this.opacity(1.0))
4289 .child(
4290 panel_icon_button("expand-commit-editor", IconName::Maximize)
4291 .icon_size(IconSize::Small)
4292 .size(ui::ButtonSize::Default)
4293 .tooltip(move |_window, cx| {
4294 Tooltip::for_action_in(
4295 "Open Commit Modal",
4296 &git::ExpandCommitEditor,
4297 &expand_tooltip_focus_handle,
4298 cx,
4299 )
4300 })
4301 .on_click(cx.listener({
4302 move |_, _, window, cx| {
4303 window.dispatch_action(
4304 git::ExpandCommitEditor.boxed_clone(),
4305 cx,
4306 )
4307 }
4308 })),
4309 ),
4310 ),
4311 );
4312
4313 Some(footer)
4314 }
4315
4316 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4317 let (can_commit, tooltip) = self.configure_commit_button(cx);
4318 let title = self.commit_button_title();
4319 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4320 let amend = self.amend_pending();
4321 let signoff = self.signoff_enabled;
4322
4323 let label_color = if self.pending_commit.is_some() {
4324 Color::Disabled
4325 } else {
4326 Color::Default
4327 };
4328
4329 div()
4330 .id("commit-wrapper")
4331 .on_hover(cx.listener(move |this, hovered, _, cx| {
4332 this.show_placeholders =
4333 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4334 cx.notify()
4335 }))
4336 .child(SplitButton::new(
4337 ButtonLike::new_rounded_left(ElementId::Name(
4338 format!("split-button-left-{}", title).into(),
4339 ))
4340 .layer(ElevationIndex::ModalSurface)
4341 .size(ButtonSize::Compact)
4342 .child(
4343 Label::new(title)
4344 .size(LabelSize::Small)
4345 .color(label_color)
4346 .mr_0p5(),
4347 )
4348 .on_click({
4349 let git_panel = cx.weak_entity();
4350 move |_, window, cx| {
4351 telemetry::event!("Git Committed", source = "Git Panel");
4352 git_panel
4353 .update(cx, |git_panel, cx| {
4354 git_panel.commit_changes(
4355 CommitOptions { amend, signoff },
4356 window,
4357 cx,
4358 );
4359 })
4360 .ok();
4361 }
4362 })
4363 .disabled(!can_commit || self.modal_open)
4364 .tooltip({
4365 let handle = commit_tooltip_focus_handle.clone();
4366 move |_window, cx| {
4367 if can_commit {
4368 Tooltip::with_meta_in(
4369 tooltip,
4370 Some(if amend { &git::Amend } else { &git::Commit }),
4371 format!(
4372 "git commit{}{}",
4373 if amend { " --amend" } else { "" },
4374 if signoff { " --signoff" } else { "" }
4375 ),
4376 &handle.clone(),
4377 cx,
4378 )
4379 } else {
4380 Tooltip::simple(tooltip, cx)
4381 }
4382 }
4383 }),
4384 self.render_git_commit_menu(
4385 ElementId::Name(format!("split-button-right-{}", title).into()),
4386 Some(commit_tooltip_focus_handle),
4387 cx,
4388 )
4389 .into_any_element(),
4390 ))
4391 }
4392
4393 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4394 h_flex()
4395 .py_1p5()
4396 .px_2()
4397 .gap_1p5()
4398 .justify_between()
4399 .border_t_1()
4400 .border_color(cx.theme().colors().border.opacity(0.8))
4401 .child(
4402 div()
4403 .flex_grow()
4404 .overflow_hidden()
4405 .max_w(relative(0.85))
4406 .child(
4407 Label::new("This will update your most recent commit.")
4408 .size(LabelSize::Small)
4409 .truncate(),
4410 ),
4411 )
4412 .child(
4413 panel_button("Cancel")
4414 .size(ButtonSize::Default)
4415 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4416 )
4417 }
4418
4419 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
4420 let active_repository = self.active_repository.as_ref()?;
4421 let branch = active_repository.read(cx).branch.as_ref()?;
4422 let commit = branch.most_recent_commit.as_ref()?.clone();
4423 let workspace = self.workspace.clone();
4424 let this = cx.entity();
4425
4426 Some(
4427 h_flex()
4428 .p_1p5()
4429 .gap_1p5()
4430 .justify_between()
4431 .border_t_1()
4432 .border_color(cx.theme().colors().border.opacity(0.8))
4433 .child(
4434 div()
4435 .id("commit-msg-hover")
4436 .px_1()
4437 .cursor_pointer()
4438 .line_clamp(1)
4439 .rounded_sm()
4440 .hover(|s| s.bg(cx.theme().colors().element_hover))
4441 .child(
4442 Label::new(commit.subject.clone())
4443 .size(LabelSize::Small)
4444 .truncate(),
4445 )
4446 .on_click({
4447 let commit = commit.clone();
4448 let repo = active_repository.downgrade();
4449 move |_, window, cx| {
4450 CommitView::open(
4451 commit.sha.to_string(),
4452 repo.clone(),
4453 workspace.clone(),
4454 None,
4455 None,
4456 window,
4457 cx,
4458 );
4459 }
4460 })
4461 .hoverable_tooltip({
4462 let repo = active_repository.clone();
4463 move |window, cx| {
4464 GitPanelMessageTooltip::new(
4465 this.clone(),
4466 commit.sha.clone(),
4467 repo.clone(),
4468 window,
4469 cx,
4470 )
4471 .into()
4472 }
4473 }),
4474 )
4475 .when(commit.has_parent, |this| {
4476 let has_unstaged = self.has_unstaged_changes();
4477 this.pr_2().child(
4478 panel_icon_button("undo", IconName::Undo)
4479 .icon_size(IconSize::XSmall)
4480 .icon_color(Color::Muted)
4481 .tooltip(move |_window, cx| {
4482 Tooltip::with_meta(
4483 "Uncommit",
4484 Some(&git::Uncommit),
4485 if has_unstaged {
4486 "git reset HEAD^ --soft"
4487 } else {
4488 "git reset HEAD^"
4489 },
4490 cx,
4491 )
4492 })
4493 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
4494 )
4495 }),
4496 )
4497 }
4498
4499 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4500 h_flex().h_full().flex_grow().justify_center().child(
4501 v_flex()
4502 .gap_2()
4503 .child(h_flex().w_full().justify_around().child(
4504 if self.active_repository.is_some() {
4505 "No changes to commit"
4506 } else {
4507 "No Git repositories"
4508 },
4509 ))
4510 .children({
4511 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4512 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
4513 h_flex().w_full().justify_around().child(
4514 panel_filled_button("Initialize Repository")
4515 .tooltip(Tooltip::for_action_title_in(
4516 "git init",
4517 &git::Init,
4518 &self.focus_handle,
4519 ))
4520 .on_click(move |_, _, cx| {
4521 cx.defer(move |cx| {
4522 cx.dispatch_action(&git::Init);
4523 })
4524 }),
4525 )
4526 })
4527 })
4528 .text_ui_sm(cx)
4529 .mx_auto()
4530 .text_color(Color::Placeholder.color(cx)),
4531 )
4532 }
4533
4534 fn render_buffer_header_controls(
4535 &self,
4536 entity: &Entity<Self>,
4537 file: &Arc<dyn File>,
4538 _: &Window,
4539 cx: &App,
4540 ) -> Option<AnyElement> {
4541 let repo = self.active_repository.as_ref()?.read(cx);
4542 let project_path = (file.worktree_id(cx), file.path().clone()).into();
4543 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4544 let ix = self.entry_by_path(&repo_path)?;
4545 let entry = self.entries.get(ix)?;
4546
4547 let is_staging_or_staged = repo
4548 .pending_ops_for_path(&repo_path)
4549 .map(|ops| ops.staging() || ops.staged())
4550 .or_else(|| {
4551 repo.status_for_path(&repo_path)
4552 .and_then(|status| status.status.staging().as_bool())
4553 })
4554 .or_else(|| {
4555 entry
4556 .status_entry()
4557 .and_then(|entry| entry.staging.as_bool())
4558 });
4559
4560 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4561 .disabled(!self.has_write_access(cx))
4562 .fill()
4563 .elevation(ElevationIndex::Surface)
4564 .on_click({
4565 let entry = entry.clone();
4566 let git_panel = entity.downgrade();
4567 move |_, window, cx| {
4568 git_panel
4569 .update(cx, |this, cx| {
4570 this.toggle_staged_for_entry(&entry, window, cx);
4571 cx.stop_propagation();
4572 })
4573 .ok();
4574 }
4575 });
4576 Some(
4577 h_flex()
4578 .id("start-slot")
4579 .text_lg()
4580 .child(checkbox)
4581 .on_mouse_down(MouseButton::Left, |_, _, cx| {
4582 // prevent the list item active state triggering when toggling checkbox
4583 cx.stop_propagation();
4584 })
4585 .into_any_element(),
4586 )
4587 }
4588
4589 fn render_entries(
4590 &self,
4591 has_write_access: bool,
4592 window: &mut Window,
4593 cx: &mut Context<Self>,
4594 ) -> impl IntoElement {
4595 let (is_tree_view, entry_count) = match &self.view_mode {
4596 GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4597 GitPanelViewMode::Flat => (false, self.entries.len()),
4598 };
4599
4600 v_flex()
4601 .flex_1()
4602 .size_full()
4603 .overflow_hidden()
4604 .relative()
4605 .child(
4606 h_flex()
4607 .flex_1()
4608 .size_full()
4609 .relative()
4610 .overflow_hidden()
4611 .child(
4612 uniform_list(
4613 "entries",
4614 entry_count,
4615 cx.processor(move |this, range: Range<usize>, window, cx| {
4616 let mut items = Vec::with_capacity(range.end - range.start);
4617
4618 for ix in range.into_iter().map(|ix| match &this.view_mode {
4619 GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4620 GitPanelViewMode::Flat => ix,
4621 }) {
4622 match &this.entries.get(ix) {
4623 Some(GitListEntry::Status(entry)) => {
4624 items.push(this.render_status_entry(
4625 ix,
4626 entry,
4627 0,
4628 has_write_access,
4629 window,
4630 cx,
4631 ));
4632 }
4633 Some(GitListEntry::TreeStatus(entry)) => {
4634 items.push(this.render_status_entry(
4635 ix,
4636 &entry.entry,
4637 entry.depth,
4638 has_write_access,
4639 window,
4640 cx,
4641 ));
4642 }
4643 Some(GitListEntry::Directory(entry)) => {
4644 items.push(this.render_directory_entry(
4645 ix,
4646 entry,
4647 has_write_access,
4648 window,
4649 cx,
4650 ));
4651 }
4652 Some(GitListEntry::Header(header)) => {
4653 items.push(this.render_list_header(
4654 ix,
4655 header,
4656 has_write_access,
4657 window,
4658 cx,
4659 ));
4660 }
4661 None => {}
4662 }
4663 }
4664
4665 items
4666 }),
4667 )
4668 .when(is_tree_view, |list| {
4669 let indent_size = px(TREE_INDENT);
4670 list.with_decoration(
4671 ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4672 .with_compute_indents_fn(
4673 cx.entity(),
4674 |this, range, _window, _cx| {
4675 range
4676 .map(|ix| match this.entries.get(ix) {
4677 Some(GitListEntry::Directory(dir)) => dir.depth,
4678 Some(GitListEntry::TreeStatus(status)) => {
4679 status.depth
4680 }
4681 _ => 0,
4682 })
4683 .collect()
4684 },
4685 )
4686 .with_render_fn(cx.entity(), |_, params, _, _| {
4687 // Magic number to align the tree item is 3 here
4688 // because we're using 12px as the left-side padding
4689 // and 3 makes the alignment work with the bounding box of the icon
4690 let left_offset = px(TREE_INDENT + 3_f32);
4691 let indent_size = params.indent_size;
4692 let item_height = params.item_height;
4693
4694 params
4695 .indent_guides
4696 .into_iter()
4697 .map(|layout| {
4698 let bounds = Bounds::new(
4699 point(
4700 layout.offset.x * indent_size + left_offset,
4701 layout.offset.y * item_height,
4702 ),
4703 size(px(1.), layout.length * item_height),
4704 );
4705 RenderedIndentGuide {
4706 bounds,
4707 layout,
4708 is_active: false,
4709 hitbox: None,
4710 }
4711 })
4712 .collect()
4713 }),
4714 )
4715 })
4716 .size_full()
4717 .flex_grow()
4718 .with_width_from_item(self.max_width_item_index)
4719 .track_scroll(&self.scroll_handle),
4720 )
4721 .on_mouse_down(
4722 MouseButton::Right,
4723 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4724 this.deploy_panel_context_menu(event.position, window, cx)
4725 }),
4726 )
4727 .custom_scrollbars(
4728 Scrollbars::for_settings::<GitPanelSettings>()
4729 .tracked_scroll_handle(&self.scroll_handle)
4730 .with_track_along(
4731 ScrollAxes::Horizontal,
4732 cx.theme().colors().panel_background,
4733 ),
4734 window,
4735 cx,
4736 ),
4737 )
4738 }
4739
4740 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4741 Label::new(label.into()).color(color)
4742 }
4743
4744 fn list_item_height(&self) -> Rems {
4745 rems(1.75)
4746 }
4747
4748 fn render_list_header(
4749 &self,
4750 ix: usize,
4751 header: &GitHeaderEntry,
4752 _: bool,
4753 _: &Window,
4754 _: &Context<Self>,
4755 ) -> AnyElement {
4756 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4757
4758 h_flex()
4759 .id(id)
4760 .h(self.list_item_height())
4761 .w_full()
4762 .items_end()
4763 .px_3()
4764 .pb_1()
4765 .child(
4766 Label::new(header.title())
4767 .color(Color::Muted)
4768 .size(LabelSize::Small)
4769 .line_height_style(LineHeightStyle::UiLabel)
4770 .single_line(),
4771 )
4772 .into_any_element()
4773 }
4774
4775 pub fn load_commit_details(
4776 &self,
4777 sha: String,
4778 cx: &mut Context<Self>,
4779 ) -> Task<anyhow::Result<CommitDetails>> {
4780 let Some(repo) = self.active_repository.clone() else {
4781 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4782 };
4783 repo.update(cx, |repo, cx| {
4784 let show = repo.show(sha);
4785 cx.spawn(async move |_, _| show.await?)
4786 })
4787 }
4788
4789 fn deploy_entry_context_menu(
4790 &mut self,
4791 position: Point<Pixels>,
4792 ix: usize,
4793 window: &mut Window,
4794 cx: &mut Context<Self>,
4795 ) {
4796 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4797 return;
4798 };
4799 let stage_title = if entry.status.staging().is_fully_staged() {
4800 "Unstage File"
4801 } else {
4802 "Stage File"
4803 };
4804 let restore_title = if entry.status.is_created() {
4805 "Trash File"
4806 } else {
4807 "Discard Changes"
4808 };
4809 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4810 let is_created = entry.status.is_created();
4811 context_menu
4812 .context(self.focus_handle.clone())
4813 .action(stage_title, ToggleStaged.boxed_clone())
4814 .action(restore_title, git::RestoreFile::default().boxed_clone())
4815 .action_disabled_when(
4816 !is_created,
4817 "Add to .gitignore",
4818 git::AddToGitignore.boxed_clone(),
4819 )
4820 .separator()
4821 .action("Open Diff", menu::Confirm.boxed_clone())
4822 .action("Open File", menu::SecondaryConfirm.boxed_clone())
4823 .separator()
4824 .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4825 });
4826 self.selected_entry = Some(ix);
4827 self.set_context_menu(context_menu, position, window, cx);
4828 }
4829
4830 fn deploy_panel_context_menu(
4831 &mut self,
4832 position: Point<Pixels>,
4833 window: &mut Window,
4834 cx: &mut Context<Self>,
4835 ) {
4836 let context_menu = git_panel_context_menu(
4837 self.focus_handle.clone(),
4838 GitMenuState {
4839 has_tracked_changes: self.has_tracked_changes(),
4840 has_staged_changes: self.has_staged_changes(),
4841 has_unstaged_changes: self.has_unstaged_changes(),
4842 has_new_changes: self.new_count > 0,
4843 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4844 has_stash_items: self.stash_entries.entries.len() > 0,
4845 tree_view: GitPanelSettings::get_global(cx).tree_view,
4846 },
4847 window,
4848 cx,
4849 );
4850 self.set_context_menu(context_menu, position, window, cx);
4851 }
4852
4853 fn set_context_menu(
4854 &mut self,
4855 context_menu: Entity<ContextMenu>,
4856 position: Point<Pixels>,
4857 window: &Window,
4858 cx: &mut Context<Self>,
4859 ) {
4860 let subscription = cx.subscribe_in(
4861 &context_menu,
4862 window,
4863 |this, _, _: &DismissEvent, window, cx| {
4864 if this.context_menu.as_ref().is_some_and(|context_menu| {
4865 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4866 }) {
4867 cx.focus_self(window);
4868 }
4869 this.context_menu.take();
4870 cx.notify();
4871 },
4872 );
4873 self.context_menu = Some((context_menu, position, subscription));
4874 cx.notify();
4875 }
4876
4877 fn render_status_entry(
4878 &self,
4879 ix: usize,
4880 entry: &GitStatusEntry,
4881 depth: usize,
4882 has_write_access: bool,
4883 window: &Window,
4884 cx: &Context<Self>,
4885 ) -> AnyElement {
4886 let tree_view = GitPanelSettings::get_global(cx).tree_view;
4887 let path_style = self.project.read(cx).path_style(cx);
4888 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
4889 let display_name = entry.display_name(path_style);
4890
4891 let selected = self.selected_entry == Some(ix);
4892 let marked = self.marked_entries.contains(&ix);
4893 let status_style = GitPanelSettings::get_global(cx).status_style;
4894 let status = entry.status;
4895
4896 let has_conflict = status.is_conflicted();
4897 let is_modified = status.is_modified();
4898 let is_deleted = status.is_deleted();
4899 let is_created = status.is_created();
4900
4901 let label_color = if status_style == StatusStyle::LabelColor {
4902 if has_conflict {
4903 Color::VersionControlConflict
4904 } else if is_created {
4905 Color::VersionControlAdded
4906 } else if is_modified {
4907 Color::VersionControlModified
4908 } else if is_deleted {
4909 // We don't want a bunch of red labels in the list
4910 Color::Disabled
4911 } else {
4912 Color::VersionControlAdded
4913 }
4914 } else {
4915 Color::Default
4916 };
4917
4918 let path_color = if status.is_deleted() {
4919 Color::Disabled
4920 } else {
4921 Color::Muted
4922 };
4923
4924 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4925 let checkbox_wrapper_id: ElementId =
4926 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4927 let checkbox_id: ElementId =
4928 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4929
4930 let active_repo = self
4931 .project
4932 .read(cx)
4933 .active_repository(cx)
4934 .expect("active repository must be set");
4935 let repo = active_repo.read(cx);
4936 let stage_status = GitPanel::stage_status_for_entry(entry, &repo);
4937 let mut is_staged: ToggleState = match stage_status {
4938 StageStatus::Staged => ToggleState::Selected,
4939 StageStatus::Unstaged => ToggleState::Unselected,
4940 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
4941 };
4942 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4943 is_staged = ToggleState::Selected;
4944 }
4945
4946 let handle = cx.weak_entity();
4947
4948 let selected_bg_alpha = 0.08;
4949 let marked_bg_alpha = 0.12;
4950 let state_opacity_step = 0.04;
4951
4952 let info_color = cx.theme().status().info;
4953
4954 let base_bg = match (selected, marked) {
4955 (true, true) => info_color.alpha(selected_bg_alpha + marked_bg_alpha),
4956 (true, false) => info_color.alpha(selected_bg_alpha),
4957 (false, true) => info_color.alpha(marked_bg_alpha),
4958 _ => cx.theme().colors().ghost_element_background,
4959 };
4960
4961 let (hover_bg, active_bg) = if selected {
4962 (
4963 info_color.alpha(selected_bg_alpha + state_opacity_step),
4964 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
4965 )
4966 } else {
4967 (
4968 cx.theme().colors().ghost_element_hover,
4969 cx.theme().colors().ghost_element_active,
4970 )
4971 };
4972
4973 let name_row = h_flex()
4974 .min_w_0()
4975 .flex_1()
4976 .gap_1()
4977 .child(git_status_icon(status))
4978 .map(|this| {
4979 if tree_view {
4980 this.pl(px(depth as f32 * TREE_INDENT)).child(
4981 self.entry_label(display_name, label_color)
4982 .when(status.is_deleted(), Label::strikethrough)
4983 .truncate(),
4984 )
4985 } else {
4986 this.child(self.path_formatted(
4987 entry.parent_dir(path_style),
4988 path_color,
4989 display_name,
4990 label_color,
4991 path_style,
4992 git_path_style,
4993 status.is_deleted(),
4994 ))
4995 }
4996 });
4997
4998 h_flex()
4999 .id(id)
5000 .h(self.list_item_height())
5001 .w_full()
5002 .pl_3()
5003 .pr_1()
5004 .gap_1p5()
5005 .border_1()
5006 .border_r_2()
5007 .when(selected && self.focus_handle.is_focused(window), |el| {
5008 el.border_color(cx.theme().colors().panel_focused_border)
5009 })
5010 .bg(base_bg)
5011 .hover(|s| s.bg(hover_bg))
5012 .active(|s| s.bg(active_bg))
5013 .child(name_row)
5014 .child(
5015 div()
5016 .id(checkbox_wrapper_id)
5017 .flex_none()
5018 .occlude()
5019 .cursor_pointer()
5020 .child(
5021 Checkbox::new(checkbox_id, is_staged)
5022 .disabled(!has_write_access)
5023 .fill()
5024 .elevation(ElevationIndex::Surface)
5025 .on_click_ext({
5026 let entry = entry.clone();
5027 let this = cx.weak_entity();
5028 move |_, click, window, cx| {
5029 this.update(cx, |this, cx| {
5030 if !has_write_access {
5031 return;
5032 }
5033 if click.modifiers().shift {
5034 this.stage_bulk(ix, cx);
5035 } else {
5036 let list_entry =
5037 if GitPanelSettings::get_global(cx).tree_view {
5038 GitListEntry::TreeStatus(GitTreeStatusEntry {
5039 entry: entry.clone(),
5040 depth,
5041 })
5042 } else {
5043 GitListEntry::Status(entry.clone())
5044 };
5045 this.toggle_staged_for_entry(&list_entry, window, cx);
5046 }
5047 cx.stop_propagation();
5048 })
5049 .ok();
5050 }
5051 })
5052 .tooltip(move |_window, cx| {
5053 let action = match stage_status {
5054 StageStatus::Staged => "Unstage",
5055 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5056 };
5057 let tooltip_name = action.to_string();
5058
5059 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
5060 }),
5061 ),
5062 )
5063 .on_click({
5064 cx.listener(move |this, event: &ClickEvent, window, cx| {
5065 this.selected_entry = Some(ix);
5066 cx.notify();
5067 if event.modifiers().secondary() {
5068 this.open_file(&Default::default(), window, cx)
5069 } else {
5070 this.open_diff(&Default::default(), window, cx);
5071 this.focus_handle.focus(window, cx);
5072 }
5073 })
5074 })
5075 .on_mouse_down(
5076 MouseButton::Right,
5077 move |event: &MouseDownEvent, window, cx| {
5078 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
5079 if event.button != MouseButton::Right {
5080 return;
5081 }
5082
5083 let Some(this) = handle.upgrade() else {
5084 return;
5085 };
5086 this.update(cx, |this, cx| {
5087 this.deploy_entry_context_menu(event.position, ix, window, cx);
5088 });
5089 cx.stop_propagation();
5090 },
5091 )
5092 .into_any_element()
5093 }
5094
5095 fn render_directory_entry(
5096 &self,
5097 ix: usize,
5098 entry: &GitTreeDirEntry,
5099 has_write_access: bool,
5100 window: &Window,
5101 cx: &Context<Self>,
5102 ) -> AnyElement {
5103 // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
5104 let selected = self.selected_entry == Some(ix);
5105 let label_color = Color::Muted;
5106
5107 let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
5108 let checkbox_id: ElementId =
5109 ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
5110 let checkbox_wrapper_id: ElementId =
5111 ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
5112
5113 let selected_bg_alpha = 0.08;
5114 let state_opacity_step = 0.04;
5115
5116 let info_color = cx.theme().status().info;
5117 let colors = cx.theme().colors();
5118
5119 let (base_bg, hover_bg, active_bg) = if selected {
5120 (
5121 info_color.alpha(selected_bg_alpha),
5122 info_color.alpha(selected_bg_alpha + state_opacity_step),
5123 info_color.alpha(selected_bg_alpha + state_opacity_step * 2.0),
5124 )
5125 } else {
5126 (
5127 colors.ghost_element_background,
5128 colors.ghost_element_hover,
5129 colors.ghost_element_active,
5130 )
5131 };
5132
5133 let folder_icon = if entry.expanded {
5134 IconName::FolderOpen
5135 } else {
5136 IconName::Folder
5137 };
5138
5139 let stage_status = if let Some(repo) = &self.active_repository {
5140 self.stage_status_for_directory(entry, repo.read(cx))
5141 } else {
5142 util::debug_panic!(
5143 "Won't have entries to render without an active repository in Git Panel"
5144 );
5145 StageStatus::PartiallyStaged
5146 };
5147
5148 let toggle_state: ToggleState = match stage_status {
5149 StageStatus::Staged => ToggleState::Selected,
5150 StageStatus::Unstaged => ToggleState::Unselected,
5151 StageStatus::PartiallyStaged => ToggleState::Indeterminate,
5152 };
5153
5154 let name_row = h_flex()
5155 .min_w_0()
5156 .gap_1()
5157 .pl(px(entry.depth as f32 * TREE_INDENT))
5158 .child(
5159 Icon::new(folder_icon)
5160 .size(IconSize::Small)
5161 .color(Color::Muted),
5162 )
5163 .child(self.entry_label(entry.name.clone(), label_color).truncate());
5164
5165 h_flex()
5166 .id(id)
5167 .h(self.list_item_height())
5168 .min_w_0()
5169 .w_full()
5170 .pl_3()
5171 .pr_1()
5172 .gap_1p5()
5173 .justify_between()
5174 .border_1()
5175 .border_r_2()
5176 .when(selected && self.focus_handle.is_focused(window), |el| {
5177 el.border_color(cx.theme().colors().panel_focused_border)
5178 })
5179 .bg(base_bg)
5180 .hover(|s| s.bg(hover_bg))
5181 .active(|s| s.bg(active_bg))
5182 .child(name_row)
5183 .child(
5184 div()
5185 .id(checkbox_wrapper_id)
5186 .flex_none()
5187 .occlude()
5188 .cursor_pointer()
5189 .child(
5190 Checkbox::new(checkbox_id, toggle_state)
5191 .disabled(!has_write_access)
5192 .fill()
5193 .elevation(ElevationIndex::Surface)
5194 .on_click({
5195 let entry = entry.clone();
5196 let this = cx.weak_entity();
5197 move |_, window, cx| {
5198 this.update(cx, |this, cx| {
5199 if !has_write_access {
5200 return;
5201 }
5202 this.toggle_staged_for_entry(
5203 &GitListEntry::Directory(entry.clone()),
5204 window,
5205 cx,
5206 );
5207 cx.stop_propagation();
5208 })
5209 .ok();
5210 }
5211 })
5212 .tooltip(move |_window, cx| {
5213 let action = match stage_status {
5214 StageStatus::Staged => "Unstage",
5215 StageStatus::Unstaged | StageStatus::PartiallyStaged => "Stage",
5216 };
5217 Tooltip::simple(format!("{action} folder"), cx)
5218 }),
5219 ),
5220 )
5221 .on_click({
5222 let key = entry.key.clone();
5223 cx.listener(move |this, _event: &ClickEvent, window, cx| {
5224 this.selected_entry = Some(ix);
5225 this.toggle_directory(&key, window, cx);
5226 })
5227 })
5228 .into_any_element()
5229 }
5230
5231 fn path_formatted(
5232 &self,
5233 directory: Option<String>,
5234 path_color: Color,
5235 file_name: String,
5236 label_color: Color,
5237 path_style: PathStyle,
5238 git_path_style: GitPathStyle,
5239 strikethrough: bool,
5240 ) -> Div {
5241 let file_name_first = git_path_style == GitPathStyle::FileNameFirst;
5242 let file_path_first = git_path_style == GitPathStyle::FilePathFirst;
5243
5244 let file_name = format!("{} ", file_name);
5245
5246 h_flex()
5247 .min_w_0()
5248 .overflow_hidden()
5249 .when(file_path_first, |this| this.flex_row_reverse())
5250 .child(
5251 div().flex_none().child(
5252 self.entry_label(file_name, label_color)
5253 .when(strikethrough, Label::strikethrough),
5254 ),
5255 )
5256 .when_some(directory, |this, dir| {
5257 let path_name = if file_name_first {
5258 dir
5259 } else {
5260 format!("{dir}{}", path_style.primary_separator())
5261 };
5262
5263 this.child(
5264 self.entry_label(path_name, path_color)
5265 .truncate_start()
5266 .when(strikethrough, Label::strikethrough),
5267 )
5268 })
5269 }
5270
5271 fn has_write_access(&self, cx: &App) -> bool {
5272 !self.project.read(cx).is_read_only(cx)
5273 }
5274
5275 pub fn amend_pending(&self) -> bool {
5276 self.amend_pending
5277 }
5278
5279 /// Sets the pending amend state, ensuring that the original commit message
5280 /// is either saved, when `value` is `true` and there's no pending amend, or
5281 /// restored, when `value` is `false` and there's a pending amend.
5282 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5283 if value && !self.amend_pending {
5284 let current_message = self.commit_message_buffer(cx).read(cx).text();
5285 self.original_commit_message = if current_message.trim().is_empty() {
5286 None
5287 } else {
5288 Some(current_message)
5289 };
5290 } else if !value && self.amend_pending {
5291 let message = self.original_commit_message.take().unwrap_or_default();
5292 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5293 let start = buffer.anchor_before(0);
5294 let end = buffer.anchor_after(buffer.len());
5295 buffer.edit([(start..end, message)], None, cx);
5296 });
5297 }
5298
5299 self.amend_pending = value;
5300 self.serialize(cx);
5301 cx.notify();
5302 }
5303
5304 pub fn signoff_enabled(&self) -> bool {
5305 self.signoff_enabled
5306 }
5307
5308 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5309 self.signoff_enabled = value;
5310 self.serialize(cx);
5311 cx.notify();
5312 }
5313
5314 pub fn toggle_signoff_enabled(
5315 &mut self,
5316 _: &Signoff,
5317 _window: &mut Window,
5318 cx: &mut Context<Self>,
5319 ) {
5320 self.set_signoff_enabled(!self.signoff_enabled, cx);
5321 }
5322
5323 pub async fn load(
5324 workspace: WeakEntity<Workspace>,
5325 mut cx: AsyncWindowContext,
5326 ) -> anyhow::Result<Entity<Self>> {
5327 let serialized_panel = match workspace
5328 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
5329 .ok()
5330 .flatten()
5331 {
5332 Some(serialization_key) => cx
5333 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
5334 .await
5335 .context("loading git panel")
5336 .log_err()
5337 .flatten()
5338 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5339 .transpose()
5340 .log_err()
5341 .flatten(),
5342 None => None,
5343 };
5344
5345 workspace.update_in(&mut cx, |workspace, window, cx| {
5346 let panel = GitPanel::new(workspace, window, cx);
5347
5348 if let Some(serialized_panel) = serialized_panel {
5349 panel.update(cx, |panel, cx| {
5350 panel.width = serialized_panel.width;
5351 panel.amend_pending = serialized_panel.amend_pending;
5352 panel.signoff_enabled = serialized_panel.signoff_enabled;
5353 cx.notify();
5354 })
5355 }
5356
5357 panel
5358 })
5359 }
5360
5361 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5362 let Some(op) = self.bulk_staging.as_ref() else {
5363 return;
5364 };
5365 let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5366 return;
5367 };
5368 if let Some(entry) = self.entries.get(index)
5369 && let Some(entry) = entry.status_entry()
5370 {
5371 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5372 }
5373 if index < anchor_index {
5374 std::mem::swap(&mut index, &mut anchor_index);
5375 }
5376 let entries = self
5377 .entries
5378 .get(anchor_index..=index)
5379 .unwrap_or_default()
5380 .iter()
5381 .filter_map(|entry| entry.status_entry().cloned())
5382 .collect::<Vec<_>>();
5383 self.change_file_stage(true, entries, cx);
5384 }
5385
5386 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5387 let Some(repo) = self.active_repository.as_ref() else {
5388 return;
5389 };
5390 self.bulk_staging = Some(BulkStaging {
5391 repo_id: repo.read(cx).id,
5392 anchor: path,
5393 });
5394 }
5395
5396 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5397 self.set_amend_pending(!self.amend_pending, cx);
5398 if self.amend_pending {
5399 self.load_last_commit_message(cx);
5400 }
5401 }
5402}
5403
5404impl Render for GitPanel {
5405 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5406 let project = self.project.read(cx);
5407 let has_entries = !self.entries.is_empty();
5408 let room = self
5409 .workspace
5410 .upgrade()
5411 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
5412
5413 let has_write_access = self.has_write_access(cx);
5414
5415 let has_co_authors = room.is_some_and(|room| {
5416 self.load_local_committer(cx);
5417 let room = room.read(cx);
5418 room.remote_participants()
5419 .values()
5420 .any(|remote_participant| remote_participant.can_write())
5421 });
5422
5423 v_flex()
5424 .id("git_panel")
5425 .key_context(self.dispatch_context(window, cx))
5426 .track_focus(&self.focus_handle)
5427 .when(has_write_access && !project.is_read_only(cx), |this| {
5428 this.on_action(cx.listener(Self::toggle_staged_for_selected))
5429 .on_action(cx.listener(Self::stage_range))
5430 .on_action(cx.listener(GitPanel::on_commit))
5431 .on_action(cx.listener(GitPanel::on_amend))
5432 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5433 .on_action(cx.listener(Self::stage_all))
5434 .on_action(cx.listener(Self::unstage_all))
5435 .on_action(cx.listener(Self::stage_selected))
5436 .on_action(cx.listener(Self::unstage_selected))
5437 .on_action(cx.listener(Self::restore_tracked_files))
5438 .on_action(cx.listener(Self::revert_selected))
5439 .on_action(cx.listener(Self::add_to_gitignore))
5440 .on_action(cx.listener(Self::clean_all))
5441 .on_action(cx.listener(Self::generate_commit_message_action))
5442 .on_action(cx.listener(Self::stash_all))
5443 .on_action(cx.listener(Self::stash_pop))
5444 })
5445 .on_action(cx.listener(Self::collapse_selected_entry))
5446 .on_action(cx.listener(Self::expand_selected_entry))
5447 .on_action(cx.listener(Self::select_first))
5448 .on_action(cx.listener(Self::select_next))
5449 .on_action(cx.listener(Self::select_previous))
5450 .on_action(cx.listener(Self::select_last))
5451 .on_action(cx.listener(Self::first_entry))
5452 .on_action(cx.listener(Self::next_entry))
5453 .on_action(cx.listener(Self::previous_entry))
5454 .on_action(cx.listener(Self::last_entry))
5455 .on_action(cx.listener(Self::close_panel))
5456 .on_action(cx.listener(Self::open_diff))
5457 .on_action(cx.listener(Self::open_file))
5458 .on_action(cx.listener(Self::file_history))
5459 .on_action(cx.listener(Self::focus_changes_list))
5460 .on_action(cx.listener(Self::focus_editor))
5461 .on_action(cx.listener(Self::expand_commit_editor))
5462 .when(has_write_access && has_co_authors, |git_panel| {
5463 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5464 })
5465 .on_action(cx.listener(Self::toggle_sort_by_path))
5466 .on_action(cx.listener(Self::toggle_tree_view))
5467 .size_full()
5468 .overflow_hidden()
5469 .bg(cx.theme().colors().panel_background)
5470 .child(
5471 v_flex()
5472 .size_full()
5473 .children(self.render_panel_header(window, cx))
5474 .map(|this| {
5475 if has_entries {
5476 this.child(self.render_entries(has_write_access, window, cx))
5477 } else {
5478 this.child(self.render_empty_state(cx).into_any_element())
5479 }
5480 })
5481 .children(self.render_footer(window, cx))
5482 .when(self.amend_pending, |this| {
5483 this.child(self.render_pending_amend(cx))
5484 })
5485 .when(!self.amend_pending, |this| {
5486 this.children(self.render_previous_commit(cx))
5487 })
5488 .into_any_element(),
5489 )
5490 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5491 deferred(
5492 anchored()
5493 .position(*position)
5494 .anchor(Corner::TopLeft)
5495 .child(menu.clone()),
5496 )
5497 .with_priority(1)
5498 }))
5499 }
5500}
5501
5502impl Focusable for GitPanel {
5503 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5504 if self.entries.is_empty() {
5505 self.commit_editor.focus_handle(cx)
5506 } else {
5507 self.focus_handle.clone()
5508 }
5509 }
5510}
5511
5512impl EventEmitter<Event> for GitPanel {}
5513
5514impl EventEmitter<PanelEvent> for GitPanel {}
5515
5516pub(crate) struct GitPanelAddon {
5517 pub(crate) workspace: WeakEntity<Workspace>,
5518}
5519
5520impl editor::Addon for GitPanelAddon {
5521 fn to_any(&self) -> &dyn std::any::Any {
5522 self
5523 }
5524
5525 fn render_buffer_header_controls(
5526 &self,
5527 excerpt_info: &ExcerptInfo,
5528 window: &Window,
5529 cx: &App,
5530 ) -> Option<AnyElement> {
5531 let file = excerpt_info.buffer.file()?;
5532 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5533
5534 git_panel
5535 .read(cx)
5536 .render_buffer_header_controls(&git_panel, file, window, cx)
5537 }
5538}
5539
5540impl Panel for GitPanel {
5541 fn persistent_name() -> &'static str {
5542 "GitPanel"
5543 }
5544
5545 fn panel_key() -> &'static str {
5546 GIT_PANEL_KEY
5547 }
5548
5549 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5550 GitPanelSettings::get_global(cx).dock
5551 }
5552
5553 fn position_is_valid(&self, position: DockPosition) -> bool {
5554 matches!(position, DockPosition::Left | DockPosition::Right)
5555 }
5556
5557 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5558 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5559 settings.git_panel.get_or_insert_default().dock = Some(position.into())
5560 });
5561 }
5562
5563 fn size(&self, _: &Window, cx: &App) -> Pixels {
5564 self.width
5565 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
5566 }
5567
5568 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
5569 self.width = size;
5570 self.serialize(cx);
5571 cx.notify();
5572 }
5573
5574 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5575 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5576 }
5577
5578 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5579 Some("Git Panel")
5580 }
5581
5582 fn toggle_action(&self) -> Box<dyn Action> {
5583 Box::new(ToggleFocus)
5584 }
5585
5586 fn activation_priority(&self) -> u32 {
5587 2
5588 }
5589}
5590
5591impl PanelHeader for GitPanel {}
5592
5593struct GitPanelMessageTooltip {
5594 commit_tooltip: Option<Entity<CommitTooltip>>,
5595}
5596
5597impl GitPanelMessageTooltip {
5598 fn new(
5599 git_panel: Entity<GitPanel>,
5600 sha: SharedString,
5601 repository: Entity<Repository>,
5602 window: &mut Window,
5603 cx: &mut App,
5604 ) -> Entity<Self> {
5605 let remote_url = repository.read(cx).default_remote_url();
5606 cx.new(|cx| {
5607 cx.spawn_in(window, async move |this, cx| {
5608 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5609 (
5610 git_panel.load_commit_details(sha.to_string(), cx),
5611 git_panel.workspace.clone(),
5612 )
5613 });
5614 let details = details.await?;
5615 let provider_registry = cx
5616 .update(|_, app| GitHostingProviderRegistry::default_global(app))
5617 .ok();
5618
5619 let commit_details = crate::commit_tooltip::CommitDetails {
5620 sha: details.sha.clone(),
5621 author_name: details.author_name.clone(),
5622 author_email: details.author_email.clone(),
5623 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5624 message: Some(ParsedCommitMessage::parse(
5625 details.sha.to_string(),
5626 details.message.to_string(),
5627 remote_url.as_deref(),
5628 provider_registry,
5629 )),
5630 };
5631
5632 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5633 this.commit_tooltip = Some(cx.new(move |cx| {
5634 CommitTooltip::new(commit_details, repository, workspace, cx)
5635 }));
5636 cx.notify();
5637 })
5638 })
5639 .detach();
5640
5641 Self {
5642 commit_tooltip: None,
5643 }
5644 })
5645 }
5646}
5647
5648impl Render for GitPanelMessageTooltip {
5649 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5650 if let Some(commit_tooltip) = &self.commit_tooltip {
5651 commit_tooltip.clone().into_any_element()
5652 } else {
5653 gpui::Empty.into_any_element()
5654 }
5655 }
5656}
5657
5658#[derive(IntoElement, RegisterComponent)]
5659pub struct PanelRepoFooter {
5660 active_repository: SharedString,
5661 branch: Option<Branch>,
5662 head_commit: Option<CommitDetails>,
5663
5664 // Getting a GitPanel in previews will be difficult.
5665 //
5666 // For now just take an option here, and we won't bind handlers to buttons in previews.
5667 git_panel: Option<Entity<GitPanel>>,
5668}
5669
5670impl PanelRepoFooter {
5671 pub fn new(
5672 active_repository: SharedString,
5673 branch: Option<Branch>,
5674 head_commit: Option<CommitDetails>,
5675 git_panel: Option<Entity<GitPanel>>,
5676 ) -> Self {
5677 Self {
5678 active_repository,
5679 branch,
5680 head_commit,
5681 git_panel,
5682 }
5683 }
5684
5685 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5686 Self {
5687 active_repository,
5688 branch,
5689 head_commit: None,
5690 git_panel: None,
5691 }
5692 }
5693}
5694
5695impl RenderOnce for PanelRepoFooter {
5696 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5697 let project = self
5698 .git_panel
5699 .as_ref()
5700 .map(|panel| panel.read(cx).project.clone());
5701
5702 let (workspace, repo) = self
5703 .git_panel
5704 .as_ref()
5705 .map(|panel| {
5706 let panel = panel.read(cx);
5707 (panel.workspace.clone(), panel.active_repository.clone())
5708 })
5709 .unzip();
5710
5711 let single_repo = project
5712 .as_ref()
5713 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5714 .unwrap_or(true);
5715
5716 const MAX_BRANCH_LEN: usize = 16;
5717 const MAX_REPO_LEN: usize = 16;
5718 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
5719 const MAX_SHORT_SHA_LEN: usize = 8;
5720 let branch_name = self
5721 .branch
5722 .as_ref()
5723 .map(|branch| branch.name().to_owned())
5724 .or_else(|| {
5725 self.head_commit.as_ref().map(|commit| {
5726 commit
5727 .sha
5728 .chars()
5729 .take(MAX_SHORT_SHA_LEN)
5730 .collect::<String>()
5731 })
5732 })
5733 .unwrap_or_else(|| " (no branch)".to_owned());
5734 let show_separator = self.branch.is_some() || self.head_commit.is_some();
5735
5736 let active_repo_name = self.active_repository.clone();
5737
5738 let branch_actual_len = branch_name.len();
5739 let repo_actual_len = active_repo_name.len();
5740
5741 // ideally, show the whole branch and repo names but
5742 // when we can't, use a budget to allocate space between the two
5743 let (repo_display_len, branch_display_len) =
5744 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
5745 (repo_actual_len, branch_actual_len)
5746 } else if branch_actual_len <= MAX_BRANCH_LEN {
5747 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
5748 (repo_space, branch_actual_len)
5749 } else if repo_actual_len <= MAX_REPO_LEN {
5750 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
5751 (repo_actual_len, branch_space)
5752 } else {
5753 (MAX_REPO_LEN, MAX_BRANCH_LEN)
5754 };
5755
5756 let truncated_repo_name = if repo_actual_len <= repo_display_len {
5757 active_repo_name.to_string()
5758 } else {
5759 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
5760 };
5761
5762 let truncated_branch_name = if branch_actual_len <= branch_display_len {
5763 branch_name
5764 } else {
5765 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
5766 };
5767
5768 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
5769 .size(ButtonSize::None)
5770 .label_size(LabelSize::Small)
5771 .color(Color::Muted);
5772
5773 let repo_selector = PopoverMenu::new("repository-switcher")
5774 .menu({
5775 let project = project;
5776 move |window, cx| {
5777 let project = project.clone()?;
5778 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
5779 }
5780 })
5781 .trigger_with_tooltip(
5782 repo_selector_trigger.disabled(single_repo).truncate(true),
5783 Tooltip::text("Switch Active Repository"),
5784 )
5785 .anchor(Corner::BottomLeft)
5786 .into_any_element();
5787
5788 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
5789 .size(ButtonSize::None)
5790 .label_size(LabelSize::Small)
5791 .truncate(true)
5792 .on_click(|_, window, cx| {
5793 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
5794 });
5795
5796 let branch_selector = PopoverMenu::new("popover-button")
5797 .menu(move |window, cx| {
5798 let workspace = workspace.clone()?;
5799 let repo = repo.clone().flatten();
5800 Some(branch_picker::popover(workspace, false, repo, window, cx))
5801 })
5802 .trigger_with_tooltip(
5803 branch_selector_button,
5804 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
5805 )
5806 .anchor(Corner::BottomLeft)
5807 .offset(gpui::Point {
5808 x: px(0.0),
5809 y: px(-2.0),
5810 });
5811
5812 h_flex()
5813 .h(px(36.))
5814 .w_full()
5815 .px_2()
5816 .justify_between()
5817 .gap_1()
5818 .child(
5819 h_flex()
5820 .flex_1()
5821 .overflow_hidden()
5822 .gap_px()
5823 .child(
5824 Icon::new(IconName::GitBranchAlt)
5825 .size(IconSize::Small)
5826 .color(if single_repo {
5827 Color::Disabled
5828 } else {
5829 Color::Muted
5830 }),
5831 )
5832 .child(repo_selector)
5833 .when(show_separator, |this| {
5834 this.child(
5835 div()
5836 .text_sm()
5837 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
5838 .child("/"),
5839 )
5840 })
5841 .child(branch_selector),
5842 )
5843 .children(if let Some(git_panel) = self.git_panel {
5844 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
5845 } else {
5846 None
5847 })
5848 }
5849}
5850
5851impl Component for PanelRepoFooter {
5852 fn scope() -> ComponentScope {
5853 ComponentScope::VersionControl
5854 }
5855
5856 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
5857 let unknown_upstream = None;
5858 let no_remote_upstream = Some(UpstreamTracking::Gone);
5859 let ahead_of_upstream = Some(
5860 UpstreamTrackingStatus {
5861 ahead: 2,
5862 behind: 0,
5863 }
5864 .into(),
5865 );
5866 let behind_upstream = Some(
5867 UpstreamTrackingStatus {
5868 ahead: 0,
5869 behind: 2,
5870 }
5871 .into(),
5872 );
5873 let ahead_and_behind_upstream = Some(
5874 UpstreamTrackingStatus {
5875 ahead: 3,
5876 behind: 1,
5877 }
5878 .into(),
5879 );
5880
5881 let not_ahead_or_behind_upstream = Some(
5882 UpstreamTrackingStatus {
5883 ahead: 0,
5884 behind: 0,
5885 }
5886 .into(),
5887 );
5888
5889 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
5890 Branch {
5891 is_head: true,
5892 ref_name: "some-branch".into(),
5893 upstream: upstream.map(|tracking| Upstream {
5894 ref_name: "origin/some-branch".into(),
5895 tracking,
5896 }),
5897 most_recent_commit: Some(CommitSummary {
5898 sha: "abc123".into(),
5899 subject: "Modify stuff".into(),
5900 commit_timestamp: 1710932954,
5901 author_name: "John Doe".into(),
5902 has_parent: true,
5903 }),
5904 }
5905 }
5906
5907 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
5908 Branch {
5909 is_head: true,
5910 ref_name: branch_name.to_string().into(),
5911 upstream: upstream.map(|tracking| Upstream {
5912 ref_name: format!("zed/{}", branch_name).into(),
5913 tracking,
5914 }),
5915 most_recent_commit: Some(CommitSummary {
5916 sha: "abc123".into(),
5917 subject: "Modify stuff".into(),
5918 commit_timestamp: 1710932954,
5919 author_name: "John Doe".into(),
5920 has_parent: true,
5921 }),
5922 }
5923 }
5924
5925 fn active_repository(id: usize) -> SharedString {
5926 format!("repo-{}", id).into()
5927 }
5928
5929 let example_width = px(340.);
5930 Some(
5931 v_flex()
5932 .gap_6()
5933 .w_full()
5934 .flex_none()
5935 .children(vec![
5936 example_group_with_title(
5937 "Action Button States",
5938 vec![
5939 single_example(
5940 "No Branch",
5941 div()
5942 .w(example_width)
5943 .overflow_hidden()
5944 .child(PanelRepoFooter::new_preview(active_repository(1), None))
5945 .into_any_element(),
5946 ),
5947 single_example(
5948 "Remote status unknown",
5949 div()
5950 .w(example_width)
5951 .overflow_hidden()
5952 .child(PanelRepoFooter::new_preview(
5953 active_repository(2),
5954 Some(branch(unknown_upstream)),
5955 ))
5956 .into_any_element(),
5957 ),
5958 single_example(
5959 "No Remote Upstream",
5960 div()
5961 .w(example_width)
5962 .overflow_hidden()
5963 .child(PanelRepoFooter::new_preview(
5964 active_repository(3),
5965 Some(branch(no_remote_upstream)),
5966 ))
5967 .into_any_element(),
5968 ),
5969 single_example(
5970 "Not Ahead or Behind",
5971 div()
5972 .w(example_width)
5973 .overflow_hidden()
5974 .child(PanelRepoFooter::new_preview(
5975 active_repository(4),
5976 Some(branch(not_ahead_or_behind_upstream)),
5977 ))
5978 .into_any_element(),
5979 ),
5980 single_example(
5981 "Behind remote",
5982 div()
5983 .w(example_width)
5984 .overflow_hidden()
5985 .child(PanelRepoFooter::new_preview(
5986 active_repository(5),
5987 Some(branch(behind_upstream)),
5988 ))
5989 .into_any_element(),
5990 ),
5991 single_example(
5992 "Ahead of remote",
5993 div()
5994 .w(example_width)
5995 .overflow_hidden()
5996 .child(PanelRepoFooter::new_preview(
5997 active_repository(6),
5998 Some(branch(ahead_of_upstream)),
5999 ))
6000 .into_any_element(),
6001 ),
6002 single_example(
6003 "Ahead and behind remote",
6004 div()
6005 .w(example_width)
6006 .overflow_hidden()
6007 .child(PanelRepoFooter::new_preview(
6008 active_repository(7),
6009 Some(branch(ahead_and_behind_upstream)),
6010 ))
6011 .into_any_element(),
6012 ),
6013 ],
6014 )
6015 .grow()
6016 .vertical(),
6017 ])
6018 .children(vec![
6019 example_group_with_title(
6020 "Labels",
6021 vec![
6022 single_example(
6023 "Short Branch & Repo",
6024 div()
6025 .w(example_width)
6026 .overflow_hidden()
6027 .child(PanelRepoFooter::new_preview(
6028 SharedString::from("zed"),
6029 Some(custom("main", behind_upstream)),
6030 ))
6031 .into_any_element(),
6032 ),
6033 single_example(
6034 "Long Branch",
6035 div()
6036 .w(example_width)
6037 .overflow_hidden()
6038 .child(PanelRepoFooter::new_preview(
6039 SharedString::from("zed"),
6040 Some(custom(
6041 "redesign-and-update-git-ui-list-entry-style",
6042 behind_upstream,
6043 )),
6044 ))
6045 .into_any_element(),
6046 ),
6047 single_example(
6048 "Long Repo",
6049 div()
6050 .w(example_width)
6051 .overflow_hidden()
6052 .child(PanelRepoFooter::new_preview(
6053 SharedString::from("zed-industries-community-examples"),
6054 Some(custom("gpui", ahead_of_upstream)),
6055 ))
6056 .into_any_element(),
6057 ),
6058 single_example(
6059 "Long Repo & Branch",
6060 div()
6061 .w(example_width)
6062 .overflow_hidden()
6063 .child(PanelRepoFooter::new_preview(
6064 SharedString::from("zed-industries-community-examples"),
6065 Some(custom(
6066 "redesign-and-update-git-ui-list-entry-style",
6067 behind_upstream,
6068 )),
6069 ))
6070 .into_any_element(),
6071 ),
6072 single_example(
6073 "Uppercase Repo",
6074 div()
6075 .w(example_width)
6076 .overflow_hidden()
6077 .child(PanelRepoFooter::new_preview(
6078 SharedString::from("LICENSES"),
6079 Some(custom("main", ahead_of_upstream)),
6080 ))
6081 .into_any_element(),
6082 ),
6083 single_example(
6084 "Uppercase Branch",
6085 div()
6086 .w(example_width)
6087 .overflow_hidden()
6088 .child(PanelRepoFooter::new_preview(
6089 SharedString::from("zed"),
6090 Some(custom("update-README", behind_upstream)),
6091 ))
6092 .into_any_element(),
6093 ),
6094 ],
6095 )
6096 .grow()
6097 .vertical(),
6098 ])
6099 .into_any_element(),
6100 )
6101 }
6102}
6103
6104fn open_output(
6105 operation: impl Into<SharedString>,
6106 workspace: &mut Workspace,
6107 output: &str,
6108 window: &mut Window,
6109 cx: &mut Context<Workspace>,
6110) {
6111 let operation = operation.into();
6112 let buffer = cx.new(|cx| Buffer::local(output, cx));
6113 buffer.update(cx, |buffer, cx| {
6114 buffer.set_capability(language::Capability::ReadOnly, cx);
6115 });
6116 let editor = cx.new(|cx| {
6117 let mut editor = Editor::for_buffer(buffer, None, window, cx);
6118 editor.buffer().update(cx, |buffer, cx| {
6119 buffer.set_title(format!("Output from git {operation}"), cx);
6120 });
6121 editor.set_read_only(true);
6122 editor
6123 });
6124
6125 workspace.add_item_to_center(Box::new(editor), window, cx);
6126}
6127
6128pub(crate) fn show_error_toast(
6129 workspace: Entity<Workspace>,
6130 action: impl Into<SharedString>,
6131 e: anyhow::Error,
6132 cx: &mut App,
6133) {
6134 let action = action.into();
6135 let message = e.to_string().trim().to_string();
6136 if message
6137 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
6138 .next()
6139 .is_some()
6140 { // Hide the cancelled by user message
6141 } else {
6142 workspace.update(cx, |workspace, cx| {
6143 let workspace_weak = cx.weak_entity();
6144 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
6145 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
6146 .action("View Log", move |window, cx| {
6147 let message = message.clone();
6148 let action = action.clone();
6149 workspace_weak
6150 .update(cx, move |workspace, cx| {
6151 open_output(action, workspace, &message, window, cx)
6152 })
6153 .ok();
6154 })
6155 });
6156 workspace.toggle_status_toast(toast, cx)
6157 });
6158 }
6159}
6160
6161#[cfg(test)]
6162mod tests {
6163 use git::{
6164 repository::repo_path,
6165 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
6166 };
6167 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
6168 use indoc::indoc;
6169 use project::FakeFs;
6170 use serde_json::json;
6171 use settings::SettingsStore;
6172 use theme::LoadThemes;
6173 use util::path;
6174 use util::rel_path::rel_path;
6175
6176 use super::*;
6177
6178 fn init_test(cx: &mut gpui::TestAppContext) {
6179 zlog::init_test();
6180
6181 cx.update(|cx| {
6182 let settings_store = SettingsStore::test(cx);
6183 cx.set_global(settings_store);
6184 theme::init(LoadThemes::JustBase, cx);
6185 editor::init(cx);
6186 crate::init(cx);
6187 });
6188 }
6189
6190 #[gpui::test]
6191 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
6192 init_test(cx);
6193 let fs = FakeFs::new(cx.background_executor.clone());
6194 fs.insert_tree(
6195 "/root",
6196 json!({
6197 "zed": {
6198 ".git": {},
6199 "crates": {
6200 "gpui": {
6201 "gpui.rs": "fn main() {}"
6202 },
6203 "util": {
6204 "util.rs": "fn do_it() {}"
6205 }
6206 }
6207 },
6208 }),
6209 )
6210 .await;
6211
6212 fs.set_status_for_repo(
6213 Path::new(path!("/root/zed/.git")),
6214 &[
6215 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6216 ("crates/util/util.rs", StatusCode::Modified.worktree()),
6217 ],
6218 );
6219
6220 let project =
6221 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6222 let workspace =
6223 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6224 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6225
6226 cx.read(|cx| {
6227 project
6228 .read(cx)
6229 .worktrees(cx)
6230 .next()
6231 .unwrap()
6232 .read(cx)
6233 .as_local()
6234 .unwrap()
6235 .scan_complete()
6236 })
6237 .await;
6238
6239 cx.executor().run_until_parked();
6240
6241 let panel = workspace.update(cx, GitPanel::new).unwrap();
6242
6243 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6244 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6245 });
6246 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6247 handle.await;
6248
6249 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6250 pretty_assertions::assert_eq!(
6251 entries,
6252 [
6253 GitListEntry::Header(GitHeaderEntry {
6254 header: Section::Tracked
6255 }),
6256 GitListEntry::Status(GitStatusEntry {
6257 repo_path: repo_path("crates/gpui/gpui.rs"),
6258 status: StatusCode::Modified.worktree(),
6259 staging: StageStatus::Unstaged,
6260 }),
6261 GitListEntry::Status(GitStatusEntry {
6262 repo_path: repo_path("crates/util/util.rs"),
6263 status: StatusCode::Modified.worktree(),
6264 staging: StageStatus::Unstaged,
6265 },),
6266 ],
6267 );
6268
6269 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6270 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6271 });
6272 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6273 handle.await;
6274 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6275 pretty_assertions::assert_eq!(
6276 entries,
6277 [
6278 GitListEntry::Header(GitHeaderEntry {
6279 header: Section::Tracked
6280 }),
6281 GitListEntry::Status(GitStatusEntry {
6282 repo_path: repo_path("crates/gpui/gpui.rs"),
6283 status: StatusCode::Modified.worktree(),
6284 staging: StageStatus::Unstaged,
6285 }),
6286 GitListEntry::Status(GitStatusEntry {
6287 repo_path: repo_path("crates/util/util.rs"),
6288 status: StatusCode::Modified.worktree(),
6289 staging: StageStatus::Unstaged,
6290 },),
6291 ],
6292 );
6293 }
6294
6295 #[gpui::test]
6296 async fn test_bulk_staging(cx: &mut TestAppContext) {
6297 use GitListEntry::*;
6298
6299 init_test(cx);
6300 let fs = FakeFs::new(cx.background_executor.clone());
6301 fs.insert_tree(
6302 "/root",
6303 json!({
6304 "project": {
6305 ".git": {},
6306 "src": {
6307 "main.rs": "fn main() {}",
6308 "lib.rs": "pub fn hello() {}",
6309 "utils.rs": "pub fn util() {}"
6310 },
6311 "tests": {
6312 "test.rs": "fn test() {}"
6313 },
6314 "new_file.txt": "new content",
6315 "another_new.rs": "// new file",
6316 "conflict.txt": "conflicted content"
6317 }
6318 }),
6319 )
6320 .await;
6321
6322 fs.set_status_for_repo(
6323 Path::new(path!("/root/project/.git")),
6324 &[
6325 ("src/main.rs", StatusCode::Modified.worktree()),
6326 ("src/lib.rs", StatusCode::Modified.worktree()),
6327 ("tests/test.rs", StatusCode::Modified.worktree()),
6328 ("new_file.txt", FileStatus::Untracked),
6329 ("another_new.rs", FileStatus::Untracked),
6330 ("src/utils.rs", FileStatus::Untracked),
6331 (
6332 "conflict.txt",
6333 UnmergedStatus {
6334 first_head: UnmergedStatusCode::Updated,
6335 second_head: UnmergedStatusCode::Updated,
6336 }
6337 .into(),
6338 ),
6339 ],
6340 );
6341
6342 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6343 let workspace =
6344 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6345 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6346
6347 cx.read(|cx| {
6348 project
6349 .read(cx)
6350 .worktrees(cx)
6351 .next()
6352 .unwrap()
6353 .read(cx)
6354 .as_local()
6355 .unwrap()
6356 .scan_complete()
6357 })
6358 .await;
6359
6360 cx.executor().run_until_parked();
6361
6362 let panel = workspace.update(cx, GitPanel::new).unwrap();
6363
6364 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6365 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6366 });
6367 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6368 handle.await;
6369
6370 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6371 #[rustfmt::skip]
6372 pretty_assertions::assert_matches!(
6373 entries.as_slice(),
6374 &[
6375 Header(GitHeaderEntry { header: Section::Conflict }),
6376 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6377 Header(GitHeaderEntry { header: Section::Tracked }),
6378 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6379 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6380 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6381 Header(GitHeaderEntry { header: Section::New }),
6382 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6383 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6384 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6385 ],
6386 );
6387
6388 let second_status_entry = entries[3].clone();
6389 panel.update_in(cx, |panel, window, cx| {
6390 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6391 });
6392
6393 panel.update_in(cx, |panel, window, cx| {
6394 panel.selected_entry = Some(7);
6395 panel.stage_range(&git::StageRange, window, cx);
6396 });
6397
6398 cx.read(|cx| {
6399 project
6400 .read(cx)
6401 .worktrees(cx)
6402 .next()
6403 .unwrap()
6404 .read(cx)
6405 .as_local()
6406 .unwrap()
6407 .scan_complete()
6408 })
6409 .await;
6410
6411 cx.executor().run_until_parked();
6412
6413 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6414 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6415 });
6416 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6417 handle.await;
6418
6419 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6420 #[rustfmt::skip]
6421 pretty_assertions::assert_matches!(
6422 entries.as_slice(),
6423 &[
6424 Header(GitHeaderEntry { header: Section::Conflict }),
6425 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6426 Header(GitHeaderEntry { header: Section::Tracked }),
6427 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6428 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6429 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6430 Header(GitHeaderEntry { header: Section::New }),
6431 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6432 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6433 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6434 ],
6435 );
6436
6437 let third_status_entry = entries[4].clone();
6438 panel.update_in(cx, |panel, window, cx| {
6439 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6440 });
6441
6442 panel.update_in(cx, |panel, window, cx| {
6443 panel.selected_entry = Some(9);
6444 panel.stage_range(&git::StageRange, window, cx);
6445 });
6446
6447 cx.read(|cx| {
6448 project
6449 .read(cx)
6450 .worktrees(cx)
6451 .next()
6452 .unwrap()
6453 .read(cx)
6454 .as_local()
6455 .unwrap()
6456 .scan_complete()
6457 })
6458 .await;
6459
6460 cx.executor().run_until_parked();
6461
6462 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6463 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6464 });
6465 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6466 handle.await;
6467
6468 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6469 #[rustfmt::skip]
6470 pretty_assertions::assert_matches!(
6471 entries.as_slice(),
6472 &[
6473 Header(GitHeaderEntry { header: Section::Conflict }),
6474 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6475 Header(GitHeaderEntry { header: Section::Tracked }),
6476 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6477 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6478 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6479 Header(GitHeaderEntry { header: Section::New }),
6480 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6481 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6482 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6483 ],
6484 );
6485 }
6486
6487 #[gpui::test]
6488 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6489 use GitListEntry::*;
6490
6491 init_test(cx);
6492 let fs = FakeFs::new(cx.background_executor.clone());
6493 fs.insert_tree(
6494 "/root",
6495 json!({
6496 "project": {
6497 ".git": {},
6498 "src": {
6499 "main.rs": "fn main() {}",
6500 "lib.rs": "pub fn hello() {}",
6501 "utils.rs": "pub fn util() {}"
6502 },
6503 "tests": {
6504 "test.rs": "fn test() {}"
6505 },
6506 "new_file.txt": "new content",
6507 "another_new.rs": "// new file",
6508 "conflict.txt": "conflicted content"
6509 }
6510 }),
6511 )
6512 .await;
6513
6514 fs.set_status_for_repo(
6515 Path::new(path!("/root/project/.git")),
6516 &[
6517 ("src/main.rs", StatusCode::Modified.worktree()),
6518 ("src/lib.rs", StatusCode::Modified.worktree()),
6519 ("tests/test.rs", StatusCode::Modified.worktree()),
6520 ("new_file.txt", FileStatus::Untracked),
6521 ("another_new.rs", FileStatus::Untracked),
6522 ("src/utils.rs", FileStatus::Untracked),
6523 (
6524 "conflict.txt",
6525 UnmergedStatus {
6526 first_head: UnmergedStatusCode::Updated,
6527 second_head: UnmergedStatusCode::Updated,
6528 }
6529 .into(),
6530 ),
6531 ],
6532 );
6533
6534 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6535 let workspace =
6536 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6537 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6538
6539 cx.read(|cx| {
6540 project
6541 .read(cx)
6542 .worktrees(cx)
6543 .next()
6544 .unwrap()
6545 .read(cx)
6546 .as_local()
6547 .unwrap()
6548 .scan_complete()
6549 })
6550 .await;
6551
6552 cx.executor().run_until_parked();
6553
6554 let panel = workspace.update(cx, GitPanel::new).unwrap();
6555
6556 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6557 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6558 });
6559 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6560 handle.await;
6561
6562 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6563 #[rustfmt::skip]
6564 pretty_assertions::assert_matches!(
6565 entries.as_slice(),
6566 &[
6567 Header(GitHeaderEntry { header: Section::Conflict }),
6568 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6569 Header(GitHeaderEntry { header: Section::Tracked }),
6570 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6571 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6572 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6573 Header(GitHeaderEntry { header: Section::New }),
6574 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6575 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6576 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6577 ],
6578 );
6579
6580 assert_entry_paths(
6581 &entries,
6582 &[
6583 None,
6584 Some("conflict.txt"),
6585 None,
6586 Some("src/lib.rs"),
6587 Some("src/main.rs"),
6588 Some("tests/test.rs"),
6589 None,
6590 Some("another_new.rs"),
6591 Some("new_file.txt"),
6592 Some("src/utils.rs"),
6593 ],
6594 );
6595
6596 let second_status_entry = entries[3].clone();
6597 panel.update_in(cx, |panel, window, cx| {
6598 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6599 });
6600
6601 cx.update(|_window, cx| {
6602 SettingsStore::update_global(cx, |store, cx| {
6603 store.update_user_settings(cx, |settings| {
6604 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6605 })
6606 });
6607 });
6608
6609 panel.update_in(cx, |panel, window, cx| {
6610 panel.selected_entry = Some(7);
6611 panel.stage_range(&git::StageRange, window, cx);
6612 });
6613
6614 cx.read(|cx| {
6615 project
6616 .read(cx)
6617 .worktrees(cx)
6618 .next()
6619 .unwrap()
6620 .read(cx)
6621 .as_local()
6622 .unwrap()
6623 .scan_complete()
6624 })
6625 .await;
6626
6627 cx.executor().run_until_parked();
6628
6629 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6630 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6631 });
6632 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6633 handle.await;
6634
6635 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6636 #[rustfmt::skip]
6637 pretty_assertions::assert_matches!(
6638 entries.as_slice(),
6639 &[
6640 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6641 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6642 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6643 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6644 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6645 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6646 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6647 ],
6648 );
6649
6650 assert_entry_paths(
6651 &entries,
6652 &[
6653 Some("another_new.rs"),
6654 Some("conflict.txt"),
6655 Some("new_file.txt"),
6656 Some("src/lib.rs"),
6657 Some("src/main.rs"),
6658 Some("src/utils.rs"),
6659 Some("tests/test.rs"),
6660 ],
6661 );
6662
6663 let third_status_entry = entries[4].clone();
6664 panel.update_in(cx, |panel, window, cx| {
6665 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6666 });
6667
6668 panel.update_in(cx, |panel, window, cx| {
6669 panel.selected_entry = Some(9);
6670 panel.stage_range(&git::StageRange, window, cx);
6671 });
6672
6673 cx.read(|cx| {
6674 project
6675 .read(cx)
6676 .worktrees(cx)
6677 .next()
6678 .unwrap()
6679 .read(cx)
6680 .as_local()
6681 .unwrap()
6682 .scan_complete()
6683 })
6684 .await;
6685
6686 cx.executor().run_until_parked();
6687
6688 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6689 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6690 });
6691 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6692 handle.await;
6693
6694 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6695 #[rustfmt::skip]
6696 pretty_assertions::assert_matches!(
6697 entries.as_slice(),
6698 &[
6699 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6700 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6701 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6702 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6703 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6704 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6705 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6706 ],
6707 );
6708
6709 assert_entry_paths(
6710 &entries,
6711 &[
6712 Some("another_new.rs"),
6713 Some("conflict.txt"),
6714 Some("new_file.txt"),
6715 Some("src/lib.rs"),
6716 Some("src/main.rs"),
6717 Some("src/utils.rs"),
6718 Some("tests/test.rs"),
6719 ],
6720 );
6721 }
6722
6723 #[gpui::test]
6724 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
6725 init_test(cx);
6726 let fs = FakeFs::new(cx.background_executor.clone());
6727 fs.insert_tree(
6728 "/root",
6729 json!({
6730 "project": {
6731 ".git": {},
6732 "src": {
6733 "main.rs": "fn main() {}"
6734 }
6735 }
6736 }),
6737 )
6738 .await;
6739
6740 fs.set_status_for_repo(
6741 Path::new(path!("/root/project/.git")),
6742 &[("src/main.rs", StatusCode::Modified.worktree())],
6743 );
6744
6745 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6746 let workspace =
6747 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6748 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6749
6750 let panel = workspace.update(cx, GitPanel::new).unwrap();
6751
6752 // Test: User has commit message, enables amend (saves message), then disables (restores message)
6753 panel.update(cx, |panel, cx| {
6754 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6755 let start = buffer.anchor_before(0);
6756 let end = buffer.anchor_after(buffer.len());
6757 buffer.edit([(start..end, "Initial commit message")], None, cx);
6758 });
6759
6760 panel.set_amend_pending(true, cx);
6761 assert!(panel.original_commit_message.is_some());
6762
6763 panel.set_amend_pending(false, cx);
6764 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6765 assert_eq!(current_message, "Initial commit message");
6766 assert!(panel.original_commit_message.is_none());
6767 });
6768
6769 // Test: User has empty commit message, enables amend, then disables (clears message)
6770 panel.update(cx, |panel, cx| {
6771 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6772 let start = buffer.anchor_before(0);
6773 let end = buffer.anchor_after(buffer.len());
6774 buffer.edit([(start..end, "")], None, cx);
6775 });
6776
6777 panel.set_amend_pending(true, cx);
6778 assert!(panel.original_commit_message.is_none());
6779
6780 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6781 let start = buffer.anchor_before(0);
6782 let end = buffer.anchor_after(buffer.len());
6783 buffer.edit([(start..end, "Previous commit message")], None, cx);
6784 });
6785
6786 panel.set_amend_pending(false, cx);
6787 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6788 assert_eq!(current_message, "");
6789 });
6790 }
6791
6792 #[gpui::test]
6793 async fn test_amend(cx: &mut TestAppContext) {
6794 init_test(cx);
6795 let fs = FakeFs::new(cx.background_executor.clone());
6796 fs.insert_tree(
6797 "/root",
6798 json!({
6799 "project": {
6800 ".git": {},
6801 "src": {
6802 "main.rs": "fn main() {}"
6803 }
6804 }
6805 }),
6806 )
6807 .await;
6808
6809 fs.set_status_for_repo(
6810 Path::new(path!("/root/project/.git")),
6811 &[("src/main.rs", StatusCode::Modified.worktree())],
6812 );
6813
6814 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6815 let workspace =
6816 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6817 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6818
6819 // Wait for the project scanning to finish so that `head_commit(cx)` is
6820 // actually set, otherwise no head commit would be available from which
6821 // to fetch the latest commit message from.
6822 cx.executor().run_until_parked();
6823
6824 let panel = workspace.update(cx, GitPanel::new).unwrap();
6825 panel.read_with(cx, |panel, cx| {
6826 assert!(panel.active_repository.is_some());
6827 assert!(panel.head_commit(cx).is_some());
6828 });
6829
6830 panel.update_in(cx, |panel, window, cx| {
6831 // Update the commit editor's message to ensure that its contents
6832 // are later restored, after amending is finished.
6833 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6834 buffer.set_text("refactor: update main.rs", cx);
6835 });
6836
6837 // Start amending the previous commit.
6838 panel.focus_editor(&Default::default(), window, cx);
6839 panel.on_amend(&Amend, window, cx);
6840 });
6841
6842 // Since `GitPanel.amend` attempts to fetch the latest commit message in
6843 // a background task, we need to wait for it to complete before being
6844 // able to assert that the commit message editor's state has been
6845 // updated.
6846 cx.run_until_parked();
6847
6848 panel.update_in(cx, |panel, window, cx| {
6849 assert_eq!(
6850 panel.commit_message_buffer(cx).read(cx).text(),
6851 "initial commit"
6852 );
6853 assert_eq!(
6854 panel.original_commit_message,
6855 Some("refactor: update main.rs".to_string())
6856 );
6857
6858 // Finish amending the previous commit.
6859 panel.focus_editor(&Default::default(), window, cx);
6860 panel.on_amend(&Amend, window, cx);
6861 });
6862
6863 // Since the actual commit logic is run in a background task, we need to
6864 // await its completion to actually ensure that the commit message
6865 // editor's contents are set to the original message and haven't been
6866 // cleared.
6867 cx.run_until_parked();
6868
6869 panel.update_in(cx, |panel, _window, cx| {
6870 // After amending, the commit editor's message should be restored to
6871 // the original message.
6872 assert_eq!(
6873 panel.commit_message_buffer(cx).read(cx).text(),
6874 "refactor: update main.rs"
6875 );
6876 assert!(panel.original_commit_message.is_none());
6877 });
6878 }
6879
6880 #[gpui::test]
6881 async fn test_open_diff(cx: &mut TestAppContext) {
6882 init_test(cx);
6883
6884 let fs = FakeFs::new(cx.background_executor.clone());
6885 fs.insert_tree(
6886 path!("/project"),
6887 json!({
6888 ".git": {},
6889 "tracked": "tracked\n",
6890 "untracked": "\n",
6891 }),
6892 )
6893 .await;
6894
6895 fs.set_head_and_index_for_repo(
6896 path!("/project/.git").as_ref(),
6897 &[("tracked", "old tracked\n".into())],
6898 );
6899
6900 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
6901 let workspace =
6902 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6903 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6904 let panel = workspace.update(cx, GitPanel::new).unwrap();
6905
6906 // Enable the `sort_by_path` setting and wait for entries to be updated,
6907 // as there should no longer be separators between Tracked and Untracked
6908 // files.
6909 cx.update(|_window, cx| {
6910 SettingsStore::update_global(cx, |store, cx| {
6911 store.update_user_settings(cx, |settings| {
6912 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6913 })
6914 });
6915 });
6916
6917 cx.update_window_entity(&panel, |panel, _, _| {
6918 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6919 })
6920 .await;
6921
6922 // Confirm that `Open Diff` still works for the untracked file, updating
6923 // the Project Diff's active path.
6924 panel.update_in(cx, |panel, window, cx| {
6925 panel.selected_entry = Some(1);
6926 panel.open_diff(&menu::Confirm, window, cx);
6927 });
6928 cx.run_until_parked();
6929
6930 let _ = workspace.update(cx, |workspace, _window, cx| {
6931 let active_path = workspace
6932 .item_of_type::<ProjectDiff>(cx)
6933 .expect("ProjectDiff should exist")
6934 .read(cx)
6935 .active_path(cx)
6936 .expect("active_path should exist");
6937
6938 assert_eq!(active_path.path, rel_path("untracked").into_arc());
6939 });
6940 }
6941
6942 #[gpui::test]
6943 async fn test_tree_view_reveals_collapsed_parent_on_select_entry_by_path(
6944 cx: &mut TestAppContext,
6945 ) {
6946 init_test(cx);
6947
6948 let fs = FakeFs::new(cx.background_executor.clone());
6949 fs.insert_tree(
6950 path!("/project"),
6951 json!({
6952 ".git": {},
6953 "src": {
6954 "a": {
6955 "foo.rs": "fn foo() {}",
6956 },
6957 "b": {
6958 "bar.rs": "fn bar() {}",
6959 },
6960 },
6961 }),
6962 )
6963 .await;
6964
6965 fs.set_status_for_repo(
6966 path!("/project/.git").as_ref(),
6967 &[
6968 ("src/a/foo.rs", StatusCode::Modified.worktree()),
6969 ("src/b/bar.rs", StatusCode::Modified.worktree()),
6970 ],
6971 );
6972
6973 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
6974 let workspace =
6975 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6976 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6977
6978 cx.read(|cx| {
6979 project
6980 .read(cx)
6981 .worktrees(cx)
6982 .next()
6983 .unwrap()
6984 .read(cx)
6985 .as_local()
6986 .unwrap()
6987 .scan_complete()
6988 })
6989 .await;
6990
6991 cx.executor().run_until_parked();
6992
6993 cx.update(|_window, cx| {
6994 SettingsStore::update_global(cx, |store, cx| {
6995 store.update_user_settings(cx, |settings| {
6996 settings.git_panel.get_or_insert_default().tree_view = Some(true);
6997 })
6998 });
6999 });
7000
7001 let panel = workspace.update(cx, GitPanel::new).unwrap();
7002
7003 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7004 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7005 });
7006 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7007 handle.await;
7008
7009 let src_key = panel.read_with(cx, |panel, _| {
7010 panel
7011 .entries
7012 .iter()
7013 .find_map(|entry| match entry {
7014 GitListEntry::Directory(dir) if dir.key.path == repo_path("src") => {
7015 Some(dir.key.clone())
7016 }
7017 _ => None,
7018 })
7019 .expect("src directory should exist in tree view")
7020 });
7021
7022 panel.update_in(cx, |panel, window, cx| {
7023 panel.toggle_directory(&src_key, window, cx);
7024 });
7025
7026 panel.read_with(cx, |panel, _| {
7027 let state = panel
7028 .view_mode
7029 .tree_state()
7030 .expect("tree view state should exist");
7031 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(false));
7032 });
7033
7034 let worktree_id =
7035 cx.read(|cx| project.read(cx).worktrees(cx).next().unwrap().read(cx).id());
7036 let project_path = ProjectPath {
7037 worktree_id,
7038 path: RelPath::unix("src/a/foo.rs").unwrap().into_arc(),
7039 };
7040
7041 panel.update_in(cx, |panel, window, cx| {
7042 panel.select_entry_by_path(project_path, window, cx);
7043 });
7044
7045 panel.read_with(cx, |panel, _| {
7046 let state = panel
7047 .view_mode
7048 .tree_state()
7049 .expect("tree view state should exist");
7050 assert_eq!(state.expanded_dirs.get(&src_key).copied(), Some(true));
7051
7052 let selected_ix = panel.selected_entry.expect("selection should be set");
7053 assert!(state.logical_indices.contains(&selected_ix));
7054
7055 let selected_entry = panel
7056 .entries
7057 .get(selected_ix)
7058 .and_then(|entry| entry.status_entry())
7059 .expect("selected entry should be a status entry");
7060 assert_eq!(selected_entry.repo_path, repo_path("src/a/foo.rs"));
7061 });
7062 }
7063
7064 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
7065 assert_eq!(entries.len(), expected_paths.len());
7066 for (entry, expected_path) in entries.iter().zip(expected_paths) {
7067 assert_eq!(
7068 entry.status_entry().map(|status| status
7069 .repo_path
7070 .as_ref()
7071 .as_std_path()
7072 .to_string_lossy()
7073 .to_string()),
7074 expected_path.map(|s| s.to_string())
7075 );
7076 }
7077 }
7078
7079 #[test]
7080 fn test_compress_diff_no_truncation() {
7081 let diff = indoc! {"
7082 --- a/file.txt
7083 +++ b/file.txt
7084 @@ -1,2 +1,2 @@
7085 -old
7086 +new
7087 "};
7088 let result = GitPanel::compress_commit_diff(diff, 1000);
7089 assert_eq!(result, diff);
7090 }
7091
7092 #[test]
7093 fn test_compress_diff_truncate_long_lines() {
7094 let long_line = "🦀".repeat(300);
7095 let diff = indoc::formatdoc! {"
7096 --- a/file.txt
7097 +++ b/file.txt
7098 @@ -1,2 +1,3 @@
7099 context
7100 +{}
7101 more context
7102 ", long_line};
7103 let result = GitPanel::compress_commit_diff(&diff, 100);
7104 assert!(result.contains("...[truncated]"));
7105 assert!(result.len() < diff.len());
7106 }
7107
7108 #[test]
7109 fn test_compress_diff_truncate_hunks() {
7110 let diff = indoc! {"
7111 --- a/file.txt
7112 +++ b/file.txt
7113 @@ -1,2 +1,2 @@
7114 context
7115 -old1
7116 +new1
7117 @@ -5,2 +5,2 @@
7118 context 2
7119 -old2
7120 +new2
7121 @@ -10,2 +10,2 @@
7122 context 3
7123 -old3
7124 +new3
7125 "};
7126 let result = GitPanel::compress_commit_diff(diff, 100);
7127 let expected = indoc! {"
7128 --- a/file.txt
7129 +++ b/file.txt
7130 @@ -1,2 +1,2 @@
7131 context
7132 -old1
7133 +new1
7134 [...skipped 2 hunks...]
7135 "};
7136 assert_eq!(result, expected);
7137 }
7138
7139 #[gpui::test]
7140 async fn test_suggest_commit_message(cx: &mut TestAppContext) {
7141 init_test(cx);
7142
7143 let fs = FakeFs::new(cx.background_executor.clone());
7144 fs.insert_tree(
7145 path!("/project"),
7146 json!({
7147 ".git": {},
7148 "tracked": "tracked\n",
7149 "untracked": "\n",
7150 }),
7151 )
7152 .await;
7153
7154 fs.set_head_and_index_for_repo(
7155 path!("/project/.git").as_ref(),
7156 &[("tracked", "old tracked\n".into())],
7157 );
7158
7159 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
7160 let workspace =
7161 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
7162 let cx = &mut VisualTestContext::from_window(*workspace, cx);
7163 let panel = workspace.update(cx, GitPanel::new).unwrap();
7164
7165 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7166 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7167 });
7168 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7169 handle.await;
7170
7171 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
7172
7173 // GitPanel
7174 // - Tracked:
7175 // - [] tracked
7176 // - Untracked
7177 // - [] untracked
7178 //
7179 // The commit message should now read:
7180 // "Update tracked"
7181 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7182 assert_eq!(message, Some("Update tracked".to_string()));
7183
7184 let first_status_entry = entries[1].clone();
7185 panel.update_in(cx, |panel, window, cx| {
7186 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7187 });
7188
7189 cx.read(|cx| {
7190 project
7191 .read(cx)
7192 .worktrees(cx)
7193 .next()
7194 .unwrap()
7195 .read(cx)
7196 .as_local()
7197 .unwrap()
7198 .scan_complete()
7199 })
7200 .await;
7201
7202 cx.executor().run_until_parked();
7203
7204 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7205 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7206 });
7207 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7208 handle.await;
7209
7210 // GitPanel
7211 // - Tracked:
7212 // - [x] tracked
7213 // - Untracked
7214 // - [] untracked
7215 //
7216 // The commit message should still read:
7217 // "Update tracked"
7218 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7219 assert_eq!(message, Some("Update tracked".to_string()));
7220
7221 let second_status_entry = entries[3].clone();
7222 panel.update_in(cx, |panel, window, cx| {
7223 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7224 });
7225
7226 cx.read(|cx| {
7227 project
7228 .read(cx)
7229 .worktrees(cx)
7230 .next()
7231 .unwrap()
7232 .read(cx)
7233 .as_local()
7234 .unwrap()
7235 .scan_complete()
7236 })
7237 .await;
7238
7239 cx.executor().run_until_parked();
7240
7241 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7242 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7243 });
7244 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7245 handle.await;
7246
7247 // GitPanel
7248 // - Tracked:
7249 // - [x] tracked
7250 // - Untracked
7251 // - [x] untracked
7252 //
7253 // The commit message should now read:
7254 // "Enter commit message"
7255 // (which means we should see None returned).
7256 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7257 assert!(message.is_none());
7258
7259 panel.update_in(cx, |panel, window, cx| {
7260 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
7261 });
7262
7263 cx.read(|cx| {
7264 project
7265 .read(cx)
7266 .worktrees(cx)
7267 .next()
7268 .unwrap()
7269 .read(cx)
7270 .as_local()
7271 .unwrap()
7272 .scan_complete()
7273 })
7274 .await;
7275
7276 cx.executor().run_until_parked();
7277
7278 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7279 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7280 });
7281 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7282 handle.await;
7283
7284 // GitPanel
7285 // - Tracked:
7286 // - [] tracked
7287 // - Untracked
7288 // - [x] untracked
7289 //
7290 // The commit message should now read:
7291 // "Update untracked"
7292 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7293 assert_eq!(message, Some("Create untracked".to_string()));
7294
7295 panel.update_in(cx, |panel, window, cx| {
7296 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
7297 });
7298
7299 cx.read(|cx| {
7300 project
7301 .read(cx)
7302 .worktrees(cx)
7303 .next()
7304 .unwrap()
7305 .read(cx)
7306 .as_local()
7307 .unwrap()
7308 .scan_complete()
7309 })
7310 .await;
7311
7312 cx.executor().run_until_parked();
7313
7314 let handle = cx.update_window_entity(&panel, |panel, _, _| {
7315 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
7316 });
7317 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
7318 handle.await;
7319
7320 // GitPanel
7321 // - Tracked:
7322 // - [] tracked
7323 // - Untracked
7324 // - [] untracked
7325 //
7326 // The commit message should now read:
7327 // "Update tracked"
7328 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7329 assert_eq!(message, Some("Update tracked".to_string()));
7330 }
7331}