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 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
10};
11use agent_settings::AgentSettings;
12use anyhow::Context as _;
13use askpass::AskPassDelegate;
14use db::kvp::KEY_VALUE_STORE;
15use editor::{Editor, EditorElement, EditorMode, MultiBuffer};
16use futures::StreamExt as _;
17use git::blame::ParsedCommitMessage;
18use git::repository::{
19 Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,
20 PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,
21 UpstreamTrackingStatus, get_git_committer,
22};
23use git::stash::GitStash;
24use git::status::StageStatus;
25use git::{Amend, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};
26use git::{
27 ExpandCommitEditor, RestoreTrackedFiles, StageAll, StashAll, StashApply, StashPop,
28 TrashUntrackedFiles, UnstageAll,
29};
30use gpui::{
31 Action, AsyncApp, AsyncWindowContext, ClickEvent, Corner, DismissEvent, Entity, EventEmitter,
32 FocusHandle, Focusable, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior,
33 MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Subscription, Task,
34 UniformListScrollHandle, WeakEntity, actions, anchored, deferred, uniform_list,
35};
36use itertools::Itertools;
37use language::{Buffer, File};
38use language_model::{
39 ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
40};
41use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
42use multi_buffer::ExcerptInfo;
43use notifications::status_toast::{StatusToast, ToastIcon};
44use panel::{
45 PanelHeader, panel_button, panel_editor_container, panel_editor_style, panel_filled_button,
46 panel_icon_button,
47};
48use project::{
49 Fs, Project, ProjectPath,
50 git_store::{GitStoreEvent, Repository, RepositoryEvent, RepositoryId},
51};
52use serde::{Deserialize, Serialize};
53use settings::{Settings, SettingsStore, StatusStyle};
54use std::future::Future;
55use std::ops::Range;
56use std::path::Path;
57use std::{collections::HashSet, sync::Arc, time::Duration, usize};
58use strum::{IntoEnumIterator, VariantNames};
59use time::OffsetDateTime;
60use ui::{
61 Checkbox, CommonAnimationExt, ContextMenu, ElevationIndex, IconPosition, Label, LabelSize,
62 PopoverMenu, ScrollAxes, Scrollbars, SplitButton, Tooltip, WithScrollbar, prelude::*,
63};
64use util::paths::PathStyle;
65use util::{ResultExt, TryFutureExt, maybe};
66use workspace::SERIALIZATION_THROTTLE_TIME;
67
68use cloud_llm_client::CompletionIntent;
69use workspace::{
70 Workspace,
71 dock::{DockPosition, Panel, PanelEvent},
72 notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId},
73};
74
75actions!(
76 git_panel,
77 [
78 /// Closes the git panel.
79 Close,
80 /// Toggles focus on the git panel.
81 ToggleFocus,
82 /// Opens the git panel menu.
83 OpenMenu,
84 /// Focuses on the commit message editor.
85 FocusEditor,
86 /// Focuses on the changes list.
87 FocusChanges,
88 /// Toggles automatic co-author suggestions.
89 ToggleFillCoAuthors,
90 /// Toggles sorting entries by path vs status.
91 ToggleSortByPath,
92 ]
93);
94
95fn prompt<T>(
96 msg: &str,
97 detail: Option<&str>,
98 window: &mut Window,
99 cx: &mut App,
100) -> Task<anyhow::Result<T>>
101where
102 T: IntoEnumIterator + VariantNames + 'static,
103{
104 let rx = window.prompt(PromptLevel::Info, msg, detail, T::VARIANTS, cx);
105 cx.spawn(async move |_| Ok(T::iter().nth(rx.await?).unwrap()))
106}
107
108#[derive(strum::EnumIter, strum::VariantNames)]
109#[strum(serialize_all = "title_case")]
110enum TrashCancel {
111 Trash,
112 Cancel,
113}
114
115struct GitMenuState {
116 has_tracked_changes: bool,
117 has_staged_changes: bool,
118 has_unstaged_changes: bool,
119 has_new_changes: bool,
120 sort_by_path: bool,
121 has_stash_items: bool,
122}
123
124fn git_panel_context_menu(
125 focus_handle: FocusHandle,
126 state: GitMenuState,
127 window: &mut Window,
128 cx: &mut App,
129) -> Entity<ContextMenu> {
130 ContextMenu::build(window, cx, move |context_menu, _, _| {
131 context_menu
132 .context(focus_handle)
133 .action_disabled_when(
134 !state.has_unstaged_changes,
135 "Stage All",
136 StageAll.boxed_clone(),
137 )
138 .action_disabled_when(
139 !state.has_staged_changes,
140 "Unstage All",
141 UnstageAll.boxed_clone(),
142 )
143 .separator()
144 .action_disabled_when(
145 !(state.has_new_changes || state.has_tracked_changes),
146 "Stash All",
147 StashAll.boxed_clone(),
148 )
149 .action_disabled_when(!state.has_stash_items, "Stash Pop", StashPop.boxed_clone())
150 .action("View Stash", zed_actions::git::ViewStash.boxed_clone())
151 .separator()
152 .action("Open Diff", project_diff::Diff.boxed_clone())
153 .separator()
154 .action_disabled_when(
155 !state.has_tracked_changes,
156 "Discard Tracked Changes",
157 RestoreTrackedFiles.boxed_clone(),
158 )
159 .action_disabled_when(
160 !state.has_new_changes,
161 "Trash Untracked Files",
162 TrashUntrackedFiles.boxed_clone(),
163 )
164 .separator()
165 .entry(
166 if state.sort_by_path {
167 "Sort by Status"
168 } else {
169 "Sort by Path"
170 },
171 Some(Box::new(ToggleSortByPath)),
172 move |window, cx| window.dispatch_action(Box::new(ToggleSortByPath), cx),
173 )
174 })
175}
176
177const GIT_PANEL_KEY: &str = "GitPanel";
178
179const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
180
181pub fn register(workspace: &mut Workspace) {
182 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
183 workspace.toggle_panel_focus::<GitPanel>(window, cx);
184 });
185 workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
186 CommitModal::toggle(workspace, None, window, cx)
187 });
188}
189
190#[derive(Debug, Clone)]
191pub enum Event {
192 Focus,
193}
194
195#[derive(Serialize, Deserialize)]
196struct SerializedGitPanel {
197 width: Option<Pixels>,
198 #[serde(default)]
199 amend_pending: bool,
200 #[serde(default)]
201 signoff_enabled: bool,
202}
203
204#[derive(Debug, PartialEq, Eq, Clone, Copy)]
205enum Section {
206 Conflict,
207 Tracked,
208 New,
209}
210
211#[derive(Debug, PartialEq, Eq, Clone)]
212struct GitHeaderEntry {
213 header: Section,
214}
215
216impl GitHeaderEntry {
217 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
218 let this = &self.header;
219 let status = status_entry.status;
220 match this {
221 Section::Conflict => {
222 repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path)
223 }
224 Section::Tracked => !status.is_created(),
225 Section::New => status.is_created(),
226 }
227 }
228 pub fn title(&self) -> &'static str {
229 match self.header {
230 Section::Conflict => "Conflicts",
231 Section::Tracked => "Tracked",
232 Section::New => "Untracked",
233 }
234 }
235}
236
237#[derive(Debug, PartialEq, Eq, Clone)]
238enum GitListEntry {
239 Status(GitStatusEntry),
240 Header(GitHeaderEntry),
241}
242
243impl GitListEntry {
244 fn status_entry(&self) -> Option<&GitStatusEntry> {
245 match self {
246 GitListEntry::Status(entry) => Some(entry),
247 _ => None,
248 }
249 }
250}
251
252#[derive(Debug, PartialEq, Eq, Clone)]
253pub struct GitStatusEntry {
254 pub(crate) repo_path: RepoPath,
255 pub(crate) status: FileStatus,
256 pub(crate) staging: StageStatus,
257}
258
259impl GitStatusEntry {
260 fn display_name(&self, path_style: PathStyle) -> String {
261 self.repo_path
262 .file_name()
263 .map(|name| name.to_owned())
264 .unwrap_or_else(|| self.repo_path.display(path_style).to_string())
265 }
266
267 fn parent_dir(&self, path_style: PathStyle) -> Option<String> {
268 self.repo_path
269 .parent()
270 .map(|parent| parent.display(path_style).to_string())
271 }
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
275enum TargetStatus {
276 Staged,
277 Unstaged,
278 Reverted,
279 Unchanged,
280}
281
282struct PendingOperation {
283 finished: bool,
284 target_status: TargetStatus,
285 entries: Vec<GitStatusEntry>,
286 op_id: usize,
287}
288
289pub struct GitPanel {
290 pub(crate) active_repository: Option<Entity<Repository>>,
291 pub(crate) commit_editor: Entity<Editor>,
292 conflicted_count: usize,
293 conflicted_staged_count: usize,
294 add_coauthors: bool,
295 generate_commit_message_task: Option<Task<Option<()>>>,
296 entries: Vec<GitListEntry>,
297 single_staged_entry: Option<GitStatusEntry>,
298 single_tracked_entry: Option<GitStatusEntry>,
299 focus_handle: FocusHandle,
300 fs: Arc<dyn Fs>,
301 new_count: usize,
302 entry_count: usize,
303 new_staged_count: usize,
304 pending: Vec<PendingOperation>,
305 pending_commit: Option<Task<()>>,
306 amend_pending: bool,
307 original_commit_message: Option<String>,
308 signoff_enabled: bool,
309 pending_serialization: Task<()>,
310 pub(crate) project: Entity<Project>,
311 scroll_handle: UniformListScrollHandle,
312 max_width_item_index: Option<usize>,
313 selected_entry: Option<usize>,
314 marked_entries: Vec<usize>,
315 tracked_count: usize,
316 tracked_staged_count: usize,
317 update_visible_entries_task: Task<()>,
318 width: Option<Pixels>,
319 workspace: WeakEntity<Workspace>,
320 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
321 modal_open: bool,
322 show_placeholders: bool,
323 local_committer: Option<GitCommitter>,
324 local_committer_task: Option<Task<()>>,
325 bulk_staging: Option<BulkStaging>,
326 stash_entries: GitStash,
327 _settings_subscription: Subscription,
328}
329
330#[derive(Clone, Debug, PartialEq, Eq)]
331struct BulkStaging {
332 repo_id: RepositoryId,
333 anchor: RepoPath,
334}
335
336const MAX_PANEL_EDITOR_LINES: usize = 6;
337
338pub(crate) fn commit_message_editor(
339 commit_message_buffer: Entity<Buffer>,
340 placeholder: Option<SharedString>,
341 project: Entity<Project>,
342 in_panel: bool,
343 window: &mut Window,
344 cx: &mut Context<Editor>,
345) -> Editor {
346 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
347 let max_lines = if in_panel { MAX_PANEL_EDITOR_LINES } else { 18 };
348 let mut commit_editor = Editor::new(
349 EditorMode::AutoHeight {
350 min_lines: max_lines,
351 max_lines: Some(max_lines),
352 },
353 buffer,
354 None,
355 window,
356 cx,
357 );
358 commit_editor.set_collaboration_hub(Box::new(project));
359 commit_editor.set_use_autoclose(false);
360 commit_editor.set_show_gutter(false, cx);
361 commit_editor.set_use_modal_editing(true);
362 commit_editor.set_show_wrap_guides(false, cx);
363 commit_editor.set_show_indent_guides(false, cx);
364 let placeholder = placeholder.unwrap_or("Enter commit message".into());
365 commit_editor.set_placeholder_text(&placeholder, window, cx);
366 commit_editor
367}
368
369impl GitPanel {
370 fn new(
371 workspace: &mut Workspace,
372 window: &mut Window,
373 cx: &mut Context<Workspace>,
374 ) -> Entity<Self> {
375 let project = workspace.project().clone();
376 let app_state = workspace.app_state().clone();
377 let fs = app_state.fs.clone();
378 let git_store = project.read(cx).git_store().clone();
379 let active_repository = project.read(cx).active_repository(cx);
380
381 cx.new(|cx| {
382 let focus_handle = cx.focus_handle();
383 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
384
385 let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
386 cx.observe_global_in::<SettingsStore>(window, move |this, window, cx| {
387 let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
388 if is_sort_by_path != was_sort_by_path {
389 this.entries.clear();
390 this.update_visible_entries(window, cx);
391 }
392 was_sort_by_path = is_sort_by_path
393 })
394 .detach();
395
396 // just to let us render a placeholder editor.
397 // Once the active git repo is set, this buffer will be replaced.
398 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
399 let commit_editor = cx.new(|cx| {
400 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
401 });
402
403 commit_editor.update(cx, |editor, cx| {
404 editor.clear(window, cx);
405 });
406
407 let scroll_handle = UniformListScrollHandle::new();
408
409 let mut was_ai_enabled = AgentSettings::get_global(cx).enabled(cx);
410 let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {
411 let is_ai_enabled = AgentSettings::get_global(cx).enabled(cx);
412 if was_ai_enabled != is_ai_enabled {
413 was_ai_enabled = is_ai_enabled;
414 cx.notify();
415 }
416 });
417
418 cx.subscribe_in(
419 &git_store,
420 window,
421 move |this, _git_store, event, window, cx| match event {
422 GitStoreEvent::ActiveRepositoryChanged(_) => {
423 this.active_repository = this.project.read(cx).active_repository(cx);
424 this.schedule_update(true, window, cx);
425 }
426 GitStoreEvent::RepositoryUpdated(
427 _,
428 RepositoryEvent::StatusesChanged { full_scan: true }
429 | RepositoryEvent::BranchChanged
430 | RepositoryEvent::MergeHeadsChanged,
431 true,
432 ) => {
433 this.schedule_update(true, window, cx);
434 }
435 GitStoreEvent::RepositoryUpdated(
436 _,
437 RepositoryEvent::StatusesChanged { full_scan: false },
438 true,
439 )
440 | GitStoreEvent::RepositoryAdded
441 | GitStoreEvent::RepositoryRemoved(_) => {
442 this.schedule_update(false, window, cx);
443 }
444 GitStoreEvent::IndexWriteError(error) => {
445 this.workspace
446 .update(cx, |workspace, cx| {
447 workspace.show_error(error, cx);
448 })
449 .ok();
450 }
451 GitStoreEvent::RepositoryUpdated(_, _, _) => {}
452 GitStoreEvent::JobsUpdated | GitStoreEvent::ConflictsUpdated => {}
453 },
454 )
455 .detach();
456
457 let mut this = Self {
458 active_repository,
459 commit_editor,
460 conflicted_count: 0,
461 conflicted_staged_count: 0,
462 add_coauthors: true,
463 generate_commit_message_task: None,
464 entries: Vec::new(),
465 focus_handle: cx.focus_handle(),
466 fs,
467 new_count: 0,
468 new_staged_count: 0,
469 pending: Vec::new(),
470 pending_commit: None,
471 amend_pending: false,
472 original_commit_message: None,
473 signoff_enabled: false,
474 pending_serialization: Task::ready(()),
475 single_staged_entry: None,
476 single_tracked_entry: None,
477 project,
478 scroll_handle,
479 max_width_item_index: None,
480 selected_entry: None,
481 marked_entries: Vec::new(),
482 tracked_count: 0,
483 tracked_staged_count: 0,
484 update_visible_entries_task: Task::ready(()),
485 width: None,
486 show_placeholders: false,
487 local_committer: None,
488 local_committer_task: None,
489 context_menu: None,
490 workspace: workspace.weak_handle(),
491 modal_open: false,
492 entry_count: 0,
493 bulk_staging: None,
494 stash_entries: Default::default(),
495 _settings_subscription,
496 };
497
498 this.schedule_update(false, window, cx);
499 this
500 })
501 }
502
503 pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> {
504 if GitPanelSettings::get_global(cx).sort_by_path {
505 return self
506 .entries
507 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
508 .ok();
509 }
510
511 if self.conflicted_count > 0 {
512 let conflicted_start = 1;
513 if let Ok(ix) = self.entries[conflicted_start..conflicted_start + self.conflicted_count]
514 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
515 {
516 return Some(conflicted_start + ix);
517 }
518 }
519 if self.tracked_count > 0 {
520 let tracked_start = if self.conflicted_count > 0 {
521 1 + self.conflicted_count
522 } else {
523 0
524 } + 1;
525 if let Ok(ix) = self.entries[tracked_start..tracked_start + self.tracked_count]
526 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
527 {
528 return Some(tracked_start + ix);
529 }
530 }
531 if self.new_count > 0 {
532 let untracked_start = if self.conflicted_count > 0 {
533 1 + self.conflicted_count
534 } else {
535 0
536 } + if self.tracked_count > 0 {
537 1 + self.tracked_count
538 } else {
539 0
540 } + 1;
541 if let Ok(ix) = self.entries[untracked_start..untracked_start + self.new_count]
542 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(path))
543 {
544 return Some(untracked_start + ix);
545 }
546 }
547 None
548 }
549
550 pub fn select_entry_by_path(
551 &mut self,
552 path: ProjectPath,
553 _: &mut Window,
554 cx: &mut Context<Self>,
555 ) {
556 let Some(git_repo) = self.active_repository.as_ref() else {
557 return;
558 };
559 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path, cx) else {
560 return;
561 };
562 let Some(ix) = self.entry_by_path(&repo_path, cx) else {
563 return;
564 };
565 self.selected_entry = Some(ix);
566 cx.notify();
567 }
568
569 fn serialization_key(workspace: &Workspace) -> Option<String> {
570 workspace
571 .database_id()
572 .map(|id| i64::from(id).to_string())
573 .or(workspace.session_id())
574 .map(|id| format!("{}-{:?}", GIT_PANEL_KEY, id))
575 }
576
577 fn serialize(&mut self, cx: &mut Context<Self>) {
578 let width = self.width;
579 let amend_pending = self.amend_pending;
580 let signoff_enabled = self.signoff_enabled;
581
582 self.pending_serialization = cx.spawn(async move |git_panel, cx| {
583 cx.background_executor()
584 .timer(SERIALIZATION_THROTTLE_TIME)
585 .await;
586 let Some(serialization_key) = git_panel
587 .update(cx, |git_panel, cx| {
588 git_panel
589 .workspace
590 .read_with(cx, |workspace, _| Self::serialization_key(workspace))
591 .ok()
592 .flatten()
593 })
594 .ok()
595 .flatten()
596 else {
597 return;
598 };
599 cx.background_spawn(
600 async move {
601 KEY_VALUE_STORE
602 .write_kvp(
603 serialization_key,
604 serde_json::to_string(&SerializedGitPanel {
605 width,
606 amend_pending,
607 signoff_enabled,
608 })?,
609 )
610 .await?;
611 anyhow::Ok(())
612 }
613 .log_err(),
614 )
615 .await;
616 });
617 }
618
619 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
620 self.modal_open = open;
621 cx.notify();
622 }
623
624 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
625 let mut dispatch_context = KeyContext::new_with_defaults();
626 dispatch_context.add("GitPanel");
627
628 if window
629 .focused(cx)
630 .is_some_and(|focused| self.focus_handle == focused)
631 {
632 dispatch_context.add("menu");
633 dispatch_context.add("ChangesList");
634 }
635
636 if self.commit_editor.read(cx).is_focused(window) {
637 dispatch_context.add("CommitEditor");
638 }
639
640 dispatch_context
641 }
642
643 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
644 cx.emit(PanelEvent::Close);
645 }
646
647 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
648 if !self.focus_handle.contains_focused(window, cx) {
649 cx.emit(Event::Focus);
650 }
651 }
652
653 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
654 if let Some(selected_entry) = self.selected_entry {
655 self.scroll_handle
656 .scroll_to_item(selected_entry, ScrollStrategy::Center);
657 }
658
659 cx.notify();
660 }
661
662 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
663 if !self.entries.is_empty() {
664 self.selected_entry = Some(1);
665 self.scroll_to_selected_entry(cx);
666 }
667 }
668
669 fn select_previous(
670 &mut self,
671 _: &SelectPrevious,
672 _window: &mut Window,
673 cx: &mut Context<Self>,
674 ) {
675 let item_count = self.entries.len();
676 if item_count == 0 {
677 return;
678 }
679
680 if let Some(selected_entry) = self.selected_entry {
681 let new_selected_entry = if selected_entry > 0 {
682 selected_entry - 1
683 } else {
684 selected_entry
685 };
686
687 if matches!(
688 self.entries.get(new_selected_entry),
689 Some(GitListEntry::Header(..))
690 ) {
691 if new_selected_entry > 0 {
692 self.selected_entry = Some(new_selected_entry - 1)
693 }
694 } else {
695 self.selected_entry = Some(new_selected_entry);
696 }
697
698 self.scroll_to_selected_entry(cx);
699 }
700
701 cx.notify();
702 }
703
704 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
705 let item_count = self.entries.len();
706 if item_count == 0 {
707 return;
708 }
709
710 if let Some(selected_entry) = self.selected_entry {
711 let new_selected_entry = if selected_entry < item_count - 1 {
712 selected_entry + 1
713 } else {
714 selected_entry
715 };
716 if matches!(
717 self.entries.get(new_selected_entry),
718 Some(GitListEntry::Header(..))
719 ) {
720 self.selected_entry = Some(new_selected_entry + 1);
721 } else {
722 self.selected_entry = Some(new_selected_entry);
723 }
724
725 self.scroll_to_selected_entry(cx);
726 }
727
728 cx.notify();
729 }
730
731 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
732 if self.entries.last().is_some() {
733 self.selected_entry = Some(self.entries.len() - 1);
734 self.scroll_to_selected_entry(cx);
735 }
736 }
737
738 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
739 self.commit_editor.update(cx, |editor, cx| {
740 window.focus(&editor.focus_handle(cx));
741 });
742 cx.notify();
743 }
744
745 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
746 let have_entries = self
747 .active_repository
748 .as_ref()
749 .is_some_and(|active_repository| active_repository.read(cx).status_summary().count > 0);
750 if have_entries && self.selected_entry.is_none() {
751 self.selected_entry = Some(1);
752 self.scroll_to_selected_entry(cx);
753 cx.notify();
754 }
755 }
756
757 fn focus_changes_list(
758 &mut self,
759 _: &FocusChanges,
760 window: &mut Window,
761 cx: &mut Context<Self>,
762 ) {
763 self.select_first_entry_if_none(cx);
764
765 cx.focus_self(window);
766 cx.notify();
767 }
768
769 fn get_selected_entry(&self) -> Option<&GitListEntry> {
770 self.selected_entry.and_then(|i| self.entries.get(i))
771 }
772
773 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
774 maybe!({
775 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
776 let workspace = self.workspace.upgrade()?;
777 let git_repo = self.active_repository.as_ref()?;
778
779 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx)
780 && let Some(project_path) = project_diff.read(cx).active_path(cx)
781 && Some(&entry.repo_path)
782 == git_repo
783 .read(cx)
784 .project_path_to_repo_path(&project_path, cx)
785 .as_ref()
786 {
787 project_diff.focus_handle(cx).focus(window);
788 project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
789 return None;
790 };
791
792 self.workspace
793 .update(cx, |workspace, cx| {
794 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
795 })
796 .ok();
797 self.focus_handle.focus(window);
798
799 Some(())
800 });
801 }
802
803 fn open_file(
804 &mut self,
805 _: &menu::SecondaryConfirm,
806 window: &mut Window,
807 cx: &mut Context<Self>,
808 ) {
809 maybe!({
810 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
811 let active_repo = self.active_repository.as_ref()?;
812 let path = active_repo
813 .read(cx)
814 .repo_path_to_project_path(&entry.repo_path, cx)?;
815 if entry.status.is_deleted() {
816 return None;
817 }
818
819 self.workspace
820 .update(cx, |workspace, cx| {
821 workspace
822 .open_path_preview(path, None, false, false, true, window, cx)
823 .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
824 Some(format!("{e}"))
825 });
826 })
827 .ok()
828 });
829 }
830
831 fn revert_selected(
832 &mut self,
833 action: &git::RestoreFile,
834 window: &mut Window,
835 cx: &mut Context<Self>,
836 ) {
837 let path_style = self.project.read(cx).path_style(cx);
838 maybe!({
839 let list_entry = self.entries.get(self.selected_entry?)?.clone();
840 let entry = list_entry.status_entry()?.to_owned();
841 let skip_prompt = action.skip_prompt || entry.status.is_created();
842
843 let prompt = if skip_prompt {
844 Task::ready(Ok(0))
845 } else {
846 let prompt = window.prompt(
847 PromptLevel::Warning,
848 &format!(
849 "Are you sure you want to restore {}?",
850 entry
851 .repo_path
852 .file_name()
853 .unwrap_or(entry.repo_path.display(path_style).as_ref()),
854 ),
855 None,
856 &["Restore", "Cancel"],
857 cx,
858 );
859 cx.background_spawn(prompt)
860 };
861
862 let this = cx.weak_entity();
863 window
864 .spawn(cx, async move |cx| {
865 if prompt.await? != 0 {
866 return anyhow::Ok(());
867 }
868
869 this.update_in(cx, |this, window, cx| {
870 this.revert_entry(&entry, window, cx);
871 })?;
872
873 Ok(())
874 })
875 .detach();
876 Some(())
877 });
878 }
879
880 fn add_to_gitignore(
881 &mut self,
882 _: &git::AddToGitignore,
883 _window: &mut Window,
884 cx: &mut Context<Self>,
885 ) {
886 maybe!({
887 let list_entry = self.entries.get(self.selected_entry?)?.clone();
888 let entry = list_entry.status_entry()?.to_owned();
889
890 if !entry.status.is_created() {
891 return Some(());
892 }
893
894 let project = self.project.downgrade();
895 let repo_path = entry.repo_path;
896 let active_repository = self.active_repository.as_ref()?.downgrade();
897
898 cx.spawn(async move |_, cx| {
899 let file_path_str = repo_path.0.display(PathStyle::Posix);
900
901 let repo_root = active_repository.read_with(cx, |repository, _| {
902 repository.snapshot().work_directory_abs_path
903 })?;
904
905 let gitignore_abs_path = repo_root.join(".gitignore");
906
907 let buffer = project
908 .update(cx, |project, cx| {
909 project.open_local_buffer(gitignore_abs_path, cx)
910 })?
911 .await?;
912
913 let mut should_save = false;
914 buffer.update(cx, |buffer, cx| {
915 let existing_content = buffer.text();
916
917 if existing_content
918 .lines()
919 .any(|line| line.trim() == file_path_str)
920 {
921 return;
922 }
923
924 let insert_position = existing_content.len();
925 let new_entry = if existing_content.is_empty() {
926 format!("{}\n", file_path_str)
927 } else if existing_content.ends_with('\n') {
928 format!("{}\n", file_path_str)
929 } else {
930 format!("\n{}\n", file_path_str)
931 };
932
933 buffer.edit([(insert_position..insert_position, new_entry)], None, cx);
934 should_save = true;
935 })?;
936
937 if should_save {
938 project
939 .update(cx, |project, cx| project.save_buffer(buffer, cx))?
940 .await?;
941 }
942
943 anyhow::Ok(())
944 })
945 .detach_and_log_err(cx);
946
947 Some(())
948 });
949 }
950
951 fn revert_entry(
952 &mut self,
953 entry: &GitStatusEntry,
954 window: &mut Window,
955 cx: &mut Context<Self>,
956 ) {
957 maybe!({
958 let active_repo = self.active_repository.clone()?;
959 let path = active_repo
960 .read(cx)
961 .repo_path_to_project_path(&entry.repo_path, cx)?;
962 let workspace = self.workspace.clone();
963
964 if entry.status.staging().has_staged() {
965 self.change_file_stage(false, vec![entry.clone()], cx);
966 }
967 let filename = path.path.file_name()?.to_string();
968
969 if !entry.status.is_created() {
970 self.perform_checkout(vec![entry.clone()], window, cx);
971 } else {
972 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
973 cx.spawn_in(window, async move |_, cx| {
974 match prompt.await? {
975 TrashCancel::Trash => {}
976 TrashCancel::Cancel => return Ok(()),
977 }
978 let task = workspace.update(cx, |workspace, cx| {
979 workspace
980 .project()
981 .update(cx, |project, cx| project.delete_file(path, true, cx))
982 })?;
983 if let Some(task) = task {
984 task.await?;
985 }
986 Ok(())
987 })
988 .detach_and_prompt_err(
989 "Failed to trash file",
990 window,
991 cx,
992 |e, _, _| Some(format!("{e}")),
993 );
994 }
995 Some(())
996 });
997 }
998
999 fn perform_checkout(
1000 &mut self,
1001 entries: Vec<GitStatusEntry>,
1002 window: &mut Window,
1003 cx: &mut Context<Self>,
1004 ) {
1005 let workspace = self.workspace.clone();
1006 let Some(active_repository) = self.active_repository.clone() else {
1007 return;
1008 };
1009
1010 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1011 self.pending.push(PendingOperation {
1012 op_id,
1013 target_status: TargetStatus::Reverted,
1014 entries: entries.clone(),
1015 finished: false,
1016 });
1017 self.update_visible_entries(window, cx);
1018 let task = cx.spawn(async move |_, cx| {
1019 let tasks: Vec<_> = workspace.update(cx, |workspace, cx| {
1020 workspace.project().update(cx, |project, cx| {
1021 entries
1022 .iter()
1023 .filter_map(|entry| {
1024 let path = active_repository
1025 .read(cx)
1026 .repo_path_to_project_path(&entry.repo_path, cx)?;
1027 Some(project.open_buffer(path, cx))
1028 })
1029 .collect()
1030 })
1031 })?;
1032
1033 let buffers = futures::future::join_all(tasks).await;
1034
1035 active_repository
1036 .update(cx, |repo, cx| {
1037 repo.checkout_files(
1038 "HEAD",
1039 entries
1040 .into_iter()
1041 .map(|entries| entries.repo_path)
1042 .collect(),
1043 cx,
1044 )
1045 })?
1046 .await??;
1047
1048 let tasks: Vec<_> = cx.update(|cx| {
1049 buffers
1050 .iter()
1051 .filter_map(|buffer| {
1052 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
1053 buffer.is_dirty().then(|| buffer.reload(cx))
1054 })
1055 })
1056 .collect()
1057 })?;
1058
1059 futures::future::join_all(tasks).await;
1060
1061 Ok(())
1062 });
1063
1064 cx.spawn_in(window, async move |this, cx| {
1065 let result = task.await;
1066
1067 this.update_in(cx, |this, window, cx| {
1068 for pending in this.pending.iter_mut() {
1069 if pending.op_id == op_id {
1070 pending.finished = true;
1071 if result.is_err() {
1072 pending.target_status = TargetStatus::Unchanged;
1073 this.update_visible_entries(window, cx);
1074 }
1075 break;
1076 }
1077 }
1078 result
1079 .map_err(|e| {
1080 this.show_error_toast("checkout", e, cx);
1081 })
1082 .ok();
1083 })
1084 .ok();
1085 })
1086 .detach();
1087 }
1088
1089 fn restore_tracked_files(
1090 &mut self,
1091 _: &RestoreTrackedFiles,
1092 window: &mut Window,
1093 cx: &mut Context<Self>,
1094 ) {
1095 let entries = self
1096 .entries
1097 .iter()
1098 .filter_map(|entry| entry.status_entry().cloned())
1099 .filter(|status_entry| !status_entry.status.is_created())
1100 .collect::<Vec<_>>();
1101
1102 match entries.len() {
1103 0 => return,
1104 1 => return self.revert_entry(&entries[0], window, cx),
1105 _ => {}
1106 }
1107 let mut details = entries
1108 .iter()
1109 .filter_map(|entry| entry.repo_path.0.file_name())
1110 .map(|filename| filename.to_string())
1111 .take(5)
1112 .join("\n");
1113 if entries.len() > 5 {
1114 details.push_str(&format!("\nand {} more…", entries.len() - 5))
1115 }
1116
1117 #[derive(strum::EnumIter, strum::VariantNames)]
1118 #[strum(serialize_all = "title_case")]
1119 enum RestoreCancel {
1120 RestoreTrackedFiles,
1121 Cancel,
1122 }
1123 let prompt = prompt(
1124 "Discard changes to these files?",
1125 Some(&details),
1126 window,
1127 cx,
1128 );
1129 cx.spawn_in(window, async move |this, cx| {
1130 if let Ok(RestoreCancel::RestoreTrackedFiles) = prompt.await {
1131 this.update_in(cx, |this, window, cx| {
1132 this.perform_checkout(entries, window, cx);
1133 })
1134 .ok();
1135 }
1136 })
1137 .detach();
1138 }
1139
1140 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1141 let workspace = self.workspace.clone();
1142 let Some(active_repo) = self.active_repository.clone() else {
1143 return;
1144 };
1145 let to_delete = self
1146 .entries
1147 .iter()
1148 .filter_map(|entry| entry.status_entry())
1149 .filter(|status_entry| status_entry.status.is_created())
1150 .cloned()
1151 .collect::<Vec<_>>();
1152
1153 match to_delete.len() {
1154 0 => return,
1155 1 => return self.revert_entry(&to_delete[0], window, cx),
1156 _ => {}
1157 };
1158
1159 let mut details = to_delete
1160 .iter()
1161 .map(|entry| {
1162 entry
1163 .repo_path
1164 .0
1165 .file_name()
1166 .map(|f| f.to_string())
1167 .unwrap_or_default()
1168 })
1169 .take(5)
1170 .join("\n");
1171
1172 if to_delete.len() > 5 {
1173 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1174 }
1175
1176 let prompt = prompt("Trash these files?", Some(&details), window, cx);
1177 cx.spawn_in(window, async move |this, cx| {
1178 match prompt.await? {
1179 TrashCancel::Trash => {}
1180 TrashCancel::Cancel => return Ok(()),
1181 }
1182 let tasks = workspace.update(cx, |workspace, cx| {
1183 to_delete
1184 .iter()
1185 .filter_map(|entry| {
1186 workspace.project().update(cx, |project, cx| {
1187 let project_path = active_repo
1188 .read(cx)
1189 .repo_path_to_project_path(&entry.repo_path, cx)?;
1190 project.delete_file(project_path, true, cx)
1191 })
1192 })
1193 .collect::<Vec<_>>()
1194 })?;
1195 let to_unstage = to_delete
1196 .into_iter()
1197 .filter(|entry| !entry.status.staging().is_fully_unstaged())
1198 .collect();
1199 this.update(cx, |this, cx| this.change_file_stage(false, to_unstage, cx))?;
1200 for task in tasks {
1201 task.await?;
1202 }
1203 Ok(())
1204 })
1205 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1206 Some(format!("{e}"))
1207 });
1208 }
1209
1210 pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1211 let entries = self
1212 .entries
1213 .iter()
1214 .filter_map(|entry| entry.status_entry())
1215 .filter(|status_entry| status_entry.staging.has_unstaged())
1216 .cloned()
1217 .collect::<Vec<_>>();
1218 self.change_file_stage(true, entries, cx);
1219 }
1220
1221 pub fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1222 let entries = self
1223 .entries
1224 .iter()
1225 .filter_map(|entry| entry.status_entry())
1226 .filter(|status_entry| status_entry.staging.has_staged())
1227 .cloned()
1228 .collect::<Vec<_>>();
1229 self.change_file_stage(false, entries, cx);
1230 }
1231
1232 fn toggle_staged_for_entry(
1233 &mut self,
1234 entry: &GitListEntry,
1235 _window: &mut Window,
1236 cx: &mut Context<Self>,
1237 ) {
1238 let Some(active_repository) = self.active_repository.as_ref() else {
1239 return;
1240 };
1241 let (stage, repo_paths) = match entry {
1242 GitListEntry::Status(status_entry) => {
1243 if status_entry.status.staging().is_fully_staged() {
1244 if let Some(op) = self.bulk_staging.clone()
1245 && op.anchor == status_entry.repo_path
1246 {
1247 self.bulk_staging = None;
1248 }
1249
1250 (false, vec![status_entry.clone()])
1251 } else {
1252 self.set_bulk_staging_anchor(status_entry.repo_path.clone(), cx);
1253
1254 (true, vec![status_entry.clone()])
1255 }
1256 }
1257 GitListEntry::Header(section) => {
1258 let goal_staged_state = !self.header_state(section.header).selected();
1259 let repository = active_repository.read(cx);
1260 let entries = self
1261 .entries
1262 .iter()
1263 .filter_map(|entry| entry.status_entry())
1264 .filter(|status_entry| {
1265 section.contains(status_entry, repository)
1266 && status_entry.staging.as_bool() != Some(goal_staged_state)
1267 })
1268 .cloned()
1269 .collect::<Vec<_>>();
1270
1271 (goal_staged_state, entries)
1272 }
1273 };
1274 self.change_file_stage(stage, repo_paths, cx);
1275 }
1276
1277 fn change_file_stage(
1278 &mut self,
1279 stage: bool,
1280 entries: Vec<GitStatusEntry>,
1281 cx: &mut Context<Self>,
1282 ) {
1283 let Some(active_repository) = self.active_repository.clone() else {
1284 return;
1285 };
1286 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1287 self.pending.push(PendingOperation {
1288 op_id,
1289 target_status: if stage {
1290 TargetStatus::Staged
1291 } else {
1292 TargetStatus::Unstaged
1293 },
1294 entries: entries.clone(),
1295 finished: false,
1296 });
1297 let repository = active_repository.read(cx);
1298 self.update_counts(repository);
1299 cx.notify();
1300
1301 cx.spawn({
1302 async move |this, cx| {
1303 let result = cx
1304 .update(|cx| {
1305 if stage {
1306 active_repository.update(cx, |repo, cx| {
1307 let repo_paths = entries
1308 .iter()
1309 .map(|entry| entry.repo_path.clone())
1310 .collect();
1311 repo.stage_entries(repo_paths, cx)
1312 })
1313 } else {
1314 active_repository.update(cx, |repo, cx| {
1315 let repo_paths = entries
1316 .iter()
1317 .map(|entry| entry.repo_path.clone())
1318 .collect();
1319 repo.unstage_entries(repo_paths, cx)
1320 })
1321 }
1322 })?
1323 .await;
1324
1325 this.update(cx, |this, cx| {
1326 for pending in this.pending.iter_mut() {
1327 if pending.op_id == op_id {
1328 pending.finished = true
1329 }
1330 }
1331 result
1332 .map_err(|e| {
1333 this.show_error_toast(if stage { "add" } else { "reset" }, e, cx);
1334 })
1335 .ok();
1336 cx.notify();
1337 })
1338 }
1339 })
1340 .detach();
1341 }
1342
1343 pub fn total_staged_count(&self) -> usize {
1344 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1345 }
1346
1347 pub fn stash_pop(&mut self, _: &StashPop, _window: &mut Window, cx: &mut Context<Self>) {
1348 let Some(active_repository) = self.active_repository.clone() else {
1349 return;
1350 };
1351
1352 cx.spawn({
1353 async move |this, cx| {
1354 let stash_task = active_repository
1355 .update(cx, |repo, cx| repo.stash_pop(None, cx))?
1356 .await;
1357 this.update(cx, |this, cx| {
1358 stash_task
1359 .map_err(|e| {
1360 this.show_error_toast("stash pop", e, cx);
1361 })
1362 .ok();
1363 cx.notify();
1364 })
1365 }
1366 })
1367 .detach();
1368 }
1369
1370 pub fn stash_apply(&mut self, _: &StashApply, _window: &mut Window, cx: &mut Context<Self>) {
1371 let Some(active_repository) = self.active_repository.clone() else {
1372 return;
1373 };
1374
1375 cx.spawn({
1376 async move |this, cx| {
1377 let stash_task = active_repository
1378 .update(cx, |repo, cx| repo.stash_apply(None, cx))?
1379 .await;
1380 this.update(cx, |this, cx| {
1381 stash_task
1382 .map_err(|e| {
1383 this.show_error_toast("stash apply", e, cx);
1384 })
1385 .ok();
1386 cx.notify();
1387 })
1388 }
1389 })
1390 .detach();
1391 }
1392
1393 pub fn stash_all(&mut self, _: &StashAll, _window: &mut Window, cx: &mut Context<Self>) {
1394 let Some(active_repository) = self.active_repository.clone() else {
1395 return;
1396 };
1397
1398 cx.spawn({
1399 async move |this, cx| {
1400 let stash_task = active_repository
1401 .update(cx, |repo, cx| repo.stash_all(cx))?
1402 .await;
1403 this.update(cx, |this, cx| {
1404 stash_task
1405 .map_err(|e| {
1406 this.show_error_toast("stash", e, cx);
1407 })
1408 .ok();
1409 cx.notify();
1410 })
1411 }
1412 })
1413 .detach();
1414 }
1415
1416 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1417 self.commit_editor
1418 .read(cx)
1419 .buffer()
1420 .read(cx)
1421 .as_singleton()
1422 .unwrap()
1423 }
1424
1425 fn toggle_staged_for_selected(
1426 &mut self,
1427 _: &git::ToggleStaged,
1428 window: &mut Window,
1429 cx: &mut Context<Self>,
1430 ) {
1431 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1432 self.toggle_staged_for_entry(&selected_entry, window, cx);
1433 }
1434 }
1435
1436 fn stage_range(&mut self, _: &git::StageRange, _window: &mut Window, cx: &mut Context<Self>) {
1437 let Some(index) = self.selected_entry else {
1438 return;
1439 };
1440 self.stage_bulk(index, cx);
1441 }
1442
1443 fn stage_selected(&mut self, _: &git::StageFile, _window: &mut Window, cx: &mut Context<Self>) {
1444 let Some(selected_entry) = self.get_selected_entry() else {
1445 return;
1446 };
1447 let Some(status_entry) = selected_entry.status_entry() else {
1448 return;
1449 };
1450 if status_entry.staging != StageStatus::Staged {
1451 self.change_file_stage(true, vec![status_entry.clone()], cx);
1452 }
1453 }
1454
1455 fn unstage_selected(
1456 &mut self,
1457 _: &git::UnstageFile,
1458 _window: &mut Window,
1459 cx: &mut Context<Self>,
1460 ) {
1461 let Some(selected_entry) = self.get_selected_entry() else {
1462 return;
1463 };
1464 let Some(status_entry) = selected_entry.status_entry() else {
1465 return;
1466 };
1467 if status_entry.staging != StageStatus::Unstaged {
1468 self.change_file_stage(false, vec![status_entry.clone()], cx);
1469 }
1470 }
1471
1472 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1473 if self.amend_pending {
1474 return;
1475 }
1476 if self
1477 .commit_editor
1478 .focus_handle(cx)
1479 .contains_focused(window, cx)
1480 {
1481 telemetry::event!("Git Committed", source = "Git Panel");
1482 self.commit_changes(
1483 CommitOptions {
1484 amend: false,
1485 signoff: self.signoff_enabled,
1486 },
1487 window,
1488 cx,
1489 )
1490 } else {
1491 cx.propagate();
1492 }
1493 }
1494
1495 fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
1496 if self
1497 .commit_editor
1498 .focus_handle(cx)
1499 .contains_focused(window, cx)
1500 {
1501 if self.head_commit(cx).is_some() {
1502 if !self.amend_pending {
1503 self.set_amend_pending(true, cx);
1504 self.load_last_commit_message_if_empty(cx);
1505 } else {
1506 telemetry::event!("Git Amended", source = "Git Panel");
1507 self.commit_changes(
1508 CommitOptions {
1509 amend: true,
1510 signoff: self.signoff_enabled,
1511 },
1512 window,
1513 cx,
1514 );
1515 }
1516 }
1517 } else {
1518 cx.propagate();
1519 }
1520 }
1521
1522 pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
1523 self.active_repository
1524 .as_ref()
1525 .and_then(|repo| repo.read(cx).head_commit.as_ref())
1526 .cloned()
1527 }
1528
1529 pub fn load_last_commit_message_if_empty(&mut self, cx: &mut Context<Self>) {
1530 if !self.commit_editor.read(cx).is_empty(cx) {
1531 return;
1532 }
1533 let Some(head_commit) = self.head_commit(cx) else {
1534 return;
1535 };
1536 let recent_sha = head_commit.sha.to_string();
1537 let detail_task = self.load_commit_details(recent_sha, cx);
1538 cx.spawn(async move |this, cx| {
1539 if let Ok(message) = detail_task.await.map(|detail| detail.message) {
1540 this.update(cx, |this, cx| {
1541 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1542 let start = buffer.anchor_before(0);
1543 let end = buffer.anchor_after(buffer.len());
1544 buffer.edit([(start..end, message)], None, cx);
1545 });
1546 })
1547 .log_err();
1548 }
1549 })
1550 .detach();
1551 }
1552
1553 fn custom_or_suggested_commit_message(
1554 &self,
1555 window: &mut Window,
1556 cx: &mut Context<Self>,
1557 ) -> Option<String> {
1558 let git_commit_language = self.commit_editor.read(cx).language_at(0, cx);
1559 let message = self.commit_editor.read(cx).text(cx);
1560 if message.is_empty() {
1561 return self
1562 .suggest_commit_message(cx)
1563 .filter(|message| !message.trim().is_empty());
1564 } else if message.trim().is_empty() {
1565 return None;
1566 }
1567 let buffer = cx.new(|cx| {
1568 let mut buffer = Buffer::local(message, cx);
1569 buffer.set_language(git_commit_language, cx);
1570 buffer
1571 });
1572 let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
1573 let wrapped_message = editor.update(cx, |editor, cx| {
1574 editor.select_all(&Default::default(), window, cx);
1575 editor.rewrap(&Default::default(), window, cx);
1576 editor.text(cx)
1577 });
1578 if wrapped_message.trim().is_empty() {
1579 return None;
1580 }
1581 Some(wrapped_message)
1582 }
1583
1584 fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
1585 let text = self.commit_editor.read(cx).text(cx);
1586 if !text.trim().is_empty() {
1587 true
1588 } else if text.is_empty() {
1589 self.suggest_commit_message(cx)
1590 .is_some_and(|text| !text.trim().is_empty())
1591 } else {
1592 false
1593 }
1594 }
1595
1596 pub(crate) fn commit_changes(
1597 &mut self,
1598 options: CommitOptions,
1599 window: &mut Window,
1600 cx: &mut Context<Self>,
1601 ) {
1602 let Some(active_repository) = self.active_repository.clone() else {
1603 return;
1604 };
1605 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1606 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1607 cx.spawn(async move |_| {
1608 prompt.await.ok();
1609 })
1610 .detach();
1611 };
1612
1613 if self.has_unstaged_conflicts() {
1614 error_spawn(
1615 "There are still conflicts. You must stage these before committing",
1616 window,
1617 cx,
1618 );
1619 return;
1620 }
1621
1622 let commit_message = self.custom_or_suggested_commit_message(window, cx);
1623
1624 let Some(mut message) = commit_message else {
1625 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1626 return;
1627 };
1628
1629 if self.add_coauthors {
1630 self.fill_co_authors(&mut message, cx);
1631 }
1632
1633 let task = if self.has_staged_changes() {
1634 // Repository serializes all git operations, so we can just send a commit immediately
1635 let commit_task = active_repository.update(cx, |repo, cx| {
1636 repo.commit(message.into(), None, options, cx)
1637 });
1638 cx.background_spawn(async move { commit_task.await? })
1639 } else {
1640 let changed_files = self
1641 .entries
1642 .iter()
1643 .filter_map(|entry| entry.status_entry())
1644 .filter(|status_entry| !status_entry.status.is_created())
1645 .map(|status_entry| status_entry.repo_path.clone())
1646 .collect::<Vec<_>>();
1647
1648 if changed_files.is_empty() && !options.amend {
1649 error_spawn("No changes to commit", window, cx);
1650 return;
1651 }
1652
1653 let stage_task =
1654 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1655 cx.spawn(async move |_, cx| {
1656 stage_task.await?;
1657 let commit_task = active_repository.update(cx, |repo, cx| {
1658 repo.commit(message.into(), None, options, cx)
1659 })?;
1660 commit_task.await?
1661 })
1662 };
1663 let task = cx.spawn_in(window, async move |this, cx| {
1664 let result = task.await;
1665 this.update_in(cx, |this, window, cx| {
1666 this.pending_commit.take();
1667 match result {
1668 Ok(()) => {
1669 this.commit_editor
1670 .update(cx, |editor, cx| editor.clear(window, cx));
1671 this.original_commit_message = None;
1672 }
1673 Err(e) => this.show_error_toast("commit", e, cx),
1674 }
1675 })
1676 .ok();
1677 });
1678
1679 self.pending_commit = Some(task);
1680 if options.amend {
1681 self.set_amend_pending(false, cx);
1682 }
1683 }
1684
1685 pub(crate) fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1686 let Some(repo) = self.active_repository.clone() else {
1687 return;
1688 };
1689 telemetry::event!("Git Uncommitted");
1690
1691 let confirmation = self.check_for_pushed_commits(window, cx);
1692 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1693
1694 let task = cx.spawn_in(window, async move |this, cx| {
1695 let result = maybe!(async {
1696 if let Ok(true) = confirmation.await {
1697 let prior_head = prior_head.await?;
1698
1699 repo.update(cx, |repo, cx| {
1700 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1701 })?
1702 .await??;
1703
1704 Ok(Some(prior_head))
1705 } else {
1706 Ok(None)
1707 }
1708 })
1709 .await;
1710
1711 this.update_in(cx, |this, window, cx| {
1712 this.pending_commit.take();
1713 match result {
1714 Ok(None) => {}
1715 Ok(Some(prior_commit)) => {
1716 this.commit_editor.update(cx, |editor, cx| {
1717 editor.set_text(prior_commit.message, window, cx)
1718 });
1719 }
1720 Err(e) => this.show_error_toast("reset", e, cx),
1721 }
1722 })
1723 .ok();
1724 });
1725
1726 self.pending_commit = Some(task);
1727 }
1728
1729 fn check_for_pushed_commits(
1730 &mut self,
1731 window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
1734 let repo = self.active_repository.clone();
1735 let mut cx = window.to_async(cx);
1736
1737 async move {
1738 let repo = repo.context("No active repository")?;
1739
1740 let pushed_to: Vec<SharedString> = repo
1741 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1742 .await??;
1743
1744 if pushed_to.is_empty() {
1745 Ok(true)
1746 } else {
1747 #[derive(strum::EnumIter, strum::VariantNames)]
1748 #[strum(serialize_all = "title_case")]
1749 enum CancelUncommit {
1750 Uncommit,
1751 Cancel,
1752 }
1753 let detail = format!(
1754 "This commit was already pushed to {}.",
1755 pushed_to.into_iter().join(", ")
1756 );
1757 let result = cx
1758 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1759 .await?;
1760
1761 match result {
1762 CancelUncommit::Cancel => Ok(false),
1763 CancelUncommit::Uncommit => Ok(true),
1764 }
1765 }
1766 }
1767 }
1768
1769 /// Suggests a commit message based on the changed files and their statuses
1770 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1771 if let Some(merge_message) = self
1772 .active_repository
1773 .as_ref()
1774 .and_then(|repo| repo.read(cx).merge.message.as_ref())
1775 {
1776 return Some(merge_message.to_string());
1777 }
1778
1779 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1780 Some(staged_entry)
1781 } else if self.total_staged_count() == 0
1782 && let Some(single_tracked_entry) = &self.single_tracked_entry
1783 {
1784 Some(single_tracked_entry)
1785 } else {
1786 None
1787 }?;
1788
1789 let action_text = if git_status_entry.status.is_deleted() {
1790 Some("Delete")
1791 } else if git_status_entry.status.is_created() {
1792 Some("Create")
1793 } else if git_status_entry.status.is_modified() {
1794 Some("Update")
1795 } else {
1796 None
1797 }?;
1798
1799 let file_name = git_status_entry
1800 .repo_path
1801 .file_name()
1802 .unwrap_or_default()
1803 .to_string();
1804
1805 Some(format!("{} {}", action_text, file_name))
1806 }
1807
1808 fn generate_commit_message_action(
1809 &mut self,
1810 _: &git::GenerateCommitMessage,
1811 _window: &mut Window,
1812 cx: &mut Context<Self>,
1813 ) {
1814 self.generate_commit_message(cx);
1815 }
1816
1817 /// Generates a commit message using an LLM.
1818 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1819 if !self.can_commit() || !AgentSettings::get_global(cx).enabled(cx) {
1820 return;
1821 }
1822
1823 let Some(ConfiguredModel { provider, model }) =
1824 LanguageModelRegistry::read_global(cx).commit_message_model()
1825 else {
1826 return;
1827 };
1828
1829 let Some(repo) = self.active_repository.as_ref() else {
1830 return;
1831 };
1832
1833 telemetry::event!("Git Commit Message Generated");
1834
1835 let diff = repo.update(cx, |repo, cx| {
1836 if self.has_staged_changes() {
1837 repo.diff(DiffType::HeadToIndex, cx)
1838 } else {
1839 repo.diff(DiffType::HeadToWorktree, cx)
1840 }
1841 });
1842
1843 let temperature = AgentSettings::temperature_for_model(&model, cx);
1844
1845 self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1846 async move {
1847 let _defer = cx.on_drop(&this, |this, _cx| {
1848 this.generate_commit_message_task.take();
1849 });
1850
1851 if let Some(task) = cx.update(|cx| {
1852 if !provider.is_authenticated(cx) {
1853 Some(provider.authenticate(cx))
1854 } else {
1855 None
1856 }
1857 })? {
1858 task.await.log_err();
1859 };
1860
1861 let mut diff_text = match diff.await {
1862 Ok(result) => match result {
1863 Ok(text) => text,
1864 Err(e) => {
1865 Self::show_commit_message_error(&this, &e, cx);
1866 return anyhow::Ok(());
1867 }
1868 },
1869 Err(e) => {
1870 Self::show_commit_message_error(&this, &e, cx);
1871 return anyhow::Ok(());
1872 }
1873 };
1874
1875 const ONE_MB: usize = 1_000_000;
1876 if diff_text.len() > ONE_MB {
1877 diff_text = diff_text.chars().take(ONE_MB).collect()
1878 }
1879
1880 let subject = this.update(cx, |this, cx| {
1881 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1882 })?;
1883
1884 let text_empty = subject.trim().is_empty();
1885
1886 let content = if text_empty {
1887 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1888 } else {
1889 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1890 };
1891
1892 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1893
1894 let request = LanguageModelRequest {
1895 thread_id: None,
1896 prompt_id: None,
1897 intent: Some(CompletionIntent::GenerateGitCommitMessage),
1898 mode: None,
1899 messages: vec![LanguageModelRequestMessage {
1900 role: Role::User,
1901 content: vec![content.into()],
1902 cache: false,
1903 }],
1904 tools: Vec::new(),
1905 tool_choice: None,
1906 stop: Vec::new(),
1907 temperature,
1908 thinking_allowed: false,
1909 };
1910
1911 let stream = model.stream_completion_text(request, cx);
1912 match stream.await {
1913 Ok(mut messages) => {
1914 if !text_empty {
1915 this.update(cx, |this, cx| {
1916 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1917 let insert_position = buffer.anchor_before(buffer.len());
1918 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1919 });
1920 })?;
1921 }
1922
1923 while let Some(message) = messages.stream.next().await {
1924 match message {
1925 Ok(text) => {
1926 this.update(cx, |this, cx| {
1927 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1928 let insert_position = buffer.anchor_before(buffer.len());
1929 buffer.edit([(insert_position..insert_position, text)], None, cx);
1930 });
1931 })?;
1932 }
1933 Err(e) => {
1934 Self::show_commit_message_error(&this, &e, cx);
1935 break;
1936 }
1937 }
1938 }
1939 }
1940 Err(e) => {
1941 Self::show_commit_message_error(&this, &e, cx);
1942 }
1943 }
1944
1945 anyhow::Ok(())
1946 }
1947 .log_err().await
1948 }));
1949 }
1950
1951 fn get_fetch_options(
1952 &self,
1953 window: &mut Window,
1954 cx: &mut Context<Self>,
1955 ) -> Task<Option<FetchOptions>> {
1956 let repo = self.active_repository.clone();
1957 let workspace = self.workspace.clone();
1958
1959 cx.spawn_in(window, async move |_, cx| {
1960 let repo = repo?;
1961 let remotes = repo
1962 .update(cx, |repo, _| repo.get_remotes(None))
1963 .ok()?
1964 .await
1965 .ok()?
1966 .log_err()?;
1967
1968 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
1969 if remotes.len() > 1 {
1970 remotes.push(FetchOptions::All);
1971 }
1972 let selection = cx
1973 .update(|window, cx| {
1974 picker_prompt::prompt(
1975 "Pick which remote to fetch",
1976 remotes.iter().map(|r| r.name()).collect(),
1977 workspace,
1978 window,
1979 cx,
1980 )
1981 })
1982 .ok()?
1983 .await?;
1984 remotes.get(selection).cloned()
1985 })
1986 }
1987
1988 pub(crate) fn fetch(
1989 &mut self,
1990 is_fetch_all: bool,
1991 window: &mut Window,
1992 cx: &mut Context<Self>,
1993 ) {
1994 if !self.can_push_and_pull(cx) {
1995 return;
1996 }
1997
1998 let Some(repo) = self.active_repository.clone() else {
1999 return;
2000 };
2001 telemetry::event!("Git Fetched");
2002 let askpass = self.askpass_delegate("git fetch", window, cx);
2003 let this = cx.weak_entity();
2004
2005 let fetch_options = if is_fetch_all {
2006 Task::ready(Some(FetchOptions::All))
2007 } else {
2008 self.get_fetch_options(window, cx)
2009 };
2010
2011 window
2012 .spawn(cx, async move |cx| {
2013 let Some(fetch_options) = fetch_options.await else {
2014 return Ok(());
2015 };
2016 let fetch = repo.update(cx, |repo, cx| {
2017 repo.fetch(fetch_options.clone(), askpass, cx)
2018 })?;
2019
2020 let remote_message = fetch.await?;
2021 this.update(cx, |this, cx| {
2022 let action = match fetch_options {
2023 FetchOptions::All => RemoteAction::Fetch(None),
2024 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2025 };
2026 match remote_message {
2027 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2028 Err(e) => {
2029 log::error!("Error while fetching {:?}", e);
2030 this.show_error_toast(action.name(), e, cx)
2031 }
2032 }
2033
2034 anyhow::Ok(())
2035 })
2036 .ok();
2037 anyhow::Ok(())
2038 })
2039 .detach_and_log_err(cx);
2040 }
2041
2042 pub(crate) fn git_clone(&mut self, repo: String, window: &mut Window, cx: &mut Context<Self>) {
2043 let path = cx.prompt_for_paths(gpui::PathPromptOptions {
2044 files: false,
2045 directories: true,
2046 multiple: false,
2047 prompt: Some("Select as Repository Destination".into()),
2048 });
2049
2050 let workspace = self.workspace.clone();
2051
2052 cx.spawn_in(window, async move |this, cx| {
2053 let mut paths = path.await.ok()?.ok()??;
2054 let mut path = paths.pop()?;
2055 let repo_name = repo.split("/").last()?.strip_suffix(".git")?.to_owned();
2056
2057 let fs = this.read_with(cx, |this, _| this.fs.clone()).ok()?;
2058
2059 let prompt_answer = match fs.git_clone(&repo, path.as_path()).await {
2060 Ok(_) => cx.update(|window, cx| {
2061 window.prompt(
2062 PromptLevel::Info,
2063 &format!("Git Clone: {}", repo_name),
2064 None,
2065 &["Add repo to project", "Open repo in new project"],
2066 cx,
2067 )
2068 }),
2069 Err(e) => {
2070 this.update(cx, |this: &mut GitPanel, cx| {
2071 let toast = StatusToast::new(e.to_string(), cx, |this, _| {
2072 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2073 .dismiss_button(true)
2074 });
2075
2076 this.workspace
2077 .update(cx, |workspace, cx| {
2078 workspace.toggle_status_toast(toast, cx);
2079 })
2080 .ok();
2081 })
2082 .ok()?;
2083
2084 return None;
2085 }
2086 }
2087 .ok()?;
2088
2089 path.push(repo_name);
2090 match prompt_answer.await.ok()? {
2091 0 => {
2092 workspace
2093 .update(cx, |workspace, cx| {
2094 workspace
2095 .project()
2096 .update(cx, |project, cx| {
2097 project.create_worktree(path.as_path(), true, cx)
2098 })
2099 .detach();
2100 })
2101 .ok();
2102 }
2103 1 => {
2104 workspace
2105 .update(cx, move |workspace, cx| {
2106 workspace::open_new(
2107 Default::default(),
2108 workspace.app_state().clone(),
2109 cx,
2110 move |workspace, _, cx| {
2111 cx.activate(true);
2112 workspace
2113 .project()
2114 .update(cx, |project, cx| {
2115 project.create_worktree(&path, true, cx)
2116 })
2117 .detach();
2118 },
2119 )
2120 .detach();
2121 })
2122 .ok();
2123 }
2124 _ => {}
2125 }
2126
2127 Some(())
2128 })
2129 .detach();
2130 }
2131
2132 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2133 let worktrees = self
2134 .project
2135 .read(cx)
2136 .visible_worktrees(cx)
2137 .collect::<Vec<_>>();
2138
2139 let worktree = if worktrees.len() == 1 {
2140 Task::ready(Some(worktrees.first().unwrap().clone()))
2141 } else if worktrees.is_empty() {
2142 let result = window.prompt(
2143 PromptLevel::Warning,
2144 "Unable to initialize a git repository",
2145 Some("Open a directory first"),
2146 &["Ok"],
2147 cx,
2148 );
2149 cx.background_executor()
2150 .spawn(async move {
2151 result.await.ok();
2152 })
2153 .detach();
2154 return;
2155 } else {
2156 let worktree_directories = worktrees
2157 .iter()
2158 .map(|worktree| worktree.read(cx).abs_path())
2159 .map(|worktree_abs_path| {
2160 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2161 Path::new("~")
2162 .join(path)
2163 .to_string_lossy()
2164 .to_string()
2165 .into()
2166 } else {
2167 worktree_abs_path.to_string_lossy().into_owned().into()
2168 }
2169 })
2170 .collect_vec();
2171 let prompt = picker_prompt::prompt(
2172 "Where would you like to initialize this git repository?",
2173 worktree_directories,
2174 self.workspace.clone(),
2175 window,
2176 cx,
2177 );
2178
2179 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2180 };
2181
2182 cx.spawn_in(window, async move |this, cx| {
2183 let worktree = match worktree.await {
2184 Some(worktree) => worktree,
2185 None => {
2186 return;
2187 }
2188 };
2189
2190 let Ok(result) = this.update(cx, |this, cx| {
2191 let fallback_branch_name = GitPanelSettings::get_global(cx)
2192 .fallback_branch_name
2193 .clone();
2194 this.project.read(cx).git_init(
2195 worktree.read(cx).abs_path(),
2196 fallback_branch_name,
2197 cx,
2198 )
2199 }) else {
2200 return;
2201 };
2202
2203 let result = result.await;
2204
2205 this.update_in(cx, |this, _, cx| match result {
2206 Ok(()) => {}
2207 Err(e) => this.show_error_toast("init", e, cx),
2208 })
2209 .ok();
2210 })
2211 .detach();
2212 }
2213
2214 pub(crate) fn pull(&mut self, rebase: bool, window: &mut Window, cx: &mut Context<Self>) {
2215 if !self.can_push_and_pull(cx) {
2216 return;
2217 }
2218 let Some(repo) = self.active_repository.clone() else {
2219 return;
2220 };
2221 let Some(branch) = repo.read(cx).branch.as_ref() else {
2222 return;
2223 };
2224 telemetry::event!("Git Pulled");
2225 let branch = branch.clone();
2226 let remote = self.get_remote(false, window, cx);
2227 cx.spawn_in(window, async move |this, cx| {
2228 let remote = match remote.await {
2229 Ok(Some(remote)) => remote,
2230 Ok(None) => {
2231 return Ok(());
2232 }
2233 Err(e) => {
2234 log::error!("Failed to get current remote: {}", e);
2235 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2236 .ok();
2237 return Ok(());
2238 }
2239 };
2240
2241 let askpass = this.update_in(cx, |this, window, cx| {
2242 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2243 })?;
2244
2245 let pull = repo.update(cx, |repo, cx| {
2246 repo.pull(
2247 branch.name().to_owned().into(),
2248 remote.name.clone(),
2249 rebase,
2250 askpass,
2251 cx,
2252 )
2253 })?;
2254
2255 let remote_message = pull.await?;
2256
2257 let action = RemoteAction::Pull(remote);
2258 this.update(cx, |this, cx| match remote_message {
2259 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2260 Err(e) => {
2261 log::error!("Error while pulling {:?}", e);
2262 this.show_error_toast(action.name(), e, cx)
2263 }
2264 })
2265 .ok();
2266
2267 anyhow::Ok(())
2268 })
2269 .detach_and_log_err(cx);
2270 }
2271
2272 pub(crate) fn push(
2273 &mut self,
2274 force_push: bool,
2275 select_remote: bool,
2276 window: &mut Window,
2277 cx: &mut Context<Self>,
2278 ) {
2279 if !self.can_push_and_pull(cx) {
2280 return;
2281 }
2282 let Some(repo) = self.active_repository.clone() else {
2283 return;
2284 };
2285 let Some(branch) = repo.read(cx).branch.as_ref() else {
2286 return;
2287 };
2288 telemetry::event!("Git Pushed");
2289 let branch = branch.clone();
2290
2291 let options = if force_push {
2292 Some(PushOptions::Force)
2293 } else {
2294 match branch.upstream {
2295 Some(Upstream {
2296 tracking: UpstreamTracking::Gone,
2297 ..
2298 })
2299 | None => Some(PushOptions::SetUpstream),
2300 _ => None,
2301 }
2302 };
2303 let remote = self.get_remote(select_remote, window, cx);
2304
2305 cx.spawn_in(window, async move |this, cx| {
2306 let remote = match remote.await {
2307 Ok(Some(remote)) => remote,
2308 Ok(None) => {
2309 return Ok(());
2310 }
2311 Err(e) => {
2312 log::error!("Failed to get current remote: {}", e);
2313 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2314 .ok();
2315 return Ok(());
2316 }
2317 };
2318
2319 let askpass_delegate = this.update_in(cx, |this, window, cx| {
2320 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2321 })?;
2322
2323 let push = repo.update(cx, |repo, cx| {
2324 repo.push(
2325 branch.name().to_owned().into(),
2326 remote.name.clone(),
2327 options,
2328 askpass_delegate,
2329 cx,
2330 )
2331 })?;
2332
2333 let remote_output = push.await?;
2334
2335 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2336 this.update(cx, |this, cx| match remote_output {
2337 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2338 Err(e) => {
2339 log::error!("Error while pushing {:?}", e);
2340 this.show_error_toast(action.name(), e, cx)
2341 }
2342 })?;
2343
2344 anyhow::Ok(())
2345 })
2346 .detach_and_log_err(cx);
2347 }
2348
2349 fn askpass_delegate(
2350 &self,
2351 operation: impl Into<SharedString>,
2352 window: &mut Window,
2353 cx: &mut Context<Self>,
2354 ) -> AskPassDelegate {
2355 let this = cx.weak_entity();
2356 let operation = operation.into();
2357 let window = window.window_handle();
2358 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2359 window
2360 .update(cx, |_, window, cx| {
2361 this.update(cx, |this, cx| {
2362 this.workspace.update(cx, |workspace, cx| {
2363 workspace.toggle_modal(window, cx, |window, cx| {
2364 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2365 });
2366 })
2367 })
2368 })
2369 .ok();
2370 })
2371 }
2372
2373 fn can_push_and_pull(&self, cx: &App) -> bool {
2374 !self.project.read(cx).is_via_collab()
2375 }
2376
2377 fn get_remote(
2378 &mut self,
2379 always_select: bool,
2380 window: &mut Window,
2381 cx: &mut Context<Self>,
2382 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2383 let repo = self.active_repository.clone();
2384 let workspace = self.workspace.clone();
2385 let mut cx = window.to_async(cx);
2386
2387 async move {
2388 let repo = repo.context("No active repository")?;
2389 let current_remotes: Vec<Remote> = repo
2390 .update(&mut cx, |repo, _| {
2391 let current_branch = if always_select {
2392 None
2393 } else {
2394 let current_branch = repo.branch.as_ref().context("No active branch")?;
2395 Some(current_branch.name().to_string())
2396 };
2397 anyhow::Ok(repo.get_remotes(current_branch))
2398 })??
2399 .await??;
2400
2401 let current_remotes: Vec<_> = current_remotes
2402 .into_iter()
2403 .map(|remotes| remotes.name)
2404 .collect();
2405 let selection = cx
2406 .update(|window, cx| {
2407 picker_prompt::prompt(
2408 "Pick which remote to push to",
2409 current_remotes.clone(),
2410 workspace,
2411 window,
2412 cx,
2413 )
2414 })?
2415 .await;
2416
2417 Ok(selection.map(|selection| Remote {
2418 name: current_remotes[selection].clone(),
2419 }))
2420 }
2421 }
2422
2423 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2424 if self.local_committer_task.is_none() {
2425 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2426 let committer = get_git_committer(cx).await;
2427 this.update(cx, |this, cx| {
2428 this.local_committer = Some(committer);
2429 cx.notify()
2430 })
2431 .ok();
2432 }));
2433 }
2434 }
2435
2436 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2437 let mut new_co_authors = Vec::new();
2438 let project = self.project.read(cx);
2439
2440 let Some(room) = self
2441 .workspace
2442 .upgrade()
2443 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2444 else {
2445 return Vec::default();
2446 };
2447
2448 let room = room.read(cx);
2449
2450 for (peer_id, collaborator) in project.collaborators() {
2451 if collaborator.is_host {
2452 continue;
2453 }
2454
2455 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2456 continue;
2457 };
2458 if !participant.can_write() {
2459 continue;
2460 }
2461 if let Some(email) = &collaborator.committer_email {
2462 let name = collaborator
2463 .committer_name
2464 .clone()
2465 .or_else(|| participant.user.name.clone())
2466 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2467 new_co_authors.push((name.clone(), email.clone()))
2468 }
2469 }
2470 if !project.is_local()
2471 && !project.is_read_only(cx)
2472 && let Some(local_committer) = self.local_committer(room, cx)
2473 {
2474 new_co_authors.push(local_committer);
2475 }
2476 new_co_authors
2477 }
2478
2479 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2480 let user = room.local_participant_user(cx)?;
2481 let committer = self.local_committer.as_ref()?;
2482 let email = committer.email.clone()?;
2483 let name = committer
2484 .name
2485 .clone()
2486 .or_else(|| user.name.clone())
2487 .unwrap_or_else(|| user.github_login.clone().to_string());
2488 Some((name, email))
2489 }
2490
2491 fn toggle_fill_co_authors(
2492 &mut self,
2493 _: &ToggleFillCoAuthors,
2494 _: &mut Window,
2495 cx: &mut Context<Self>,
2496 ) {
2497 self.add_coauthors = !self.add_coauthors;
2498 cx.notify();
2499 }
2500
2501 fn toggle_sort_by_path(
2502 &mut self,
2503 _: &ToggleSortByPath,
2504 _: &mut Window,
2505 cx: &mut Context<Self>,
2506 ) {
2507 let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
2508 if let Some(workspace) = self.workspace.upgrade() {
2509 let workspace = workspace.read(cx);
2510 let fs = workspace.app_state().fs.clone();
2511 cx.update_global::<SettingsStore, _>(|store, _cx| {
2512 store.update_settings_file(fs, move |settings, _cx| {
2513 settings.git_panel.get_or_insert_default().sort_by_path =
2514 Some(!current_setting);
2515 });
2516 });
2517 }
2518 }
2519
2520 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2521 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2522
2523 let existing_text = message.to_ascii_lowercase();
2524 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2525 let mut ends_with_co_authors = false;
2526 let existing_co_authors = existing_text
2527 .lines()
2528 .filter_map(|line| {
2529 let line = line.trim();
2530 if line.starts_with(&lowercase_co_author_prefix) {
2531 ends_with_co_authors = true;
2532 Some(line)
2533 } else {
2534 ends_with_co_authors = false;
2535 None
2536 }
2537 })
2538 .collect::<HashSet<_>>();
2539
2540 let new_co_authors = self
2541 .potential_co_authors(cx)
2542 .into_iter()
2543 .filter(|(_, email)| {
2544 !existing_co_authors
2545 .iter()
2546 .any(|existing| existing.contains(email.as_str()))
2547 })
2548 .collect::<Vec<_>>();
2549
2550 if new_co_authors.is_empty() {
2551 return;
2552 }
2553
2554 if !ends_with_co_authors {
2555 message.push('\n');
2556 }
2557 for (name, email) in new_co_authors {
2558 message.push('\n');
2559 message.push_str(CO_AUTHOR_PREFIX);
2560 message.push_str(&name);
2561 message.push_str(" <");
2562 message.push_str(&email);
2563 message.push('>');
2564 }
2565 message.push('\n');
2566 }
2567
2568 fn schedule_update(
2569 &mut self,
2570 clear_pending: bool,
2571 window: &mut Window,
2572 cx: &mut Context<Self>,
2573 ) {
2574 let handle = cx.entity().downgrade();
2575 self.reopen_commit_buffer(window, cx);
2576 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2577 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2578 if let Some(git_panel) = handle.upgrade() {
2579 git_panel
2580 .update_in(cx, |git_panel, window, cx| {
2581 if clear_pending {
2582 git_panel.clear_pending();
2583 }
2584 git_panel.update_visible_entries(window, cx);
2585 })
2586 .ok();
2587 }
2588 });
2589 }
2590
2591 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2592 let Some(active_repo) = self.active_repository.as_ref() else {
2593 return;
2594 };
2595 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2596 let project = self.project.read(cx);
2597 active_repo.open_commit_buffer(
2598 Some(project.languages().clone()),
2599 project.buffer_store().clone(),
2600 cx,
2601 )
2602 });
2603
2604 cx.spawn_in(window, async move |git_panel, cx| {
2605 let buffer = load_buffer.await?;
2606 git_panel.update_in(cx, |git_panel, window, cx| {
2607 if git_panel
2608 .commit_editor
2609 .read(cx)
2610 .buffer()
2611 .read(cx)
2612 .as_singleton()
2613 .as_ref()
2614 != Some(&buffer)
2615 {
2616 git_panel.commit_editor = cx.new(|cx| {
2617 commit_message_editor(
2618 buffer,
2619 git_panel.suggest_commit_message(cx).map(SharedString::from),
2620 git_panel.project.clone(),
2621 true,
2622 window,
2623 cx,
2624 )
2625 });
2626 }
2627 })
2628 })
2629 .detach_and_log_err(cx);
2630 }
2631
2632 fn clear_pending(&mut self) {
2633 self.pending.retain(|v| !v.finished)
2634 }
2635
2636 fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2637 let path_style = self.project.read(cx).path_style(cx);
2638 let bulk_staging = self.bulk_staging.take();
2639 let last_staged_path_prev_index = bulk_staging
2640 .as_ref()
2641 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2642
2643 self.entries.clear();
2644 self.single_staged_entry.take();
2645 self.single_tracked_entry.take();
2646 self.conflicted_count = 0;
2647 self.conflicted_staged_count = 0;
2648 self.new_count = 0;
2649 self.tracked_count = 0;
2650 self.new_staged_count = 0;
2651 self.tracked_staged_count = 0;
2652 self.entry_count = 0;
2653
2654 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2655
2656 let mut changed_entries = Vec::new();
2657 let mut new_entries = Vec::new();
2658 let mut conflict_entries = Vec::new();
2659 let mut single_staged_entry = None;
2660 let mut staged_count = 0;
2661 let mut max_width_item: Option<(RepoPath, usize)> = None;
2662
2663 let Some(repo) = self.active_repository.as_ref() else {
2664 // Just clear entries if no repository is active.
2665 cx.notify();
2666 return;
2667 };
2668
2669 let repo = repo.read(cx);
2670
2671 self.stash_entries = repo.cached_stash();
2672
2673 for entry in repo.cached_status() {
2674 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2675 let is_new = entry.status.is_created();
2676 let staging = entry.status.staging();
2677
2678 if self.pending.iter().any(|pending| {
2679 pending.target_status == TargetStatus::Reverted
2680 && !pending.finished
2681 && pending
2682 .entries
2683 .iter()
2684 .any(|pending| pending.repo_path == entry.repo_path)
2685 }) {
2686 continue;
2687 }
2688
2689 let entry = GitStatusEntry {
2690 repo_path: entry.repo_path.clone(),
2691 status: entry.status,
2692 staging,
2693 };
2694
2695 if staging.has_staged() {
2696 staged_count += 1;
2697 single_staged_entry = Some(entry.clone());
2698 }
2699
2700 let width_estimate = Self::item_width_estimate(
2701 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
2702 entry.display_name(path_style).len(),
2703 );
2704
2705 match max_width_item.as_mut() {
2706 Some((repo_path, estimate)) => {
2707 if width_estimate > *estimate {
2708 *repo_path = entry.repo_path.clone();
2709 *estimate = width_estimate;
2710 }
2711 }
2712 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2713 }
2714
2715 if sort_by_path {
2716 changed_entries.push(entry);
2717 } else if is_conflict {
2718 conflict_entries.push(entry);
2719 } else if is_new {
2720 new_entries.push(entry);
2721 } else {
2722 changed_entries.push(entry);
2723 }
2724 }
2725
2726 let mut pending_staged_count = 0;
2727 let mut last_pending_staged = None;
2728 let mut pending_status_for_single_staged = None;
2729 for pending in self.pending.iter() {
2730 if pending.target_status == TargetStatus::Staged {
2731 pending_staged_count += pending.entries.len();
2732 last_pending_staged = pending.entries.first().cloned();
2733 }
2734 if let Some(single_staged) = &single_staged_entry
2735 && pending
2736 .entries
2737 .iter()
2738 .any(|entry| entry.repo_path == single_staged.repo_path)
2739 {
2740 pending_status_for_single_staged = Some(pending.target_status);
2741 }
2742 }
2743
2744 if conflict_entries.is_empty() && staged_count == 1 && pending_staged_count == 0 {
2745 match pending_status_for_single_staged {
2746 Some(TargetStatus::Staged) | None => {
2747 self.single_staged_entry = single_staged_entry;
2748 }
2749 _ => {}
2750 }
2751 } else if conflict_entries.is_empty() && pending_staged_count == 1 {
2752 self.single_staged_entry = last_pending_staged;
2753 }
2754
2755 if conflict_entries.is_empty() && changed_entries.len() == 1 {
2756 self.single_tracked_entry = changed_entries.first().cloned();
2757 }
2758
2759 if !conflict_entries.is_empty() {
2760 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2761 header: Section::Conflict,
2762 }));
2763 self.entries
2764 .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2765 }
2766
2767 if !changed_entries.is_empty() {
2768 if !sort_by_path {
2769 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2770 header: Section::Tracked,
2771 }));
2772 }
2773 self.entries
2774 .extend(changed_entries.into_iter().map(GitListEntry::Status));
2775 }
2776 if !new_entries.is_empty() {
2777 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2778 header: Section::New,
2779 }));
2780 self.entries
2781 .extend(new_entries.into_iter().map(GitListEntry::Status));
2782 }
2783
2784 if let Some((repo_path, _)) = max_width_item {
2785 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2786 GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2787 GitListEntry::Header(_) => false,
2788 });
2789 }
2790
2791 self.update_counts(repo);
2792
2793 let bulk_staging_anchor_new_index = bulk_staging
2794 .as_ref()
2795 .filter(|op| op.repo_id == repo.id)
2796 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2797 if bulk_staging_anchor_new_index == last_staged_path_prev_index
2798 && let Some(index) = bulk_staging_anchor_new_index
2799 && let Some(entry) = self.entries.get(index)
2800 && let Some(entry) = entry.status_entry()
2801 && self.entry_staging(entry) == StageStatus::Staged
2802 {
2803 self.bulk_staging = bulk_staging;
2804 }
2805
2806 self.select_first_entry_if_none(cx);
2807
2808 let suggested_commit_message = self.suggest_commit_message(cx);
2809 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2810
2811 self.commit_editor.update(cx, |editor, cx| {
2812 editor.set_placeholder_text(&placeholder_text, window, cx)
2813 });
2814
2815 cx.notify();
2816 }
2817
2818 fn header_state(&self, header_type: Section) -> ToggleState {
2819 let (staged_count, count) = match header_type {
2820 Section::New => (self.new_staged_count, self.new_count),
2821 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2822 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2823 };
2824 if staged_count == 0 {
2825 ToggleState::Unselected
2826 } else if count == staged_count {
2827 ToggleState::Selected
2828 } else {
2829 ToggleState::Indeterminate
2830 }
2831 }
2832
2833 fn update_counts(&mut self, repo: &Repository) {
2834 self.show_placeholders = false;
2835 self.conflicted_count = 0;
2836 self.conflicted_staged_count = 0;
2837 self.new_count = 0;
2838 self.tracked_count = 0;
2839 self.new_staged_count = 0;
2840 self.tracked_staged_count = 0;
2841 self.entry_count = 0;
2842 for entry in &self.entries {
2843 let Some(status_entry) = entry.status_entry() else {
2844 continue;
2845 };
2846 self.entry_count += 1;
2847 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2848 self.conflicted_count += 1;
2849 if self.entry_staging(status_entry).has_staged() {
2850 self.conflicted_staged_count += 1;
2851 }
2852 } else if status_entry.status.is_created() {
2853 self.new_count += 1;
2854 if self.entry_staging(status_entry).has_staged() {
2855 self.new_staged_count += 1;
2856 }
2857 } else {
2858 self.tracked_count += 1;
2859 if self.entry_staging(status_entry).has_staged() {
2860 self.tracked_staged_count += 1;
2861 }
2862 }
2863 }
2864 }
2865
2866 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2867 for pending in self.pending.iter().rev() {
2868 if pending
2869 .entries
2870 .iter()
2871 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2872 {
2873 match pending.target_status {
2874 TargetStatus::Staged => return StageStatus::Staged,
2875 TargetStatus::Unstaged => return StageStatus::Unstaged,
2876 TargetStatus::Reverted => continue,
2877 TargetStatus::Unchanged => continue,
2878 }
2879 }
2880 }
2881 entry.staging
2882 }
2883
2884 pub(crate) fn has_staged_changes(&self) -> bool {
2885 self.tracked_staged_count > 0
2886 || self.new_staged_count > 0
2887 || self.conflicted_staged_count > 0
2888 }
2889
2890 pub(crate) fn has_unstaged_changes(&self) -> bool {
2891 self.tracked_count > self.tracked_staged_count
2892 || self.new_count > self.new_staged_count
2893 || self.conflicted_count > self.conflicted_staged_count
2894 }
2895
2896 fn has_tracked_changes(&self) -> bool {
2897 self.tracked_count > 0
2898 }
2899
2900 pub fn has_unstaged_conflicts(&self) -> bool {
2901 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2902 }
2903
2904 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2905 let action = action.into();
2906 let Some(workspace) = self.workspace.upgrade() else {
2907 return;
2908 };
2909
2910 let message = e.to_string().trim().to_string();
2911 if message
2912 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2913 .next()
2914 .is_some()
2915 { // Hide the cancelled by user message
2916 } else {
2917 workspace.update(cx, |workspace, cx| {
2918 let workspace_weak = cx.weak_entity();
2919 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2920 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2921 .action("View Log", move |window, cx| {
2922 let message = message.clone();
2923 let action = action.clone();
2924 workspace_weak
2925 .update(cx, move |workspace, cx| {
2926 Self::open_output(action, workspace, &message, window, cx)
2927 })
2928 .ok();
2929 })
2930 });
2931 workspace.toggle_status_toast(toast, cx)
2932 });
2933 }
2934 }
2935
2936 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2937 where
2938 E: std::fmt::Debug + std::fmt::Display,
2939 {
2940 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2941 let _ = workspace.update(cx, |workspace, cx| {
2942 struct CommitMessageError;
2943 let notification_id = NotificationId::unique::<CommitMessageError>();
2944 workspace.show_notification(notification_id, cx, |cx| {
2945 cx.new(|cx| {
2946 ErrorMessagePrompt::new(
2947 format!("Failed to generate commit message: {err}"),
2948 cx,
2949 )
2950 })
2951 });
2952 });
2953 }
2954 }
2955
2956 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2957 let Some(workspace) = self.workspace.upgrade() else {
2958 return;
2959 };
2960
2961 workspace.update(cx, |workspace, cx| {
2962 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2963 let workspace_weak = cx.weak_entity();
2964 let operation = action.name();
2965
2966 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2967 use remote_output::SuccessStyle::*;
2968 match style {
2969 Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
2970 ToastWithLog { output } => this
2971 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2972 .action("View Log", move |window, cx| {
2973 let output = output.clone();
2974 let output =
2975 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2976 workspace_weak
2977 .update(cx, move |workspace, cx| {
2978 Self::open_output(operation, workspace, &output, window, cx)
2979 })
2980 .ok();
2981 }),
2982 PushPrLink { text, link } => this
2983 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
2984 .action(text, move |_, cx| cx.open_url(&link)),
2985 }
2986 });
2987 workspace.toggle_status_toast(status_toast, cx)
2988 });
2989 }
2990
2991 fn open_output(
2992 operation: impl Into<SharedString>,
2993 workspace: &mut Workspace,
2994 output: &str,
2995 window: &mut Window,
2996 cx: &mut Context<Workspace>,
2997 ) {
2998 let operation = operation.into();
2999 let buffer = cx.new(|cx| Buffer::local(output, cx));
3000 buffer.update(cx, |buffer, cx| {
3001 buffer.set_capability(language::Capability::ReadOnly, cx);
3002 });
3003 let editor = cx.new(|cx| {
3004 let mut editor = Editor::for_buffer(buffer, None, window, cx);
3005 editor.buffer().update(cx, |buffer, cx| {
3006 buffer.set_title(format!("Output from git {operation}"), cx);
3007 });
3008 editor.set_read_only(true);
3009 editor
3010 });
3011
3012 workspace.add_item_to_center(Box::new(editor), window, cx);
3013 }
3014
3015 pub fn can_commit(&self) -> bool {
3016 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3017 }
3018
3019 pub fn can_stage_all(&self) -> bool {
3020 self.has_unstaged_changes()
3021 }
3022
3023 pub fn can_unstage_all(&self) -> bool {
3024 self.has_staged_changes()
3025 }
3026
3027 // eventually we'll need to take depth into account here
3028 // if we add a tree view
3029 fn item_width_estimate(path: usize, file_name: usize) -> usize {
3030 path + file_name
3031 }
3032
3033 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3034 let focus_handle = self.focus_handle.clone();
3035 let has_tracked_changes = self.has_tracked_changes();
3036 let has_staged_changes = self.has_staged_changes();
3037 let has_unstaged_changes = self.has_unstaged_changes();
3038 let has_new_changes = self.new_count > 0;
3039 let has_stash_items = self.stash_entries.entries.len() > 0;
3040
3041 PopoverMenu::new(id.into())
3042 .trigger(
3043 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3044 .icon_size(IconSize::Small)
3045 .icon_color(Color::Muted),
3046 )
3047 .menu(move |window, cx| {
3048 Some(git_panel_context_menu(
3049 focus_handle.clone(),
3050 GitMenuState {
3051 has_tracked_changes,
3052 has_staged_changes,
3053 has_unstaged_changes,
3054 has_new_changes,
3055 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3056 has_stash_items,
3057 },
3058 window,
3059 cx,
3060 ))
3061 })
3062 .anchor(Corner::TopRight)
3063 }
3064
3065 pub(crate) fn render_generate_commit_message_button(
3066 &self,
3067 cx: &Context<Self>,
3068 ) -> Option<AnyElement> {
3069 if !agent_settings::AgentSettings::get_global(cx).enabled(cx)
3070 || LanguageModelRegistry::read_global(cx)
3071 .commit_message_model()
3072 .is_none()
3073 {
3074 return None;
3075 }
3076
3077 if self.generate_commit_message_task.is_some() {
3078 return Some(
3079 h_flex()
3080 .gap_1()
3081 .child(
3082 Icon::new(IconName::ArrowCircle)
3083 .size(IconSize::XSmall)
3084 .color(Color::Info)
3085 .with_rotate_animation(2),
3086 )
3087 .child(
3088 Label::new("Generating Commit...")
3089 .size(LabelSize::Small)
3090 .color(Color::Muted),
3091 )
3092 .into_any_element(),
3093 );
3094 }
3095
3096 let can_commit = self.can_commit();
3097 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3098 Some(
3099 IconButton::new("generate-commit-message", IconName::AiEdit)
3100 .shape(ui::IconButtonShape::Square)
3101 .icon_color(Color::Muted)
3102 .tooltip(move |_window, cx| {
3103 if can_commit {
3104 Tooltip::for_action_in(
3105 "Generate Commit Message",
3106 &git::GenerateCommitMessage,
3107 &editor_focus_handle,
3108 cx,
3109 )
3110 } else {
3111 Tooltip::simple("No changes to commit", cx)
3112 }
3113 })
3114 .disabled(!can_commit)
3115 .on_click(cx.listener(move |this, _event, _window, cx| {
3116 this.generate_commit_message(cx);
3117 }))
3118 .into_any_element(),
3119 )
3120 }
3121
3122 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3123 let potential_co_authors = self.potential_co_authors(cx);
3124
3125 let (tooltip_label, icon) = if self.add_coauthors {
3126 ("Remove co-authored-by", IconName::Person)
3127 } else {
3128 ("Add co-authored-by", IconName::UserCheck)
3129 };
3130
3131 if potential_co_authors.is_empty() {
3132 None
3133 } else {
3134 Some(
3135 IconButton::new("co-authors", icon)
3136 .shape(ui::IconButtonShape::Square)
3137 .icon_color(Color::Disabled)
3138 .selected_icon_color(Color::Selected)
3139 .toggle_state(self.add_coauthors)
3140 .tooltip(move |_, cx| {
3141 let title = format!(
3142 "{}:{}{}",
3143 tooltip_label,
3144 if potential_co_authors.len() == 1 {
3145 ""
3146 } else {
3147 "\n"
3148 },
3149 potential_co_authors
3150 .iter()
3151 .map(|(name, email)| format!(" {} <{}>", name, email))
3152 .join("\n")
3153 );
3154 Tooltip::simple(title, cx)
3155 })
3156 .on_click(cx.listener(|this, _, _, cx| {
3157 this.add_coauthors = !this.add_coauthors;
3158 cx.notify();
3159 }))
3160 .into_any_element(),
3161 )
3162 }
3163 }
3164
3165 fn render_git_commit_menu(
3166 &self,
3167 id: impl Into<ElementId>,
3168 keybinding_target: Option<FocusHandle>,
3169 cx: &mut Context<Self>,
3170 ) -> impl IntoElement {
3171 PopoverMenu::new(id.into())
3172 .trigger(
3173 ui::ButtonLike::new_rounded_right("commit-split-button-right")
3174 .layer(ui::ElevationIndex::ModalSurface)
3175 .size(ButtonSize::None)
3176 .child(
3177 h_flex()
3178 .px_1()
3179 .h_full()
3180 .justify_center()
3181 .border_l_1()
3182 .border_color(cx.theme().colors().border)
3183 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3184 ),
3185 )
3186 .menu({
3187 let git_panel = cx.entity();
3188 let has_previous_commit = self.head_commit(cx).is_some();
3189 let amend = self.amend_pending();
3190 let signoff = self.signoff_enabled;
3191
3192 move |window, cx| {
3193 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3194 context_menu
3195 .when_some(keybinding_target.clone(), |el, keybinding_target| {
3196 el.context(keybinding_target)
3197 })
3198 .when(has_previous_commit, |this| {
3199 this.toggleable_entry(
3200 "Amend",
3201 amend,
3202 IconPosition::Start,
3203 Some(Box::new(Amend)),
3204 {
3205 let git_panel = git_panel.downgrade();
3206 move |_, cx| {
3207 git_panel
3208 .update(cx, |git_panel, cx| {
3209 git_panel.toggle_amend_pending(cx);
3210 })
3211 .ok();
3212 }
3213 },
3214 )
3215 })
3216 .toggleable_entry(
3217 "Signoff",
3218 signoff,
3219 IconPosition::Start,
3220 Some(Box::new(Signoff)),
3221 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3222 )
3223 }))
3224 }
3225 })
3226 .anchor(Corner::TopRight)
3227 }
3228
3229 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3230 if self.has_unstaged_conflicts() {
3231 (false, "You must resolve conflicts before committing")
3232 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3233 (false, "No changes to commit")
3234 } else if self.pending_commit.is_some() {
3235 (false, "Commit in progress")
3236 } else if !self.has_commit_message(cx) {
3237 (false, "No commit message")
3238 } else if !self.has_write_access(cx) {
3239 (false, "You do not have write access to this project")
3240 } else {
3241 (true, self.commit_button_title())
3242 }
3243 }
3244
3245 pub fn commit_button_title(&self) -> &'static str {
3246 if self.amend_pending {
3247 if self.has_staged_changes() {
3248 "Amend"
3249 } else if self.has_tracked_changes() {
3250 "Amend Tracked"
3251 } else {
3252 "Amend"
3253 }
3254 } else if self.has_staged_changes() {
3255 "Commit"
3256 } else {
3257 "Commit Tracked"
3258 }
3259 }
3260
3261 fn expand_commit_editor(
3262 &mut self,
3263 _: &git::ExpandCommitEditor,
3264 window: &mut Window,
3265 cx: &mut Context<Self>,
3266 ) {
3267 let workspace = self.workspace.clone();
3268 window.defer(cx, move |window, cx| {
3269 workspace
3270 .update(cx, |workspace, cx| {
3271 CommitModal::toggle(workspace, None, window, cx)
3272 })
3273 .ok();
3274 })
3275 }
3276
3277 fn render_panel_header(
3278 &self,
3279 window: &mut Window,
3280 cx: &mut Context<Self>,
3281 ) -> Option<impl IntoElement> {
3282 self.active_repository.as_ref()?;
3283
3284 let text;
3285 let action;
3286 let tooltip;
3287 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3288 text = "Unstage All";
3289 action = git::UnstageAll.boxed_clone();
3290 tooltip = "git reset";
3291 } else {
3292 text = "Stage All";
3293 action = git::StageAll.boxed_clone();
3294 tooltip = "git add --all ."
3295 }
3296
3297 let change_string = match self.entry_count {
3298 0 => "No Changes".to_string(),
3299 1 => "1 Change".to_string(),
3300 _ => format!("{} Changes", self.entry_count),
3301 };
3302
3303 Some(
3304 self.panel_header_container(window, cx)
3305 .px_2()
3306 .justify_between()
3307 .child(
3308 panel_button(change_string)
3309 .color(Color::Muted)
3310 .tooltip(Tooltip::for_action_title_in(
3311 "Open Diff",
3312 &Diff,
3313 &self.focus_handle,
3314 ))
3315 .on_click(|_, _, cx| {
3316 cx.defer(|cx| {
3317 cx.dispatch_action(&Diff);
3318 })
3319 }),
3320 )
3321 .child(
3322 h_flex()
3323 .gap_1()
3324 .child(self.render_overflow_menu("overflow_menu"))
3325 .child(
3326 panel_filled_button(text)
3327 .tooltip(Tooltip::for_action_title_in(
3328 tooltip,
3329 action.as_ref(),
3330 &self.focus_handle,
3331 ))
3332 .disabled(self.entry_count == 0)
3333 .on_click(move |_, _, cx| {
3334 let action = action.boxed_clone();
3335 cx.defer(move |cx| {
3336 cx.dispatch_action(action.as_ref());
3337 })
3338 }),
3339 ),
3340 ),
3341 )
3342 }
3343
3344 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3345 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3346 if !self.can_push_and_pull(cx) {
3347 return None;
3348 }
3349 Some(
3350 h_flex()
3351 .gap_1()
3352 .flex_shrink_0()
3353 .when_some(branch, |this, branch| {
3354 let focus_handle = Some(self.focus_handle(cx));
3355
3356 this.children(render_remote_button(
3357 "remote-button",
3358 &branch,
3359 focus_handle,
3360 true,
3361 ))
3362 })
3363 .into_any_element(),
3364 )
3365 }
3366
3367 pub fn render_footer(
3368 &self,
3369 window: &mut Window,
3370 cx: &mut Context<Self>,
3371 ) -> Option<impl IntoElement> {
3372 let active_repository = self.active_repository.clone()?;
3373 let panel_editor_style = panel_editor_style(true, window, cx);
3374
3375 let enable_coauthors = self.render_co_authors(cx);
3376
3377 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3378 let expand_tooltip_focus_handle = editor_focus_handle;
3379
3380 let branch = active_repository.read(cx).branch.clone();
3381 let head_commit = active_repository.read(cx).head_commit.clone();
3382
3383 let footer_size = px(32.);
3384 let gap = px(9.0);
3385 let max_height = panel_editor_style
3386 .text
3387 .line_height_in_pixels(window.rem_size())
3388 * MAX_PANEL_EDITOR_LINES
3389 + gap;
3390
3391 let git_panel = cx.entity();
3392 let display_name = SharedString::from(Arc::from(
3393 active_repository
3394 .read(cx)
3395 .display_name()
3396 .trim_end_matches("/"),
3397 ));
3398 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3399 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3400 });
3401
3402 let footer = v_flex()
3403 .child(PanelRepoFooter::new(
3404 display_name,
3405 branch,
3406 head_commit,
3407 Some(git_panel),
3408 ))
3409 .child(
3410 panel_editor_container(window, cx)
3411 .id("commit-editor-container")
3412 .relative()
3413 .w_full()
3414 .h(max_height + footer_size)
3415 .border_t_1()
3416 .border_color(cx.theme().colors().border)
3417 .cursor_text()
3418 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3419 window.focus(&this.commit_editor.focus_handle(cx));
3420 }))
3421 .child(
3422 h_flex()
3423 .id("commit-footer")
3424 .border_t_1()
3425 .when(editor_is_long, |el| {
3426 el.border_color(cx.theme().colors().border_variant)
3427 })
3428 .absolute()
3429 .bottom_0()
3430 .left_0()
3431 .w_full()
3432 .px_2()
3433 .h(footer_size)
3434 .flex_none()
3435 .justify_between()
3436 .child(
3437 self.render_generate_commit_message_button(cx)
3438 .unwrap_or_else(|| div().into_any_element()),
3439 )
3440 .child(
3441 h_flex()
3442 .gap_0p5()
3443 .children(enable_coauthors)
3444 .child(self.render_commit_button(cx)),
3445 ),
3446 )
3447 .child(
3448 div()
3449 .pr_2p5()
3450 .on_action(|&editor::actions::MoveUp, _, cx| {
3451 cx.stop_propagation();
3452 })
3453 .on_action(|&editor::actions::MoveDown, _, cx| {
3454 cx.stop_propagation();
3455 })
3456 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3457 )
3458 .child(
3459 h_flex()
3460 .absolute()
3461 .top_2()
3462 .right_2()
3463 .opacity(0.5)
3464 .hover(|this| this.opacity(1.0))
3465 .child(
3466 panel_icon_button("expand-commit-editor", IconName::Maximize)
3467 .icon_size(IconSize::Small)
3468 .size(ui::ButtonSize::Default)
3469 .tooltip(move |_window, cx| {
3470 Tooltip::for_action_in(
3471 "Open Commit Modal",
3472 &git::ExpandCommitEditor,
3473 &expand_tooltip_focus_handle,
3474 cx,
3475 )
3476 })
3477 .on_click(cx.listener({
3478 move |_, _, window, cx| {
3479 window.dispatch_action(
3480 git::ExpandCommitEditor.boxed_clone(),
3481 cx,
3482 )
3483 }
3484 })),
3485 ),
3486 ),
3487 );
3488
3489 Some(footer)
3490 }
3491
3492 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3493 let (can_commit, tooltip) = self.configure_commit_button(cx);
3494 let title = self.commit_button_title();
3495 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3496 let amend = self.amend_pending();
3497 let signoff = self.signoff_enabled;
3498
3499 div()
3500 .id("commit-wrapper")
3501 .on_hover(cx.listener(move |this, hovered, _, cx| {
3502 this.show_placeholders =
3503 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3504 cx.notify()
3505 }))
3506 .child(SplitButton::new(
3507 ui::ButtonLike::new_rounded_left(ElementId::Name(
3508 format!("split-button-left-{}", title).into(),
3509 ))
3510 .layer(ui::ElevationIndex::ModalSurface)
3511 .size(ui::ButtonSize::Compact)
3512 .child(
3513 div()
3514 .child(Label::new(title).size(LabelSize::Small))
3515 .mr_0p5(),
3516 )
3517 .on_click({
3518 let git_panel = cx.weak_entity();
3519 move |_, window, cx| {
3520 telemetry::event!("Git Committed", source = "Git Panel");
3521 git_panel
3522 .update(cx, |git_panel, cx| {
3523 git_panel.commit_changes(
3524 CommitOptions { amend, signoff },
3525 window,
3526 cx,
3527 );
3528 })
3529 .ok();
3530 }
3531 })
3532 .disabled(!can_commit || self.modal_open)
3533 .tooltip({
3534 let handle = commit_tooltip_focus_handle.clone();
3535 move |_window, cx| {
3536 if can_commit {
3537 Tooltip::with_meta_in(
3538 tooltip,
3539 Some(if amend { &git::Amend } else { &git::Commit }),
3540 format!(
3541 "git commit{}{}",
3542 if amend { " --amend" } else { "" },
3543 if signoff { " --signoff" } else { "" }
3544 ),
3545 &handle.clone(),
3546 cx,
3547 )
3548 } else {
3549 Tooltip::simple(tooltip, cx)
3550 }
3551 }
3552 }),
3553 self.render_git_commit_menu(
3554 ElementId::Name(format!("split-button-right-{}", title).into()),
3555 Some(commit_tooltip_focus_handle),
3556 cx,
3557 )
3558 .into_any_element(),
3559 ))
3560 }
3561
3562 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3563 h_flex()
3564 .py_1p5()
3565 .px_2()
3566 .gap_1p5()
3567 .justify_between()
3568 .border_t_1()
3569 .border_color(cx.theme().colors().border.opacity(0.8))
3570 .child(
3571 div()
3572 .flex_grow()
3573 .overflow_hidden()
3574 .max_w(relative(0.85))
3575 .child(
3576 Label::new("This will update your most recent commit.")
3577 .size(LabelSize::Small)
3578 .truncate(),
3579 ),
3580 )
3581 .child(
3582 panel_button("Cancel")
3583 .size(ButtonSize::Default)
3584 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3585 )
3586 }
3587
3588 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3589 let active_repository = self.active_repository.as_ref()?;
3590 let branch = active_repository.read(cx).branch.as_ref()?;
3591 let commit = branch.most_recent_commit.as_ref()?.clone();
3592 let workspace = self.workspace.clone();
3593 let this = cx.entity();
3594
3595 Some(
3596 h_flex()
3597 .py_1p5()
3598 .px_2()
3599 .gap_1p5()
3600 .justify_between()
3601 .border_t_1()
3602 .border_color(cx.theme().colors().border.opacity(0.8))
3603 .child(
3604 div()
3605 .flex_grow()
3606 .overflow_hidden()
3607 .line_clamp(1)
3608 .child(
3609 Label::new(commit.subject.clone())
3610 .size(LabelSize::Small)
3611 .truncate(),
3612 )
3613 .id("commit-msg-hover")
3614 .on_click({
3615 let commit = commit.clone();
3616 let repo = active_repository.downgrade();
3617 move |_, window, cx| {
3618 CommitView::open(
3619 commit.sha.to_string(),
3620 repo.clone(),
3621 workspace.clone(),
3622 None,
3623 window,
3624 cx,
3625 );
3626 }
3627 })
3628 .hoverable_tooltip({
3629 let repo = active_repository.clone();
3630 move |window, cx| {
3631 GitPanelMessageTooltip::new(
3632 this.clone(),
3633 commit.sha.clone(),
3634 repo.clone(),
3635 window,
3636 cx,
3637 )
3638 .into()
3639 }
3640 }),
3641 )
3642 .when(commit.has_parent, |this| {
3643 let has_unstaged = self.has_unstaged_changes();
3644 this.child(
3645 panel_icon_button("undo", IconName::Undo)
3646 .icon_size(IconSize::XSmall)
3647 .icon_color(Color::Muted)
3648 .tooltip(move |_window, cx| {
3649 Tooltip::with_meta(
3650 "Uncommit",
3651 Some(&git::Uncommit),
3652 if has_unstaged {
3653 "git reset HEAD^ --soft"
3654 } else {
3655 "git reset HEAD^"
3656 },
3657 cx,
3658 )
3659 })
3660 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3661 )
3662 }),
3663 )
3664 }
3665
3666 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3667 h_flex().h_full().flex_grow().justify_center().child(
3668 v_flex()
3669 .gap_2()
3670 .child(h_flex().w_full().justify_around().child(
3671 if self.active_repository.is_some() {
3672 "No changes to commit"
3673 } else {
3674 "No Git repositories"
3675 },
3676 ))
3677 .children({
3678 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3679 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3680 h_flex().w_full().justify_around().child(
3681 panel_filled_button("Initialize Repository")
3682 .tooltip(Tooltip::for_action_title_in(
3683 "git init",
3684 &git::Init,
3685 &self.focus_handle,
3686 ))
3687 .on_click(move |_, _, cx| {
3688 cx.defer(move |cx| {
3689 cx.dispatch_action(&git::Init);
3690 })
3691 }),
3692 )
3693 })
3694 })
3695 .text_ui_sm(cx)
3696 .mx_auto()
3697 .text_color(Color::Placeholder.color(cx)),
3698 )
3699 }
3700
3701 fn render_buffer_header_controls(
3702 &self,
3703 entity: &Entity<Self>,
3704 file: &Arc<dyn File>,
3705 _: &Window,
3706 cx: &App,
3707 ) -> Option<AnyElement> {
3708 let repo = self.active_repository.as_ref()?.read(cx);
3709 let project_path = (file.worktree_id(cx), file.path().clone()).into();
3710 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3711 let ix = self.entry_by_path(&repo_path, cx)?;
3712 let entry = self.entries.get(ix)?;
3713
3714 let entry_staging = self.entry_staging(entry.status_entry()?);
3715
3716 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3717 .disabled(!self.has_write_access(cx))
3718 .fill()
3719 .elevation(ElevationIndex::Surface)
3720 .on_click({
3721 let entry = entry.clone();
3722 let git_panel = entity.downgrade();
3723 move |_, window, cx| {
3724 git_panel
3725 .update(cx, |this, cx| {
3726 this.toggle_staged_for_entry(&entry, window, cx);
3727 cx.stop_propagation();
3728 })
3729 .ok();
3730 }
3731 });
3732 Some(
3733 h_flex()
3734 .id("start-slot")
3735 .text_lg()
3736 .child(checkbox)
3737 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3738 // prevent the list item active state triggering when toggling checkbox
3739 cx.stop_propagation();
3740 })
3741 .into_any_element(),
3742 )
3743 }
3744
3745 fn render_entries(
3746 &self,
3747 has_write_access: bool,
3748 window: &mut Window,
3749 cx: &mut Context<Self>,
3750 ) -> impl IntoElement {
3751 let entry_count = self.entries.len();
3752
3753 v_flex()
3754 .flex_1()
3755 .size_full()
3756 .overflow_hidden()
3757 .relative()
3758 .child(
3759 h_flex()
3760 .flex_1()
3761 .size_full()
3762 .relative()
3763 .overflow_hidden()
3764 .child(
3765 uniform_list(
3766 "entries",
3767 entry_count,
3768 cx.processor(move |this, range: Range<usize>, window, cx| {
3769 let mut items = Vec::with_capacity(range.end - range.start);
3770
3771 for ix in range {
3772 match &this.entries.get(ix) {
3773 Some(GitListEntry::Status(entry)) => {
3774 items.push(this.render_entry(
3775 ix,
3776 entry,
3777 has_write_access,
3778 window,
3779 cx,
3780 ));
3781 }
3782 Some(GitListEntry::Header(header)) => {
3783 items.push(this.render_list_header(
3784 ix,
3785 header,
3786 has_write_access,
3787 window,
3788 cx,
3789 ));
3790 }
3791 None => {}
3792 }
3793 }
3794
3795 items
3796 }),
3797 )
3798 .size_full()
3799 .flex_grow()
3800 .with_sizing_behavior(ListSizingBehavior::Auto)
3801 .with_horizontal_sizing_behavior(
3802 ListHorizontalSizingBehavior::Unconstrained,
3803 )
3804 .with_width_from_item(self.max_width_item_index)
3805 .track_scroll(self.scroll_handle.clone()),
3806 )
3807 .on_mouse_down(
3808 MouseButton::Right,
3809 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3810 this.deploy_panel_context_menu(event.position, window, cx)
3811 }),
3812 )
3813 .custom_scrollbars(
3814 Scrollbars::for_settings::<GitPanelSettings>()
3815 .tracked_scroll_handle(self.scroll_handle.clone())
3816 .with_track_along(
3817 ScrollAxes::Horizontal,
3818 cx.theme().colors().panel_background,
3819 ),
3820 window,
3821 cx,
3822 ),
3823 )
3824 }
3825
3826 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3827 Label::new(label.into()).color(color).single_line()
3828 }
3829
3830 fn list_item_height(&self) -> Rems {
3831 rems(1.75)
3832 }
3833
3834 fn render_list_header(
3835 &self,
3836 ix: usize,
3837 header: &GitHeaderEntry,
3838 _: bool,
3839 _: &Window,
3840 _: &Context<Self>,
3841 ) -> AnyElement {
3842 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3843
3844 h_flex()
3845 .id(id)
3846 .h(self.list_item_height())
3847 .w_full()
3848 .items_end()
3849 .px(rems(0.75)) // ~12px
3850 .pb(rems(0.3125)) // ~ 5px
3851 .child(
3852 Label::new(header.title())
3853 .color(Color::Muted)
3854 .size(LabelSize::Small)
3855 .line_height_style(LineHeightStyle::UiLabel)
3856 .single_line(),
3857 )
3858 .into_any_element()
3859 }
3860
3861 pub fn load_commit_details(
3862 &self,
3863 sha: String,
3864 cx: &mut Context<Self>,
3865 ) -> Task<anyhow::Result<CommitDetails>> {
3866 let Some(repo) = self.active_repository.clone() else {
3867 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3868 };
3869 repo.update(cx, |repo, cx| {
3870 let show = repo.show(sha);
3871 cx.spawn(async move |_, _| show.await?)
3872 })
3873 }
3874
3875 fn deploy_entry_context_menu(
3876 &mut self,
3877 position: Point<Pixels>,
3878 ix: usize,
3879 window: &mut Window,
3880 cx: &mut Context<Self>,
3881 ) {
3882 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3883 return;
3884 };
3885 let stage_title = if entry.status.staging().is_fully_staged() {
3886 "Unstage File"
3887 } else {
3888 "Stage File"
3889 };
3890 let restore_title = if entry.status.is_created() {
3891 "Trash File"
3892 } else {
3893 "Restore File"
3894 };
3895 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3896 let mut context_menu = context_menu
3897 .context(self.focus_handle.clone())
3898 .action(stage_title, ToggleStaged.boxed_clone())
3899 .action(restore_title, git::RestoreFile::default().boxed_clone());
3900
3901 if entry.status.is_created() {
3902 context_menu =
3903 context_menu.action("Add to .gitignore", git::AddToGitignore.boxed_clone());
3904 }
3905
3906 context_menu
3907 .separator()
3908 .action("Open Diff", Confirm.boxed_clone())
3909 .action("Open File", SecondaryConfirm.boxed_clone())
3910 });
3911 self.selected_entry = Some(ix);
3912 self.set_context_menu(context_menu, position, window, cx);
3913 }
3914
3915 fn deploy_panel_context_menu(
3916 &mut self,
3917 position: Point<Pixels>,
3918 window: &mut Window,
3919 cx: &mut Context<Self>,
3920 ) {
3921 let context_menu = git_panel_context_menu(
3922 self.focus_handle.clone(),
3923 GitMenuState {
3924 has_tracked_changes: self.has_tracked_changes(),
3925 has_staged_changes: self.has_staged_changes(),
3926 has_unstaged_changes: self.has_unstaged_changes(),
3927 has_new_changes: self.new_count > 0,
3928 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3929 has_stash_items: self.stash_entries.entries.len() > 0,
3930 },
3931 window,
3932 cx,
3933 );
3934 self.set_context_menu(context_menu, position, window, cx);
3935 }
3936
3937 fn set_context_menu(
3938 &mut self,
3939 context_menu: Entity<ContextMenu>,
3940 position: Point<Pixels>,
3941 window: &Window,
3942 cx: &mut Context<Self>,
3943 ) {
3944 let subscription = cx.subscribe_in(
3945 &context_menu,
3946 window,
3947 |this, _, _: &DismissEvent, window, cx| {
3948 if this.context_menu.as_ref().is_some_and(|context_menu| {
3949 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3950 }) {
3951 cx.focus_self(window);
3952 }
3953 this.context_menu.take();
3954 cx.notify();
3955 },
3956 );
3957 self.context_menu = Some((context_menu, position, subscription));
3958 cx.notify();
3959 }
3960
3961 fn render_entry(
3962 &self,
3963 ix: usize,
3964 entry: &GitStatusEntry,
3965 has_write_access: bool,
3966 window: &Window,
3967 cx: &Context<Self>,
3968 ) -> AnyElement {
3969 let path_style = self.project.read(cx).path_style(cx);
3970 let display_name = entry.display_name(path_style);
3971
3972 let selected = self.selected_entry == Some(ix);
3973 let marked = self.marked_entries.contains(&ix);
3974 let status_style = GitPanelSettings::get_global(cx).status_style;
3975 let status = entry.status;
3976
3977 let has_conflict = status.is_conflicted();
3978 let is_modified = status.is_modified();
3979 let is_deleted = status.is_deleted();
3980
3981 let label_color = if status_style == StatusStyle::LabelColor {
3982 if has_conflict {
3983 Color::VersionControlConflict
3984 } else if is_modified {
3985 Color::VersionControlModified
3986 } else if is_deleted {
3987 // We don't want a bunch of red labels in the list
3988 Color::Disabled
3989 } else {
3990 Color::VersionControlAdded
3991 }
3992 } else {
3993 Color::Default
3994 };
3995
3996 let path_color = if status.is_deleted() {
3997 Color::Disabled
3998 } else {
3999 Color::Muted
4000 };
4001
4002 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4003 let checkbox_wrapper_id: ElementId =
4004 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4005 let checkbox_id: ElementId =
4006 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4007
4008 let entry_staging = self.entry_staging(entry);
4009 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4010 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4011 is_staged = ToggleState::Selected;
4012 }
4013
4014 let handle = cx.weak_entity();
4015
4016 let selected_bg_alpha = 0.08;
4017 let marked_bg_alpha = 0.12;
4018 let state_opacity_step = 0.04;
4019
4020 let base_bg = match (selected, marked) {
4021 (true, true) => cx
4022 .theme()
4023 .status()
4024 .info
4025 .alpha(selected_bg_alpha + marked_bg_alpha),
4026 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4027 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4028 _ => cx.theme().colors().ghost_element_background,
4029 };
4030
4031 let hover_bg = if selected {
4032 cx.theme()
4033 .status()
4034 .info
4035 .alpha(selected_bg_alpha + state_opacity_step)
4036 } else {
4037 cx.theme().colors().ghost_element_hover
4038 };
4039
4040 let active_bg = if selected {
4041 cx.theme()
4042 .status()
4043 .info
4044 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4045 } else {
4046 cx.theme().colors().ghost_element_active
4047 };
4048
4049 h_flex()
4050 .id(id)
4051 .h(self.list_item_height())
4052 .w_full()
4053 .items_center()
4054 .border_1()
4055 .when(selected && self.focus_handle.is_focused(window), |el| {
4056 el.border_color(cx.theme().colors().border_focused)
4057 })
4058 .px(rems(0.75)) // ~12px
4059 .overflow_hidden()
4060 .flex_none()
4061 .gap_1p5()
4062 .bg(base_bg)
4063 .hover(|this| this.bg(hover_bg))
4064 .active(|this| this.bg(active_bg))
4065 .on_click({
4066 cx.listener(move |this, event: &ClickEvent, window, cx| {
4067 this.selected_entry = Some(ix);
4068 cx.notify();
4069 if event.modifiers().secondary() {
4070 this.open_file(&Default::default(), window, cx)
4071 } else {
4072 this.open_diff(&Default::default(), window, cx);
4073 this.focus_handle.focus(window);
4074 }
4075 })
4076 })
4077 .on_mouse_down(
4078 MouseButton::Right,
4079 move |event: &MouseDownEvent, window, cx| {
4080 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4081 if event.button != MouseButton::Right {
4082 return;
4083 }
4084
4085 let Some(this) = handle.upgrade() else {
4086 return;
4087 };
4088 this.update(cx, |this, cx| {
4089 this.deploy_entry_context_menu(event.position, ix, window, cx);
4090 });
4091 cx.stop_propagation();
4092 },
4093 )
4094 .child(
4095 div()
4096 .id(checkbox_wrapper_id)
4097 .flex_none()
4098 .occlude()
4099 .cursor_pointer()
4100 .child(
4101 Checkbox::new(checkbox_id, is_staged)
4102 .disabled(!has_write_access)
4103 .fill()
4104 .elevation(ElevationIndex::Surface)
4105 .on_click_ext({
4106 let entry = entry.clone();
4107 let this = cx.weak_entity();
4108 move |_, click, window, cx| {
4109 this.update(cx, |this, cx| {
4110 if !has_write_access {
4111 return;
4112 }
4113 if click.modifiers().shift {
4114 this.stage_bulk(ix, cx);
4115 } else {
4116 this.toggle_staged_for_entry(
4117 &GitListEntry::Status(entry.clone()),
4118 window,
4119 cx,
4120 );
4121 }
4122 cx.stop_propagation();
4123 })
4124 .ok();
4125 }
4126 })
4127 .tooltip(move |_window, cx| {
4128 let is_staged = entry_staging.is_fully_staged();
4129
4130 let action = if is_staged { "Unstage" } else { "Stage" };
4131 let tooltip_name = action.to_string();
4132
4133 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
4134 }),
4135 ),
4136 )
4137 .child(git_status_icon(status))
4138 .child(
4139 h_flex()
4140 .items_center()
4141 .flex_1()
4142 // .overflow_hidden()
4143 .when_some(entry.parent_dir(path_style), |this, parent| {
4144 if !parent.is_empty() {
4145 this.child(
4146 self.entry_label(
4147 format!("{parent}{}", path_style.separator()),
4148 path_color,
4149 )
4150 .when(status.is_deleted(), |this| this.strikethrough()),
4151 )
4152 } else {
4153 this
4154 }
4155 })
4156 .child(
4157 self.entry_label(display_name, label_color)
4158 .when(status.is_deleted(), |this| this.strikethrough()),
4159 ),
4160 )
4161 .into_any_element()
4162 }
4163
4164 fn has_write_access(&self, cx: &App) -> bool {
4165 !self.project.read(cx).is_read_only(cx)
4166 }
4167
4168 pub fn amend_pending(&self) -> bool {
4169 self.amend_pending
4170 }
4171
4172 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4173 if value && !self.amend_pending {
4174 let current_message = self.commit_message_buffer(cx).read(cx).text();
4175 self.original_commit_message = if current_message.trim().is_empty() {
4176 None
4177 } else {
4178 Some(current_message)
4179 };
4180 } else if !value && self.amend_pending {
4181 let message = self.original_commit_message.take().unwrap_or_default();
4182 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4183 let start = buffer.anchor_before(0);
4184 let end = buffer.anchor_after(buffer.len());
4185 buffer.edit([(start..end, message)], None, cx);
4186 });
4187 }
4188
4189 self.amend_pending = value;
4190 self.serialize(cx);
4191 cx.notify();
4192 }
4193
4194 pub fn signoff_enabled(&self) -> bool {
4195 self.signoff_enabled
4196 }
4197
4198 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4199 self.signoff_enabled = value;
4200 self.serialize(cx);
4201 cx.notify();
4202 }
4203
4204 pub fn toggle_signoff_enabled(
4205 &mut self,
4206 _: &Signoff,
4207 _window: &mut Window,
4208 cx: &mut Context<Self>,
4209 ) {
4210 self.set_signoff_enabled(!self.signoff_enabled, cx);
4211 }
4212
4213 pub async fn load(
4214 workspace: WeakEntity<Workspace>,
4215 mut cx: AsyncWindowContext,
4216 ) -> anyhow::Result<Entity<Self>> {
4217 let serialized_panel = match workspace
4218 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4219 .ok()
4220 .flatten()
4221 {
4222 Some(serialization_key) => cx
4223 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4224 .await
4225 .context("loading git panel")
4226 .log_err()
4227 .flatten()
4228 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4229 .transpose()
4230 .log_err()
4231 .flatten(),
4232 None => None,
4233 };
4234
4235 workspace.update_in(&mut cx, |workspace, window, cx| {
4236 let panel = GitPanel::new(workspace, window, cx);
4237
4238 if let Some(serialized_panel) = serialized_panel {
4239 panel.update(cx, |panel, cx| {
4240 panel.width = serialized_panel.width;
4241 panel.amend_pending = serialized_panel.amend_pending;
4242 panel.signoff_enabled = serialized_panel.signoff_enabled;
4243 cx.notify();
4244 })
4245 }
4246
4247 panel
4248 })
4249 }
4250
4251 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4252 let Some(op) = self.bulk_staging.as_ref() else {
4253 return;
4254 };
4255 let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4256 return;
4257 };
4258 if let Some(entry) = self.entries.get(index)
4259 && let Some(entry) = entry.status_entry()
4260 {
4261 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4262 }
4263 if index < anchor_index {
4264 std::mem::swap(&mut index, &mut anchor_index);
4265 }
4266 let entries = self
4267 .entries
4268 .get(anchor_index..=index)
4269 .unwrap_or_default()
4270 .iter()
4271 .filter_map(|entry| entry.status_entry().cloned())
4272 .collect::<Vec<_>>();
4273 self.change_file_stage(true, entries, cx);
4274 }
4275
4276 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4277 let Some(repo) = self.active_repository.as_ref() else {
4278 return;
4279 };
4280 self.bulk_staging = Some(BulkStaging {
4281 repo_id: repo.read(cx).id,
4282 anchor: path,
4283 });
4284 }
4285
4286 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4287 self.set_amend_pending(!self.amend_pending, cx);
4288 if self.amend_pending {
4289 self.load_last_commit_message_if_empty(cx);
4290 }
4291 }
4292}
4293
4294impl Render for GitPanel {
4295 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4296 let project = self.project.read(cx);
4297 let has_entries = !self.entries.is_empty();
4298 let room = self
4299 .workspace
4300 .upgrade()
4301 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4302
4303 let has_write_access = self.has_write_access(cx);
4304
4305 let has_co_authors = room.is_some_and(|room| {
4306 self.load_local_committer(cx);
4307 let room = room.read(cx);
4308 room.remote_participants()
4309 .values()
4310 .any(|remote_participant| remote_participant.can_write())
4311 });
4312
4313 v_flex()
4314 .id("git_panel")
4315 .key_context(self.dispatch_context(window, cx))
4316 .track_focus(&self.focus_handle)
4317 .when(has_write_access && !project.is_read_only(cx), |this| {
4318 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4319 .on_action(cx.listener(Self::stage_range))
4320 .on_action(cx.listener(GitPanel::commit))
4321 .on_action(cx.listener(GitPanel::amend))
4322 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4323 .on_action(cx.listener(Self::stage_all))
4324 .on_action(cx.listener(Self::unstage_all))
4325 .on_action(cx.listener(Self::stage_selected))
4326 .on_action(cx.listener(Self::unstage_selected))
4327 .on_action(cx.listener(Self::restore_tracked_files))
4328 .on_action(cx.listener(Self::revert_selected))
4329 .on_action(cx.listener(Self::add_to_gitignore))
4330 .on_action(cx.listener(Self::clean_all))
4331 .on_action(cx.listener(Self::generate_commit_message_action))
4332 .on_action(cx.listener(Self::stash_all))
4333 .on_action(cx.listener(Self::stash_pop))
4334 })
4335 .on_action(cx.listener(Self::select_first))
4336 .on_action(cx.listener(Self::select_next))
4337 .on_action(cx.listener(Self::select_previous))
4338 .on_action(cx.listener(Self::select_last))
4339 .on_action(cx.listener(Self::close_panel))
4340 .on_action(cx.listener(Self::open_diff))
4341 .on_action(cx.listener(Self::open_file))
4342 .on_action(cx.listener(Self::focus_changes_list))
4343 .on_action(cx.listener(Self::focus_editor))
4344 .on_action(cx.listener(Self::expand_commit_editor))
4345 .when(has_write_access && has_co_authors, |git_panel| {
4346 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4347 })
4348 .on_action(cx.listener(Self::toggle_sort_by_path))
4349 .size_full()
4350 .overflow_hidden()
4351 .bg(cx.theme().colors().panel_background)
4352 .child(
4353 v_flex()
4354 .size_full()
4355 .children(self.render_panel_header(window, cx))
4356 .map(|this| {
4357 if has_entries {
4358 this.child(self.render_entries(has_write_access, window, cx))
4359 } else {
4360 this.child(self.render_empty_state(cx).into_any_element())
4361 }
4362 })
4363 .children(self.render_footer(window, cx))
4364 .when(self.amend_pending, |this| {
4365 this.child(self.render_pending_amend(cx))
4366 })
4367 .when(!self.amend_pending, |this| {
4368 this.children(self.render_previous_commit(cx))
4369 })
4370 .into_any_element(),
4371 )
4372 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4373 deferred(
4374 anchored()
4375 .position(*position)
4376 .anchor(Corner::TopLeft)
4377 .child(menu.clone()),
4378 )
4379 .with_priority(1)
4380 }))
4381 }
4382}
4383
4384impl Focusable for GitPanel {
4385 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4386 if self.entries.is_empty() {
4387 self.commit_editor.focus_handle(cx)
4388 } else {
4389 self.focus_handle.clone()
4390 }
4391 }
4392}
4393
4394impl EventEmitter<Event> for GitPanel {}
4395
4396impl EventEmitter<PanelEvent> for GitPanel {}
4397
4398pub(crate) struct GitPanelAddon {
4399 pub(crate) workspace: WeakEntity<Workspace>,
4400}
4401
4402impl editor::Addon for GitPanelAddon {
4403 fn to_any(&self) -> &dyn std::any::Any {
4404 self
4405 }
4406
4407 fn render_buffer_header_controls(
4408 &self,
4409 excerpt_info: &ExcerptInfo,
4410 window: &Window,
4411 cx: &App,
4412 ) -> Option<AnyElement> {
4413 let file = excerpt_info.buffer.file()?;
4414 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4415
4416 git_panel
4417 .read(cx)
4418 .render_buffer_header_controls(&git_panel, file, window, cx)
4419 }
4420}
4421
4422impl Panel for GitPanel {
4423 fn persistent_name() -> &'static str {
4424 "GitPanel"
4425 }
4426
4427 fn panel_key() -> &'static str {
4428 GIT_PANEL_KEY
4429 }
4430
4431 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4432 GitPanelSettings::get_global(cx).dock
4433 }
4434
4435 fn position_is_valid(&self, position: DockPosition) -> bool {
4436 matches!(position, DockPosition::Left | DockPosition::Right)
4437 }
4438
4439 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4440 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
4441 settings.git_panel.get_or_insert_default().dock = Some(position.into())
4442 });
4443 }
4444
4445 fn size(&self, _: &Window, cx: &App) -> Pixels {
4446 self.width
4447 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4448 }
4449
4450 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4451 self.width = size;
4452 self.serialize(cx);
4453 cx.notify();
4454 }
4455
4456 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4457 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4458 }
4459
4460 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4461 Some("Git Panel")
4462 }
4463
4464 fn toggle_action(&self) -> Box<dyn Action> {
4465 Box::new(ToggleFocus)
4466 }
4467
4468 fn activation_priority(&self) -> u32 {
4469 2
4470 }
4471}
4472
4473impl PanelHeader for GitPanel {}
4474
4475struct GitPanelMessageTooltip {
4476 commit_tooltip: Option<Entity<CommitTooltip>>,
4477}
4478
4479impl GitPanelMessageTooltip {
4480 fn new(
4481 git_panel: Entity<GitPanel>,
4482 sha: SharedString,
4483 repository: Entity<Repository>,
4484 window: &mut Window,
4485 cx: &mut App,
4486 ) -> Entity<Self> {
4487 cx.new(|cx| {
4488 cx.spawn_in(window, async move |this, cx| {
4489 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4490 (
4491 git_panel.load_commit_details(sha.to_string(), cx),
4492 git_panel.workspace.clone(),
4493 )
4494 })?;
4495 let details = details.await?;
4496
4497 let commit_details = crate::commit_tooltip::CommitDetails {
4498 sha: details.sha.clone(),
4499 author_name: details.author_name.clone(),
4500 author_email: details.author_email.clone(),
4501 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4502 message: Some(ParsedCommitMessage {
4503 message: details.message,
4504 ..Default::default()
4505 }),
4506 };
4507
4508 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4509 this.commit_tooltip = Some(cx.new(move |cx| {
4510 CommitTooltip::new(commit_details, repository, workspace, cx)
4511 }));
4512 cx.notify();
4513 })
4514 })
4515 .detach();
4516
4517 Self {
4518 commit_tooltip: None,
4519 }
4520 })
4521 }
4522}
4523
4524impl Render for GitPanelMessageTooltip {
4525 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4526 if let Some(commit_tooltip) = &self.commit_tooltip {
4527 commit_tooltip.clone().into_any_element()
4528 } else {
4529 gpui::Empty.into_any_element()
4530 }
4531 }
4532}
4533
4534#[derive(IntoElement, RegisterComponent)]
4535pub struct PanelRepoFooter {
4536 active_repository: SharedString,
4537 branch: Option<Branch>,
4538 head_commit: Option<CommitDetails>,
4539
4540 // Getting a GitPanel in previews will be difficult.
4541 //
4542 // For now just take an option here, and we won't bind handlers to buttons in previews.
4543 git_panel: Option<Entity<GitPanel>>,
4544}
4545
4546impl PanelRepoFooter {
4547 pub fn new(
4548 active_repository: SharedString,
4549 branch: Option<Branch>,
4550 head_commit: Option<CommitDetails>,
4551 git_panel: Option<Entity<GitPanel>>,
4552 ) -> Self {
4553 Self {
4554 active_repository,
4555 branch,
4556 head_commit,
4557 git_panel,
4558 }
4559 }
4560
4561 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4562 Self {
4563 active_repository,
4564 branch,
4565 head_commit: None,
4566 git_panel: None,
4567 }
4568 }
4569}
4570
4571impl RenderOnce for PanelRepoFooter {
4572 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4573 let project = self
4574 .git_panel
4575 .as_ref()
4576 .map(|panel| panel.read(cx).project.clone());
4577
4578 let repo = self
4579 .git_panel
4580 .as_ref()
4581 .and_then(|panel| panel.read(cx).active_repository.clone());
4582
4583 let single_repo = project
4584 .as_ref()
4585 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4586 .unwrap_or(true);
4587
4588 const MAX_BRANCH_LEN: usize = 16;
4589 const MAX_REPO_LEN: usize = 16;
4590 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4591 const MAX_SHORT_SHA_LEN: usize = 8;
4592
4593 let branch_name = self
4594 .branch
4595 .as_ref()
4596 .map(|branch| branch.name().to_owned())
4597 .or_else(|| {
4598 self.head_commit.as_ref().map(|commit| {
4599 commit
4600 .sha
4601 .chars()
4602 .take(MAX_SHORT_SHA_LEN)
4603 .collect::<String>()
4604 })
4605 })
4606 .unwrap_or_else(|| " (no branch)".to_owned());
4607 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4608
4609 let active_repo_name = self.active_repository.clone();
4610
4611 let branch_actual_len = branch_name.len();
4612 let repo_actual_len = active_repo_name.len();
4613
4614 // ideally, show the whole branch and repo names but
4615 // when we can't, use a budget to allocate space between the two
4616 let (repo_display_len, branch_display_len) =
4617 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4618 (repo_actual_len, branch_actual_len)
4619 } else if branch_actual_len <= MAX_BRANCH_LEN {
4620 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4621 (repo_space, branch_actual_len)
4622 } else if repo_actual_len <= MAX_REPO_LEN {
4623 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4624 (repo_actual_len, branch_space)
4625 } else {
4626 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4627 };
4628
4629 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4630 active_repo_name.to_string()
4631 } else {
4632 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4633 };
4634
4635 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4636 branch_name
4637 } else {
4638 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4639 };
4640
4641 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4642 .size(ButtonSize::None)
4643 .label_size(LabelSize::Small)
4644 .color(Color::Muted);
4645
4646 let repo_selector = PopoverMenu::new("repository-switcher")
4647 .menu({
4648 let project = project;
4649 move |window, cx| {
4650 let project = project.clone()?;
4651 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4652 }
4653 })
4654 .trigger_with_tooltip(
4655 repo_selector_trigger.disabled(single_repo).truncate(true),
4656 Tooltip::text("Switch Active Repository"),
4657 )
4658 .anchor(Corner::BottomLeft)
4659 .into_any_element();
4660
4661 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4662 .size(ButtonSize::None)
4663 .label_size(LabelSize::Small)
4664 .truncate(true)
4665 .on_click(|_, window, cx| {
4666 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4667 });
4668
4669 let branch_selector = PopoverMenu::new("popover-button")
4670 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4671 .trigger_with_tooltip(
4672 branch_selector_button,
4673 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4674 )
4675 .anchor(Corner::BottomLeft)
4676 .offset(gpui::Point {
4677 x: px(0.0),
4678 y: px(-2.0),
4679 });
4680
4681 h_flex()
4682 .h(px(36.))
4683 .w_full()
4684 .px_2()
4685 .justify_between()
4686 .gap_1()
4687 .child(
4688 h_flex()
4689 .flex_1()
4690 .overflow_hidden()
4691 .gap_px()
4692 .child(
4693 Icon::new(IconName::GitBranchAlt)
4694 .size(IconSize::Small)
4695 .color(if single_repo {
4696 Color::Disabled
4697 } else {
4698 Color::Muted
4699 }),
4700 )
4701 .child(repo_selector)
4702 .when(show_separator, |this| {
4703 this.child(
4704 div()
4705 .text_sm()
4706 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
4707 .child("/"),
4708 )
4709 })
4710 .child(branch_selector),
4711 )
4712 .children(if let Some(git_panel) = self.git_panel {
4713 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4714 } else {
4715 None
4716 })
4717 }
4718}
4719
4720impl Component for PanelRepoFooter {
4721 fn scope() -> ComponentScope {
4722 ComponentScope::VersionControl
4723 }
4724
4725 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4726 let unknown_upstream = None;
4727 let no_remote_upstream = Some(UpstreamTracking::Gone);
4728 let ahead_of_upstream = Some(
4729 UpstreamTrackingStatus {
4730 ahead: 2,
4731 behind: 0,
4732 }
4733 .into(),
4734 );
4735 let behind_upstream = Some(
4736 UpstreamTrackingStatus {
4737 ahead: 0,
4738 behind: 2,
4739 }
4740 .into(),
4741 );
4742 let ahead_and_behind_upstream = Some(
4743 UpstreamTrackingStatus {
4744 ahead: 3,
4745 behind: 1,
4746 }
4747 .into(),
4748 );
4749
4750 let not_ahead_or_behind_upstream = Some(
4751 UpstreamTrackingStatus {
4752 ahead: 0,
4753 behind: 0,
4754 }
4755 .into(),
4756 );
4757
4758 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4759 Branch {
4760 is_head: true,
4761 ref_name: "some-branch".into(),
4762 upstream: upstream.map(|tracking| Upstream {
4763 ref_name: "origin/some-branch".into(),
4764 tracking,
4765 }),
4766 most_recent_commit: Some(CommitSummary {
4767 sha: "abc123".into(),
4768 subject: "Modify stuff".into(),
4769 commit_timestamp: 1710932954,
4770 author_name: "John Doe".into(),
4771 has_parent: true,
4772 }),
4773 }
4774 }
4775
4776 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4777 Branch {
4778 is_head: true,
4779 ref_name: branch_name.to_string().into(),
4780 upstream: upstream.map(|tracking| Upstream {
4781 ref_name: format!("zed/{}", branch_name).into(),
4782 tracking,
4783 }),
4784 most_recent_commit: Some(CommitSummary {
4785 sha: "abc123".into(),
4786 subject: "Modify stuff".into(),
4787 commit_timestamp: 1710932954,
4788 author_name: "John Doe".into(),
4789 has_parent: true,
4790 }),
4791 }
4792 }
4793
4794 fn active_repository(id: usize) -> SharedString {
4795 format!("repo-{}", id).into()
4796 }
4797
4798 let example_width = px(340.);
4799 Some(
4800 v_flex()
4801 .gap_6()
4802 .w_full()
4803 .flex_none()
4804 .children(vec![
4805 example_group_with_title(
4806 "Action Button States",
4807 vec![
4808 single_example(
4809 "No Branch",
4810 div()
4811 .w(example_width)
4812 .overflow_hidden()
4813 .child(PanelRepoFooter::new_preview(active_repository(1), None))
4814 .into_any_element(),
4815 ),
4816 single_example(
4817 "Remote status unknown",
4818 div()
4819 .w(example_width)
4820 .overflow_hidden()
4821 .child(PanelRepoFooter::new_preview(
4822 active_repository(2),
4823 Some(branch(unknown_upstream)),
4824 ))
4825 .into_any_element(),
4826 ),
4827 single_example(
4828 "No Remote Upstream",
4829 div()
4830 .w(example_width)
4831 .overflow_hidden()
4832 .child(PanelRepoFooter::new_preview(
4833 active_repository(3),
4834 Some(branch(no_remote_upstream)),
4835 ))
4836 .into_any_element(),
4837 ),
4838 single_example(
4839 "Not Ahead or Behind",
4840 div()
4841 .w(example_width)
4842 .overflow_hidden()
4843 .child(PanelRepoFooter::new_preview(
4844 active_repository(4),
4845 Some(branch(not_ahead_or_behind_upstream)),
4846 ))
4847 .into_any_element(),
4848 ),
4849 single_example(
4850 "Behind remote",
4851 div()
4852 .w(example_width)
4853 .overflow_hidden()
4854 .child(PanelRepoFooter::new_preview(
4855 active_repository(5),
4856 Some(branch(behind_upstream)),
4857 ))
4858 .into_any_element(),
4859 ),
4860 single_example(
4861 "Ahead of remote",
4862 div()
4863 .w(example_width)
4864 .overflow_hidden()
4865 .child(PanelRepoFooter::new_preview(
4866 active_repository(6),
4867 Some(branch(ahead_of_upstream)),
4868 ))
4869 .into_any_element(),
4870 ),
4871 single_example(
4872 "Ahead and behind remote",
4873 div()
4874 .w(example_width)
4875 .overflow_hidden()
4876 .child(PanelRepoFooter::new_preview(
4877 active_repository(7),
4878 Some(branch(ahead_and_behind_upstream)),
4879 ))
4880 .into_any_element(),
4881 ),
4882 ],
4883 )
4884 .grow()
4885 .vertical(),
4886 ])
4887 .children(vec![
4888 example_group_with_title(
4889 "Labels",
4890 vec![
4891 single_example(
4892 "Short Branch & Repo",
4893 div()
4894 .w(example_width)
4895 .overflow_hidden()
4896 .child(PanelRepoFooter::new_preview(
4897 SharedString::from("zed"),
4898 Some(custom("main", behind_upstream)),
4899 ))
4900 .into_any_element(),
4901 ),
4902 single_example(
4903 "Long Branch",
4904 div()
4905 .w(example_width)
4906 .overflow_hidden()
4907 .child(PanelRepoFooter::new_preview(
4908 SharedString::from("zed"),
4909 Some(custom(
4910 "redesign-and-update-git-ui-list-entry-style",
4911 behind_upstream,
4912 )),
4913 ))
4914 .into_any_element(),
4915 ),
4916 single_example(
4917 "Long Repo",
4918 div()
4919 .w(example_width)
4920 .overflow_hidden()
4921 .child(PanelRepoFooter::new_preview(
4922 SharedString::from("zed-industries-community-examples"),
4923 Some(custom("gpui", ahead_of_upstream)),
4924 ))
4925 .into_any_element(),
4926 ),
4927 single_example(
4928 "Long Repo & Branch",
4929 div()
4930 .w(example_width)
4931 .overflow_hidden()
4932 .child(PanelRepoFooter::new_preview(
4933 SharedString::from("zed-industries-community-examples"),
4934 Some(custom(
4935 "redesign-and-update-git-ui-list-entry-style",
4936 behind_upstream,
4937 )),
4938 ))
4939 .into_any_element(),
4940 ),
4941 single_example(
4942 "Uppercase Repo",
4943 div()
4944 .w(example_width)
4945 .overflow_hidden()
4946 .child(PanelRepoFooter::new_preview(
4947 SharedString::from("LICENSES"),
4948 Some(custom("main", ahead_of_upstream)),
4949 ))
4950 .into_any_element(),
4951 ),
4952 single_example(
4953 "Uppercase Branch",
4954 div()
4955 .w(example_width)
4956 .overflow_hidden()
4957 .child(PanelRepoFooter::new_preview(
4958 SharedString::from("zed"),
4959 Some(custom("update-README", behind_upstream)),
4960 ))
4961 .into_any_element(),
4962 ),
4963 ],
4964 )
4965 .grow()
4966 .vertical(),
4967 ])
4968 .into_any_element(),
4969 )
4970 }
4971}
4972
4973#[cfg(test)]
4974mod tests {
4975 use git::{
4976 repository::repo_path,
4977 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
4978 };
4979 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
4980 use project::{FakeFs, WorktreeSettings};
4981 use serde_json::json;
4982 use settings::SettingsStore;
4983 use theme::LoadThemes;
4984 use util::path;
4985 use util::rel_path::rel_path;
4986
4987 use super::*;
4988
4989 fn init_test(cx: &mut gpui::TestAppContext) {
4990 zlog::init_test();
4991
4992 cx.update(|cx| {
4993 let settings_store = SettingsStore::test(cx);
4994 cx.set_global(settings_store);
4995 AgentSettings::register(cx);
4996 WorktreeSettings::register(cx);
4997 workspace::init_settings(cx);
4998 theme::init(LoadThemes::JustBase, cx);
4999 language::init(cx);
5000 editor::init(cx);
5001 Project::init_settings(cx);
5002 crate::init(cx);
5003 });
5004 }
5005
5006 #[gpui::test]
5007 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5008 init_test(cx);
5009 let fs = FakeFs::new(cx.background_executor.clone());
5010 fs.insert_tree(
5011 "/root",
5012 json!({
5013 "zed": {
5014 ".git": {},
5015 "crates": {
5016 "gpui": {
5017 "gpui.rs": "fn main() {}"
5018 },
5019 "util": {
5020 "util.rs": "fn do_it() {}"
5021 }
5022 }
5023 },
5024 }),
5025 )
5026 .await;
5027
5028 fs.set_status_for_repo(
5029 Path::new(path!("/root/zed/.git")),
5030 &[
5031 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
5032 ("crates/util/util.rs", StatusCode::Modified.worktree()),
5033 ],
5034 );
5035
5036 let project =
5037 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5038 let workspace =
5039 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5040 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5041
5042 cx.read(|cx| {
5043 project
5044 .read(cx)
5045 .worktrees(cx)
5046 .next()
5047 .unwrap()
5048 .read(cx)
5049 .as_local()
5050 .unwrap()
5051 .scan_complete()
5052 })
5053 .await;
5054
5055 cx.executor().run_until_parked();
5056
5057 let panel = workspace.update(cx, GitPanel::new).unwrap();
5058
5059 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5060 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5061 });
5062 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5063 handle.await;
5064
5065 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5066 pretty_assertions::assert_eq!(
5067 entries,
5068 [
5069 GitListEntry::Header(GitHeaderEntry {
5070 header: Section::Tracked
5071 }),
5072 GitListEntry::Status(GitStatusEntry {
5073 repo_path: repo_path("crates/gpui/gpui.rs"),
5074 status: StatusCode::Modified.worktree(),
5075 staging: StageStatus::Unstaged,
5076 }),
5077 GitListEntry::Status(GitStatusEntry {
5078 repo_path: repo_path("crates/util/util.rs"),
5079 status: StatusCode::Modified.worktree(),
5080 staging: StageStatus::Unstaged,
5081 },),
5082 ],
5083 );
5084
5085 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5086 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5087 });
5088 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5089 handle.await;
5090 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5091 pretty_assertions::assert_eq!(
5092 entries,
5093 [
5094 GitListEntry::Header(GitHeaderEntry {
5095 header: Section::Tracked
5096 }),
5097 GitListEntry::Status(GitStatusEntry {
5098 repo_path: repo_path("crates/gpui/gpui.rs"),
5099 status: StatusCode::Modified.worktree(),
5100 staging: StageStatus::Unstaged,
5101 }),
5102 GitListEntry::Status(GitStatusEntry {
5103 repo_path: repo_path("crates/util/util.rs"),
5104 status: StatusCode::Modified.worktree(),
5105 staging: StageStatus::Unstaged,
5106 },),
5107 ],
5108 );
5109 }
5110
5111 #[gpui::test]
5112 async fn test_bulk_staging(cx: &mut TestAppContext) {
5113 use GitListEntry::*;
5114
5115 init_test(cx);
5116 let fs = FakeFs::new(cx.background_executor.clone());
5117 fs.insert_tree(
5118 "/root",
5119 json!({
5120 "project": {
5121 ".git": {},
5122 "src": {
5123 "main.rs": "fn main() {}",
5124 "lib.rs": "pub fn hello() {}",
5125 "utils.rs": "pub fn util() {}"
5126 },
5127 "tests": {
5128 "test.rs": "fn test() {}"
5129 },
5130 "new_file.txt": "new content",
5131 "another_new.rs": "// new file",
5132 "conflict.txt": "conflicted content"
5133 }
5134 }),
5135 )
5136 .await;
5137
5138 fs.set_status_for_repo(
5139 Path::new(path!("/root/project/.git")),
5140 &[
5141 ("src/main.rs", StatusCode::Modified.worktree()),
5142 ("src/lib.rs", StatusCode::Modified.worktree()),
5143 ("tests/test.rs", StatusCode::Modified.worktree()),
5144 ("new_file.txt", FileStatus::Untracked),
5145 ("another_new.rs", FileStatus::Untracked),
5146 ("src/utils.rs", FileStatus::Untracked),
5147 (
5148 "conflict.txt",
5149 UnmergedStatus {
5150 first_head: UnmergedStatusCode::Updated,
5151 second_head: UnmergedStatusCode::Updated,
5152 }
5153 .into(),
5154 ),
5155 ],
5156 );
5157
5158 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5159 let workspace =
5160 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5161 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5162
5163 cx.read(|cx| {
5164 project
5165 .read(cx)
5166 .worktrees(cx)
5167 .next()
5168 .unwrap()
5169 .read(cx)
5170 .as_local()
5171 .unwrap()
5172 .scan_complete()
5173 })
5174 .await;
5175
5176 cx.executor().run_until_parked();
5177
5178 let panel = workspace.update(cx, GitPanel::new).unwrap();
5179
5180 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5181 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5182 });
5183 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5184 handle.await;
5185
5186 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5187 #[rustfmt::skip]
5188 pretty_assertions::assert_matches!(
5189 entries.as_slice(),
5190 &[
5191 Header(GitHeaderEntry { header: Section::Conflict }),
5192 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5193 Header(GitHeaderEntry { header: Section::Tracked }),
5194 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5195 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5196 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5197 Header(GitHeaderEntry { header: Section::New }),
5198 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5199 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5200 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5201 ],
5202 );
5203
5204 let second_status_entry = entries[3].clone();
5205 panel.update_in(cx, |panel, window, cx| {
5206 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5207 });
5208
5209 panel.update_in(cx, |panel, window, cx| {
5210 panel.selected_entry = Some(7);
5211 panel.stage_range(&git::StageRange, window, cx);
5212 });
5213
5214 cx.read(|cx| {
5215 project
5216 .read(cx)
5217 .worktrees(cx)
5218 .next()
5219 .unwrap()
5220 .read(cx)
5221 .as_local()
5222 .unwrap()
5223 .scan_complete()
5224 })
5225 .await;
5226
5227 cx.executor().run_until_parked();
5228
5229 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5230 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5231 });
5232 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5233 handle.await;
5234
5235 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5236 #[rustfmt::skip]
5237 pretty_assertions::assert_matches!(
5238 entries.as_slice(),
5239 &[
5240 Header(GitHeaderEntry { header: Section::Conflict }),
5241 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5242 Header(GitHeaderEntry { header: Section::Tracked }),
5243 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5244 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5245 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5246 Header(GitHeaderEntry { header: Section::New }),
5247 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5248 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5249 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5250 ],
5251 );
5252
5253 let third_status_entry = entries[4].clone();
5254 panel.update_in(cx, |panel, window, cx| {
5255 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5256 });
5257
5258 panel.update_in(cx, |panel, window, cx| {
5259 panel.selected_entry = Some(9);
5260 panel.stage_range(&git::StageRange, window, cx);
5261 });
5262
5263 cx.read(|cx| {
5264 project
5265 .read(cx)
5266 .worktrees(cx)
5267 .next()
5268 .unwrap()
5269 .read(cx)
5270 .as_local()
5271 .unwrap()
5272 .scan_complete()
5273 })
5274 .await;
5275
5276 cx.executor().run_until_parked();
5277
5278 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5279 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5280 });
5281 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5282 handle.await;
5283
5284 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5285 #[rustfmt::skip]
5286 pretty_assertions::assert_matches!(
5287 entries.as_slice(),
5288 &[
5289 Header(GitHeaderEntry { header: Section::Conflict }),
5290 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5291 Header(GitHeaderEntry { header: Section::Tracked }),
5292 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5293 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5294 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5295 Header(GitHeaderEntry { header: Section::New }),
5296 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5297 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5298 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5299 ],
5300 );
5301 }
5302
5303 #[gpui::test]
5304 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
5305 use GitListEntry::*;
5306
5307 init_test(cx);
5308 let fs = FakeFs::new(cx.background_executor.clone());
5309 fs.insert_tree(
5310 "/root",
5311 json!({
5312 "project": {
5313 ".git": {},
5314 "src": {
5315 "main.rs": "fn main() {}",
5316 "lib.rs": "pub fn hello() {}",
5317 "utils.rs": "pub fn util() {}"
5318 },
5319 "tests": {
5320 "test.rs": "fn test() {}"
5321 },
5322 "new_file.txt": "new content",
5323 "another_new.rs": "// new file",
5324 "conflict.txt": "conflicted content"
5325 }
5326 }),
5327 )
5328 .await;
5329
5330 fs.set_status_for_repo(
5331 Path::new(path!("/root/project/.git")),
5332 &[
5333 ("src/main.rs", StatusCode::Modified.worktree()),
5334 ("src/lib.rs", StatusCode::Modified.worktree()),
5335 ("tests/test.rs", StatusCode::Modified.worktree()),
5336 ("new_file.txt", FileStatus::Untracked),
5337 ("another_new.rs", FileStatus::Untracked),
5338 ("src/utils.rs", FileStatus::Untracked),
5339 (
5340 "conflict.txt",
5341 UnmergedStatus {
5342 first_head: UnmergedStatusCode::Updated,
5343 second_head: UnmergedStatusCode::Updated,
5344 }
5345 .into(),
5346 ),
5347 ],
5348 );
5349
5350 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5351 let workspace =
5352 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5353 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5354
5355 cx.read(|cx| {
5356 project
5357 .read(cx)
5358 .worktrees(cx)
5359 .next()
5360 .unwrap()
5361 .read(cx)
5362 .as_local()
5363 .unwrap()
5364 .scan_complete()
5365 })
5366 .await;
5367
5368 cx.executor().run_until_parked();
5369
5370 let panel = workspace.update(cx, GitPanel::new).unwrap();
5371
5372 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5373 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5374 });
5375 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5376 handle.await;
5377
5378 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5379 #[rustfmt::skip]
5380 pretty_assertions::assert_matches!(
5381 entries.as_slice(),
5382 &[
5383 Header(GitHeaderEntry { header: Section::Conflict }),
5384 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5385 Header(GitHeaderEntry { header: Section::Tracked }),
5386 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5387 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5388 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5389 Header(GitHeaderEntry { header: Section::New }),
5390 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5391 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5392 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5393 ],
5394 );
5395
5396 assert_entry_paths(
5397 &entries,
5398 &[
5399 None,
5400 Some("conflict.txt"),
5401 None,
5402 Some("src/lib.rs"),
5403 Some("src/main.rs"),
5404 Some("tests/test.rs"),
5405 None,
5406 Some("another_new.rs"),
5407 Some("new_file.txt"),
5408 Some("src/utils.rs"),
5409 ],
5410 );
5411
5412 let second_status_entry = entries[3].clone();
5413 panel.update_in(cx, |panel, window, cx| {
5414 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5415 });
5416
5417 cx.update(|_window, cx| {
5418 SettingsStore::update_global(cx, |store, cx| {
5419 store.update_user_settings(cx, |settings| {
5420 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5421 })
5422 });
5423 });
5424
5425 panel.update_in(cx, |panel, window, cx| {
5426 panel.selected_entry = Some(7);
5427 panel.stage_range(&git::StageRange, window, cx);
5428 });
5429
5430 cx.read(|cx| {
5431 project
5432 .read(cx)
5433 .worktrees(cx)
5434 .next()
5435 .unwrap()
5436 .read(cx)
5437 .as_local()
5438 .unwrap()
5439 .scan_complete()
5440 })
5441 .await;
5442
5443 cx.executor().run_until_parked();
5444
5445 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5446 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5447 });
5448 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5449 handle.await;
5450
5451 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5452 #[rustfmt::skip]
5453 pretty_assertions::assert_matches!(
5454 entries.as_slice(),
5455 &[
5456 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5457 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5458 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5459 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5460 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5461 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5462 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5463 ],
5464 );
5465
5466 assert_entry_paths(
5467 &entries,
5468 &[
5469 Some("another_new.rs"),
5470 Some("conflict.txt"),
5471 Some("new_file.txt"),
5472 Some("src/lib.rs"),
5473 Some("src/main.rs"),
5474 Some("src/utils.rs"),
5475 Some("tests/test.rs"),
5476 ],
5477 );
5478
5479 let third_status_entry = entries[4].clone();
5480 panel.update_in(cx, |panel, window, cx| {
5481 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5482 });
5483
5484 panel.update_in(cx, |panel, window, cx| {
5485 panel.selected_entry = Some(9);
5486 panel.stage_range(&git::StageRange, window, cx);
5487 });
5488
5489 cx.read(|cx| {
5490 project
5491 .read(cx)
5492 .worktrees(cx)
5493 .next()
5494 .unwrap()
5495 .read(cx)
5496 .as_local()
5497 .unwrap()
5498 .scan_complete()
5499 })
5500 .await;
5501
5502 cx.executor().run_until_parked();
5503
5504 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5505 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5506 });
5507 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5508 handle.await;
5509
5510 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5511 #[rustfmt::skip]
5512 pretty_assertions::assert_matches!(
5513 entries.as_slice(),
5514 &[
5515 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5516 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5517 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5518 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5519 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5520 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5521 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5522 ],
5523 );
5524
5525 assert_entry_paths(
5526 &entries,
5527 &[
5528 Some("another_new.rs"),
5529 Some("conflict.txt"),
5530 Some("new_file.txt"),
5531 Some("src/lib.rs"),
5532 Some("src/main.rs"),
5533 Some("src/utils.rs"),
5534 Some("tests/test.rs"),
5535 ],
5536 );
5537 }
5538
5539 #[gpui::test]
5540 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5541 init_test(cx);
5542 let fs = FakeFs::new(cx.background_executor.clone());
5543 fs.insert_tree(
5544 "/root",
5545 json!({
5546 "project": {
5547 ".git": {},
5548 "src": {
5549 "main.rs": "fn main() {}"
5550 }
5551 }
5552 }),
5553 )
5554 .await;
5555
5556 fs.set_status_for_repo(
5557 Path::new(path!("/root/project/.git")),
5558 &[("src/main.rs", StatusCode::Modified.worktree())],
5559 );
5560
5561 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5562 let workspace =
5563 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5564 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5565
5566 let panel = workspace.update(cx, GitPanel::new).unwrap();
5567
5568 // Test: User has commit message, enables amend (saves message), then disables (restores message)
5569 panel.update(cx, |panel, cx| {
5570 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5571 let start = buffer.anchor_before(0);
5572 let end = buffer.anchor_after(buffer.len());
5573 buffer.edit([(start..end, "Initial commit message")], None, cx);
5574 });
5575
5576 panel.set_amend_pending(true, cx);
5577 assert!(panel.original_commit_message.is_some());
5578
5579 panel.set_amend_pending(false, cx);
5580 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5581 assert_eq!(current_message, "Initial commit message");
5582 assert!(panel.original_commit_message.is_none());
5583 });
5584
5585 // Test: User has empty commit message, enables amend, then disables (clears message)
5586 panel.update(cx, |panel, cx| {
5587 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5588 let start = buffer.anchor_before(0);
5589 let end = buffer.anchor_after(buffer.len());
5590 buffer.edit([(start..end, "")], None, cx);
5591 });
5592
5593 panel.set_amend_pending(true, cx);
5594 assert!(panel.original_commit_message.is_none());
5595
5596 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5597 let start = buffer.anchor_before(0);
5598 let end = buffer.anchor_after(buffer.len());
5599 buffer.edit([(start..end, "Previous commit message")], None, cx);
5600 });
5601
5602 panel.set_amend_pending(false, cx);
5603 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5604 assert_eq!(current_message, "");
5605 });
5606 }
5607
5608 #[gpui::test]
5609 async fn test_open_diff(cx: &mut TestAppContext) {
5610 init_test(cx);
5611
5612 let fs = FakeFs::new(cx.background_executor.clone());
5613 fs.insert_tree(
5614 path!("/project"),
5615 json!({
5616 ".git": {},
5617 "tracked": "tracked\n",
5618 "untracked": "\n",
5619 }),
5620 )
5621 .await;
5622
5623 fs.set_head_and_index_for_repo(
5624 path!("/project/.git").as_ref(),
5625 &[("tracked", "old tracked\n".into())],
5626 );
5627
5628 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
5629 let workspace =
5630 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5631 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5632 let panel = workspace.update(cx, GitPanel::new).unwrap();
5633
5634 // Enable the `sort_by_path` setting and wait for entries to be updated,
5635 // as there should no longer be separators between Tracked and Untracked
5636 // files.
5637 cx.update(|_window, cx| {
5638 SettingsStore::update_global(cx, |store, cx| {
5639 store.update_user_settings(cx, |settings| {
5640 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5641 })
5642 });
5643 });
5644
5645 cx.update_window_entity(&panel, |panel, _, _| {
5646 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5647 })
5648 .await;
5649
5650 // Confirm that `Open Diff` still works for the untracked file, updating
5651 // the Project Diff's active path.
5652 panel.update_in(cx, |panel, window, cx| {
5653 panel.selected_entry = Some(1);
5654 panel.open_diff(&Confirm, window, cx);
5655 });
5656 cx.run_until_parked();
5657
5658 let _ = workspace.update(cx, |workspace, _window, cx| {
5659 let active_path = workspace
5660 .item_of_type::<ProjectDiff>(cx)
5661 .expect("ProjectDiff should exist")
5662 .read(cx)
5663 .active_path(cx)
5664 .expect("active_path should exist");
5665
5666 assert_eq!(active_path.path, rel_path("untracked").into_arc());
5667 });
5668 }
5669
5670 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
5671 assert_eq!(entries.len(), expected_paths.len());
5672 for (entry, expected_path) in entries.iter().zip(expected_paths) {
5673 assert_eq!(
5674 entry.status_entry().map(|status| status
5675 .repo_path
5676 .0
5677 .as_std_path()
5678 .to_string_lossy()
5679 .to_string()),
5680 expected_path.map(|s| s.to_string())
5681 );
5682 }
5683 }
5684}