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