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