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