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