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