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