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 prompt: Some("Select as Repository Destination".into()),
2092 });
2093
2094 let workspace = self.workspace.clone();
2095
2096 cx.spawn_in(window, async move |this, cx| {
2097 let mut paths = path.await.ok()?.ok()??;
2098 let mut path = paths.pop()?;
2099 let repo_name = repo
2100 .split(std::path::MAIN_SEPARATOR_STR)
2101 .last()?
2102 .strip_suffix(".git")?
2103 .to_owned();
2104
2105 let fs = this.read_with(cx, |this, _| this.fs.clone()).ok()?;
2106
2107 let prompt_answer = match fs.git_clone(&repo, path.as_path()).await {
2108 Ok(_) => cx.update(|window, cx| {
2109 window.prompt(
2110 PromptLevel::Info,
2111 &format!("Git Clone: {}", repo_name),
2112 None,
2113 &["Add repo to project", "Open repo in new project"],
2114 cx,
2115 )
2116 }),
2117 Err(e) => {
2118 this.update(cx, |this: &mut GitPanel, cx| {
2119 let toast = StatusToast::new(e.to_string(), cx, |this, _| {
2120 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2121 .dismiss_button(true)
2122 });
2123
2124 this.workspace
2125 .update(cx, |workspace, cx| {
2126 workspace.toggle_status_toast(toast, cx);
2127 })
2128 .ok();
2129 })
2130 .ok()?;
2131
2132 return None;
2133 }
2134 }
2135 .ok()?;
2136
2137 path.push(repo_name);
2138 match prompt_answer.await.ok()? {
2139 0 => {
2140 workspace
2141 .update(cx, |workspace, cx| {
2142 workspace
2143 .project()
2144 .update(cx, |project, cx| {
2145 project.create_worktree(path.as_path(), true, cx)
2146 })
2147 .detach();
2148 })
2149 .ok();
2150 }
2151 1 => {
2152 workspace
2153 .update(cx, move |workspace, cx| {
2154 workspace::open_new(
2155 Default::default(),
2156 workspace.app_state().clone(),
2157 cx,
2158 move |workspace, _, cx| {
2159 cx.activate(true);
2160 workspace
2161 .project()
2162 .update(cx, |project, cx| {
2163 project.create_worktree(&path, true, cx)
2164 })
2165 .detach();
2166 },
2167 )
2168 .detach();
2169 })
2170 .ok();
2171 }
2172 _ => {}
2173 }
2174
2175 Some(())
2176 })
2177 .detach();
2178 }
2179
2180 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2181 let worktrees = self
2182 .project
2183 .read(cx)
2184 .visible_worktrees(cx)
2185 .collect::<Vec<_>>();
2186
2187 let worktree = if worktrees.len() == 1 {
2188 Task::ready(Some(worktrees.first().unwrap().clone()))
2189 } else if worktrees.len() == 0 {
2190 let result = window.prompt(
2191 PromptLevel::Warning,
2192 "Unable to initialize a git repository",
2193 Some("Open a directory first"),
2194 &["Ok"],
2195 cx,
2196 );
2197 cx.background_executor()
2198 .spawn(async move {
2199 result.await.ok();
2200 })
2201 .detach();
2202 return;
2203 } else {
2204 let worktree_directories = worktrees
2205 .iter()
2206 .map(|worktree| worktree.read(cx).abs_path())
2207 .map(|worktree_abs_path| {
2208 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2209 Path::new("~")
2210 .join(path)
2211 .to_string_lossy()
2212 .to_string()
2213 .into()
2214 } else {
2215 worktree_abs_path.to_string_lossy().to_string().into()
2216 }
2217 })
2218 .collect_vec();
2219 let prompt = picker_prompt::prompt(
2220 "Where would you like to initialize this git repository?",
2221 worktree_directories,
2222 self.workspace.clone(),
2223 window,
2224 cx,
2225 );
2226
2227 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2228 };
2229
2230 cx.spawn_in(window, async move |this, cx| {
2231 let worktree = match worktree.await {
2232 Some(worktree) => worktree,
2233 None => {
2234 return;
2235 }
2236 };
2237
2238 let Ok(result) = this.update(cx, |this, cx| {
2239 let fallback_branch_name = GitPanelSettings::get_global(cx)
2240 .fallback_branch_name
2241 .clone();
2242 this.project.read(cx).git_init(
2243 worktree.read(cx).abs_path(),
2244 fallback_branch_name,
2245 cx,
2246 )
2247 }) else {
2248 return;
2249 };
2250
2251 let result = result.await;
2252
2253 this.update_in(cx, |this, _, cx| match result {
2254 Ok(()) => {}
2255 Err(e) => this.show_error_toast("init", e, cx),
2256 })
2257 .ok();
2258 })
2259 .detach();
2260 }
2261
2262 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2263 if !self.can_push_and_pull(cx) {
2264 return;
2265 }
2266 let Some(repo) = self.active_repository.clone() else {
2267 return;
2268 };
2269 let Some(branch) = repo.read(cx).branch.as_ref() else {
2270 return;
2271 };
2272 telemetry::event!("Git Pulled");
2273 let branch = branch.clone();
2274 let remote = self.get_remote(false, window, cx);
2275 cx.spawn_in(window, async move |this, cx| {
2276 let remote = match remote.await {
2277 Ok(Some(remote)) => remote,
2278 Ok(None) => {
2279 return Ok(());
2280 }
2281 Err(e) => {
2282 log::error!("Failed to get current remote: {}", e);
2283 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2284 .ok();
2285 return Ok(());
2286 }
2287 };
2288
2289 let askpass = this.update_in(cx, |this, window, cx| {
2290 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2291 })?;
2292
2293 let pull = repo.update(cx, |repo, cx| {
2294 repo.pull(
2295 branch.name().to_owned().into(),
2296 remote.name.clone(),
2297 askpass,
2298 cx,
2299 )
2300 })?;
2301
2302 let remote_message = pull.await?;
2303
2304 let action = RemoteAction::Pull(remote);
2305 this.update(cx, |this, cx| match remote_message {
2306 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2307 Err(e) => {
2308 log::error!("Error while pulling {:?}", e);
2309 this.show_error_toast(action.name(), e, cx)
2310 }
2311 })
2312 .ok();
2313
2314 anyhow::Ok(())
2315 })
2316 .detach_and_log_err(cx);
2317 }
2318
2319 pub(crate) fn push(
2320 &mut self,
2321 force_push: bool,
2322 select_remote: bool,
2323 window: &mut Window,
2324 cx: &mut Context<Self>,
2325 ) {
2326 if !self.can_push_and_pull(cx) {
2327 return;
2328 }
2329 let Some(repo) = self.active_repository.clone() else {
2330 return;
2331 };
2332 let Some(branch) = repo.read(cx).branch.as_ref() else {
2333 return;
2334 };
2335 telemetry::event!("Git Pushed");
2336 let branch = branch.clone();
2337
2338 let options = if force_push {
2339 Some(PushOptions::Force)
2340 } else {
2341 match branch.upstream {
2342 Some(Upstream {
2343 tracking: UpstreamTracking::Gone,
2344 ..
2345 })
2346 | None => Some(PushOptions::SetUpstream),
2347 _ => None,
2348 }
2349 };
2350 let remote = self.get_remote(select_remote, window, cx);
2351
2352 cx.spawn_in(window, async move |this, cx| {
2353 let remote = match remote.await {
2354 Ok(Some(remote)) => remote,
2355 Ok(None) => {
2356 return Ok(());
2357 }
2358 Err(e) => {
2359 log::error!("Failed to get current remote: {}", e);
2360 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2361 .ok();
2362 return Ok(());
2363 }
2364 };
2365
2366 let askpass_delegate = this.update_in(cx, |this, window, cx| {
2367 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2368 })?;
2369
2370 let push = repo.update(cx, |repo, cx| {
2371 repo.push(
2372 branch.name().to_owned().into(),
2373 remote.name.clone(),
2374 options,
2375 askpass_delegate,
2376 cx,
2377 )
2378 })?;
2379
2380 let remote_output = push.await?;
2381
2382 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2383 this.update(cx, |this, cx| match remote_output {
2384 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2385 Err(e) => {
2386 log::error!("Error while pushing {:?}", e);
2387 this.show_error_toast(action.name(), e, cx)
2388 }
2389 })?;
2390
2391 anyhow::Ok(())
2392 })
2393 .detach_and_log_err(cx);
2394 }
2395
2396 fn askpass_delegate(
2397 &self,
2398 operation: impl Into<SharedString>,
2399 window: &mut Window,
2400 cx: &mut Context<Self>,
2401 ) -> AskPassDelegate {
2402 let this = cx.weak_entity();
2403 let operation = operation.into();
2404 let window = window.window_handle();
2405 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2406 window
2407 .update(cx, |_, window, cx| {
2408 this.update(cx, |this, cx| {
2409 this.workspace.update(cx, |workspace, cx| {
2410 workspace.toggle_modal(window, cx, |window, cx| {
2411 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2412 });
2413 })
2414 })
2415 })
2416 .ok();
2417 })
2418 }
2419
2420 fn can_push_and_pull(&self, cx: &App) -> bool {
2421 !self.project.read(cx).is_via_collab()
2422 }
2423
2424 fn get_remote(
2425 &mut self,
2426 always_select: bool,
2427 window: &mut Window,
2428 cx: &mut Context<Self>,
2429 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2430 let repo = self.active_repository.clone();
2431 let workspace = self.workspace.clone();
2432 let mut cx = window.to_async(cx);
2433
2434 async move {
2435 let repo = repo.context("No active repository")?;
2436 let current_remotes: Vec<Remote> = repo
2437 .update(&mut cx, |repo, _| {
2438 let current_branch = if always_select {
2439 None
2440 } else {
2441 let current_branch = repo.branch.as_ref().context("No active branch")?;
2442 Some(current_branch.name().to_string())
2443 };
2444 anyhow::Ok(repo.get_remotes(current_branch))
2445 })??
2446 .await??;
2447
2448 let current_remotes: Vec<_> = current_remotes
2449 .into_iter()
2450 .map(|remotes| remotes.name)
2451 .collect();
2452 let selection = cx
2453 .update(|window, cx| {
2454 picker_prompt::prompt(
2455 "Pick which remote to push to",
2456 current_remotes.clone(),
2457 workspace,
2458 window,
2459 cx,
2460 )
2461 })?
2462 .await;
2463
2464 Ok(selection.map(|selection| Remote {
2465 name: current_remotes[selection].clone(),
2466 }))
2467 }
2468 }
2469
2470 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2471 if self.local_committer_task.is_none() {
2472 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2473 let committer = get_git_committer(cx).await;
2474 this.update(cx, |this, cx| {
2475 this.local_committer = Some(committer);
2476 cx.notify()
2477 })
2478 .ok();
2479 }));
2480 }
2481 }
2482
2483 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2484 let mut new_co_authors = Vec::new();
2485 let project = self.project.read(cx);
2486
2487 let Some(room) = self
2488 .workspace
2489 .upgrade()
2490 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2491 else {
2492 return Vec::default();
2493 };
2494
2495 let room = room.read(cx);
2496
2497 for (peer_id, collaborator) in project.collaborators() {
2498 if collaborator.is_host {
2499 continue;
2500 }
2501
2502 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2503 continue;
2504 };
2505 if !participant.can_write() {
2506 continue;
2507 }
2508 if let Some(email) = &collaborator.committer_email {
2509 let name = collaborator
2510 .committer_name
2511 .clone()
2512 .or_else(|| participant.user.name.clone())
2513 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2514 new_co_authors.push((name.clone(), email.clone()))
2515 }
2516 }
2517 if !project.is_local() && !project.is_read_only(cx) {
2518 if let Some(local_committer) = self.local_committer(room, cx) {
2519 new_co_authors.push(local_committer);
2520 }
2521 }
2522 new_co_authors
2523 }
2524
2525 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2526 let user = room.local_participant_user(cx)?;
2527 let committer = self.local_committer.as_ref()?;
2528 let email = committer.email.clone()?;
2529 let name = committer
2530 .name
2531 .clone()
2532 .or_else(|| user.name.clone())
2533 .unwrap_or_else(|| user.github_login.clone().to_string());
2534 Some((name, email))
2535 }
2536
2537 fn toggle_fill_co_authors(
2538 &mut self,
2539 _: &ToggleFillCoAuthors,
2540 _: &mut Window,
2541 cx: &mut Context<Self>,
2542 ) {
2543 self.add_coauthors = !self.add_coauthors;
2544 cx.notify();
2545 }
2546
2547 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2548 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2549
2550 let existing_text = message.to_ascii_lowercase();
2551 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2552 let mut ends_with_co_authors = false;
2553 let existing_co_authors = existing_text
2554 .lines()
2555 .filter_map(|line| {
2556 let line = line.trim();
2557 if line.starts_with(&lowercase_co_author_prefix) {
2558 ends_with_co_authors = true;
2559 Some(line)
2560 } else {
2561 ends_with_co_authors = false;
2562 None
2563 }
2564 })
2565 .collect::<HashSet<_>>();
2566
2567 let new_co_authors = self
2568 .potential_co_authors(cx)
2569 .into_iter()
2570 .filter(|(_, email)| {
2571 !existing_co_authors
2572 .iter()
2573 .any(|existing| existing.contains(email.as_str()))
2574 })
2575 .collect::<Vec<_>>();
2576
2577 if new_co_authors.is_empty() {
2578 return;
2579 }
2580
2581 if !ends_with_co_authors {
2582 message.push('\n');
2583 }
2584 for (name, email) in new_co_authors {
2585 message.push('\n');
2586 message.push_str(CO_AUTHOR_PREFIX);
2587 message.push_str(&name);
2588 message.push_str(" <");
2589 message.push_str(&email);
2590 message.push('>');
2591 }
2592 message.push('\n');
2593 }
2594
2595 fn schedule_update(
2596 &mut self,
2597 clear_pending: bool,
2598 window: &mut Window,
2599 cx: &mut Context<Self>,
2600 ) {
2601 let handle = cx.entity().downgrade();
2602 self.reopen_commit_buffer(window, cx);
2603 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2604 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2605 if let Some(git_panel) = handle.upgrade() {
2606 git_panel
2607 .update_in(cx, |git_panel, window, cx| {
2608 if clear_pending {
2609 git_panel.clear_pending();
2610 }
2611 git_panel.update_visible_entries(cx);
2612 git_panel.update_scrollbar_properties(window, cx);
2613 })
2614 .ok();
2615 }
2616 });
2617 }
2618
2619 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2620 let Some(active_repo) = self.active_repository.as_ref() else {
2621 return;
2622 };
2623 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2624 let project = self.project.read(cx);
2625 active_repo.open_commit_buffer(
2626 Some(project.languages().clone()),
2627 project.buffer_store().clone(),
2628 cx,
2629 )
2630 });
2631
2632 cx.spawn_in(window, async move |git_panel, cx| {
2633 let buffer = load_buffer.await?;
2634 git_panel.update_in(cx, |git_panel, window, cx| {
2635 if git_panel
2636 .commit_editor
2637 .read(cx)
2638 .buffer()
2639 .read(cx)
2640 .as_singleton()
2641 .as_ref()
2642 != Some(&buffer)
2643 {
2644 git_panel.commit_editor = cx.new(|cx| {
2645 commit_message_editor(
2646 buffer,
2647 git_panel.suggest_commit_message(cx).map(SharedString::from),
2648 git_panel.project.clone(),
2649 true,
2650 window,
2651 cx,
2652 )
2653 });
2654 }
2655 })
2656 })
2657 .detach_and_log_err(cx);
2658 }
2659
2660 fn clear_pending(&mut self) {
2661 self.pending.retain(|v| !v.finished)
2662 }
2663
2664 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2665 let bulk_staging = self.bulk_staging.take();
2666 let last_staged_path_prev_index = bulk_staging
2667 .as_ref()
2668 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2669
2670 self.entries.clear();
2671 self.single_staged_entry.take();
2672 self.single_tracked_entry.take();
2673 self.conflicted_count = 0;
2674 self.conflicted_staged_count = 0;
2675 self.new_count = 0;
2676 self.tracked_count = 0;
2677 self.new_staged_count = 0;
2678 self.tracked_staged_count = 0;
2679 self.entry_count = 0;
2680
2681 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2682
2683 let mut changed_entries = Vec::new();
2684 let mut new_entries = Vec::new();
2685 let mut conflict_entries = Vec::new();
2686 let mut single_staged_entry = None;
2687 let mut staged_count = 0;
2688 let mut max_width_item: Option<(RepoPath, usize)> = None;
2689
2690 let Some(repo) = self.active_repository.as_ref() else {
2691 // Just clear entries if no repository is active.
2692 cx.notify();
2693 return;
2694 };
2695
2696 let repo = repo.read(cx);
2697
2698 for entry in repo.cached_status() {
2699 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2700 let is_new = entry.status.is_created();
2701 let staging = entry.status.staging();
2702
2703 if self.pending.iter().any(|pending| {
2704 pending.target_status == TargetStatus::Reverted
2705 && !pending.finished
2706 && pending
2707 .entries
2708 .iter()
2709 .any(|pending| pending.repo_path == entry.repo_path)
2710 }) {
2711 continue;
2712 }
2713
2714 let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2715 let entry = GitStatusEntry {
2716 repo_path: entry.repo_path.clone(),
2717 abs_path,
2718 status: entry.status,
2719 staging,
2720 };
2721
2722 if staging.has_staged() {
2723 staged_count += 1;
2724 single_staged_entry = Some(entry.clone());
2725 }
2726
2727 let width_estimate = Self::item_width_estimate(
2728 entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2729 entry.display_name().len(),
2730 );
2731
2732 match max_width_item.as_mut() {
2733 Some((repo_path, estimate)) => {
2734 if width_estimate > *estimate {
2735 *repo_path = entry.repo_path.clone();
2736 *estimate = width_estimate;
2737 }
2738 }
2739 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2740 }
2741
2742 if sort_by_path {
2743 changed_entries.push(entry);
2744 } else if is_conflict {
2745 conflict_entries.push(entry);
2746 } else if is_new {
2747 new_entries.push(entry);
2748 } else {
2749 changed_entries.push(entry);
2750 }
2751 }
2752
2753 let mut pending_staged_count = 0;
2754 let mut last_pending_staged = None;
2755 let mut pending_status_for_single_staged = None;
2756 for pending in self.pending.iter() {
2757 if pending.target_status == TargetStatus::Staged {
2758 pending_staged_count += pending.entries.len();
2759 last_pending_staged = pending.entries.iter().next().cloned();
2760 }
2761 if let Some(single_staged) = &single_staged_entry {
2762 if pending
2763 .entries
2764 .iter()
2765 .any(|entry| entry.repo_path == single_staged.repo_path)
2766 {
2767 pending_status_for_single_staged = Some(pending.target_status);
2768 }
2769 }
2770 }
2771
2772 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2773 match pending_status_for_single_staged {
2774 Some(TargetStatus::Staged) | None => {
2775 self.single_staged_entry = single_staged_entry;
2776 }
2777 _ => {}
2778 }
2779 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2780 self.single_staged_entry = last_pending_staged;
2781 }
2782
2783 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2784 self.single_tracked_entry = changed_entries.first().cloned();
2785 }
2786
2787 if conflict_entries.len() > 0 {
2788 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2789 header: Section::Conflict,
2790 }));
2791 self.entries
2792 .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2793 }
2794
2795 if changed_entries.len() > 0 {
2796 if !sort_by_path {
2797 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2798 header: Section::Tracked,
2799 }));
2800 }
2801 self.entries
2802 .extend(changed_entries.into_iter().map(GitListEntry::Status));
2803 }
2804 if new_entries.len() > 0 {
2805 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2806 header: Section::New,
2807 }));
2808 self.entries
2809 .extend(new_entries.into_iter().map(GitListEntry::Status));
2810 }
2811
2812 if let Some((repo_path, _)) = max_width_item {
2813 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2814 GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2815 GitListEntry::Header(_) => false,
2816 });
2817 }
2818
2819 self.update_counts(repo);
2820
2821 let bulk_staging_anchor_new_index = bulk_staging
2822 .as_ref()
2823 .filter(|op| op.repo_id == repo.id)
2824 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2825 if bulk_staging_anchor_new_index == last_staged_path_prev_index
2826 && let Some(index) = bulk_staging_anchor_new_index
2827 && let Some(entry) = self.entries.get(index)
2828 && let Some(entry) = entry.status_entry()
2829 && self.entry_staging(entry) == StageStatus::Staged
2830 {
2831 self.bulk_staging = bulk_staging;
2832 }
2833
2834 self.select_first_entry_if_none(cx);
2835
2836 let suggested_commit_message = self.suggest_commit_message(cx);
2837 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2838
2839 self.commit_editor.update(cx, |editor, cx| {
2840 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2841 });
2842
2843 cx.notify();
2844 }
2845
2846 fn header_state(&self, header_type: Section) -> ToggleState {
2847 let (staged_count, count) = match header_type {
2848 Section::New => (self.new_staged_count, self.new_count),
2849 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2850 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2851 };
2852 if staged_count == 0 {
2853 ToggleState::Unselected
2854 } else if count == staged_count {
2855 ToggleState::Selected
2856 } else {
2857 ToggleState::Indeterminate
2858 }
2859 }
2860
2861 fn update_counts(&mut self, repo: &Repository) {
2862 self.show_placeholders = false;
2863 self.conflicted_count = 0;
2864 self.conflicted_staged_count = 0;
2865 self.new_count = 0;
2866 self.tracked_count = 0;
2867 self.new_staged_count = 0;
2868 self.tracked_staged_count = 0;
2869 self.entry_count = 0;
2870 for entry in &self.entries {
2871 let Some(status_entry) = entry.status_entry() else {
2872 continue;
2873 };
2874 self.entry_count += 1;
2875 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2876 self.conflicted_count += 1;
2877 if self.entry_staging(status_entry).has_staged() {
2878 self.conflicted_staged_count += 1;
2879 }
2880 } else if status_entry.status.is_created() {
2881 self.new_count += 1;
2882 if self.entry_staging(status_entry).has_staged() {
2883 self.new_staged_count += 1;
2884 }
2885 } else {
2886 self.tracked_count += 1;
2887 if self.entry_staging(status_entry).has_staged() {
2888 self.tracked_staged_count += 1;
2889 }
2890 }
2891 }
2892 }
2893
2894 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2895 for pending in self.pending.iter().rev() {
2896 if pending
2897 .entries
2898 .iter()
2899 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2900 {
2901 match pending.target_status {
2902 TargetStatus::Staged => return StageStatus::Staged,
2903 TargetStatus::Unstaged => return StageStatus::Unstaged,
2904 TargetStatus::Reverted => continue,
2905 TargetStatus::Unchanged => continue,
2906 }
2907 }
2908 }
2909 entry.staging
2910 }
2911
2912 pub(crate) fn has_staged_changes(&self) -> bool {
2913 self.tracked_staged_count > 0
2914 || self.new_staged_count > 0
2915 || self.conflicted_staged_count > 0
2916 }
2917
2918 pub(crate) fn has_unstaged_changes(&self) -> bool {
2919 self.tracked_count > self.tracked_staged_count
2920 || self.new_count > self.new_staged_count
2921 || self.conflicted_count > self.conflicted_staged_count
2922 }
2923
2924 fn has_tracked_changes(&self) -> bool {
2925 self.tracked_count > 0
2926 }
2927
2928 pub fn has_unstaged_conflicts(&self) -> bool {
2929 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2930 }
2931
2932 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2933 let action = action.into();
2934 let Some(workspace) = self.workspace.upgrade() else {
2935 return;
2936 };
2937
2938 let message = e.to_string().trim().to_string();
2939 if message
2940 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2941 .next()
2942 .is_some()
2943 {
2944 return; // Hide the cancelled by user message
2945 } else {
2946 workspace.update(cx, |workspace, cx| {
2947 let workspace_weak = cx.weak_entity();
2948 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2949 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2950 .action("View Log", move |window, cx| {
2951 let message = message.clone();
2952 let action = action.clone();
2953 workspace_weak
2954 .update(cx, move |workspace, cx| {
2955 Self::open_output(action, workspace, &message, window, cx)
2956 })
2957 .ok();
2958 })
2959 });
2960 workspace.toggle_status_toast(toast, cx)
2961 });
2962 }
2963 }
2964
2965 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2966 where
2967 E: std::fmt::Debug + std::fmt::Display,
2968 {
2969 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2970 let _ = workspace.update(cx, |workspace, cx| {
2971 struct CommitMessageError;
2972 let notification_id = NotificationId::unique::<CommitMessageError>();
2973 workspace.show_notification(notification_id, cx, |cx| {
2974 cx.new(|cx| {
2975 ErrorMessagePrompt::new(
2976 format!("Failed to generate commit message: {err}"),
2977 cx,
2978 )
2979 })
2980 });
2981 });
2982 }
2983 }
2984
2985 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2986 let Some(workspace) = self.workspace.upgrade() else {
2987 return;
2988 };
2989
2990 workspace.update(cx, |workspace, cx| {
2991 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2992 let workspace_weak = cx.weak_entity();
2993 let operation = action.name();
2994
2995 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2996 use remote_output::SuccessStyle::*;
2997 match style {
2998 Toast { .. } => {
2999 this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3000 }
3001 ToastWithLog { output } => this
3002 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3003 .action("View Log", move |window, cx| {
3004 let output = output.clone();
3005 let output =
3006 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3007 workspace_weak
3008 .update(cx, move |workspace, cx| {
3009 Self::open_output(operation, workspace, &output, window, cx)
3010 })
3011 .ok();
3012 }),
3013 PushPrLink { text, link } => this
3014 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3015 .action(text, move |_, cx| cx.open_url(&link)),
3016 }
3017 });
3018 workspace.toggle_status_toast(status_toast, cx)
3019 });
3020 }
3021
3022 fn open_output(
3023 operation: impl Into<SharedString>,
3024 workspace: &mut Workspace,
3025 output: &str,
3026 window: &mut Window,
3027 cx: &mut Context<Workspace>,
3028 ) {
3029 let operation = operation.into();
3030 let buffer = cx.new(|cx| Buffer::local(output, cx));
3031 buffer.update(cx, |buffer, cx| {
3032 buffer.set_capability(language::Capability::ReadOnly, cx);
3033 });
3034 let editor = cx.new(|cx| {
3035 let mut editor = Editor::for_buffer(buffer, None, window, cx);
3036 editor.buffer().update(cx, |buffer, cx| {
3037 buffer.set_title(format!("Output from git {operation}"), cx);
3038 });
3039 editor.set_read_only(true);
3040 editor
3041 });
3042
3043 workspace.add_item_to_center(Box::new(editor), window, cx);
3044 }
3045
3046 pub fn can_commit(&self) -> bool {
3047 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3048 }
3049
3050 pub fn can_stage_all(&self) -> bool {
3051 self.has_unstaged_changes()
3052 }
3053
3054 pub fn can_unstage_all(&self) -> bool {
3055 self.has_staged_changes()
3056 }
3057
3058 // eventually we'll need to take depth into account here
3059 // if we add a tree view
3060 fn item_width_estimate(path: usize, file_name: usize) -> usize {
3061 path + file_name
3062 }
3063
3064 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3065 let focus_handle = self.focus_handle.clone();
3066 let has_tracked_changes = self.has_tracked_changes();
3067 let has_staged_changes = self.has_staged_changes();
3068 let has_unstaged_changes = self.has_unstaged_changes();
3069 let has_new_changes = self.new_count > 0;
3070
3071 PopoverMenu::new(id.into())
3072 .trigger(
3073 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3074 .icon_size(IconSize::Small)
3075 .icon_color(Color::Muted),
3076 )
3077 .menu(move |window, cx| {
3078 Some(git_panel_context_menu(
3079 focus_handle.clone(),
3080 GitMenuState {
3081 has_tracked_changes,
3082 has_staged_changes,
3083 has_unstaged_changes,
3084 has_new_changes,
3085 },
3086 window,
3087 cx,
3088 ))
3089 })
3090 .anchor(Corner::TopRight)
3091 }
3092
3093 pub(crate) fn render_generate_commit_message_button(
3094 &self,
3095 cx: &Context<Self>,
3096 ) -> Option<AnyElement> {
3097 current_language_model(cx).is_some().then(|| {
3098 if self.generate_commit_message_task.is_some() {
3099 return h_flex()
3100 .gap_1()
3101 .child(
3102 Icon::new(IconName::ArrowCircle)
3103 .size(IconSize::XSmall)
3104 .color(Color::Info)
3105 .with_animation(
3106 "arrow-circle",
3107 Animation::new(Duration::from_secs(2)).repeat(),
3108 |icon, delta| {
3109 icon.transform(Transformation::rotate(percentage(delta)))
3110 },
3111 ),
3112 )
3113 .child(
3114 Label::new("Generating Commit...")
3115 .size(LabelSize::Small)
3116 .color(Color::Muted),
3117 )
3118 .into_any_element();
3119 }
3120
3121 let can_commit = self.can_commit();
3122 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3123 IconButton::new("generate-commit-message", IconName::AiEdit)
3124 .shape(ui::IconButtonShape::Square)
3125 .icon_color(Color::Muted)
3126 .tooltip(move |window, cx| {
3127 if can_commit {
3128 Tooltip::for_action_in(
3129 "Generate Commit Message",
3130 &git::GenerateCommitMessage,
3131 &editor_focus_handle,
3132 window,
3133 cx,
3134 )
3135 } else {
3136 Tooltip::simple("No changes to commit", cx)
3137 }
3138 })
3139 .disabled(!can_commit)
3140 .on_click(cx.listener(move |this, _event, _window, cx| {
3141 this.generate_commit_message(cx);
3142 }))
3143 .into_any_element()
3144 })
3145 }
3146
3147 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3148 let potential_co_authors = self.potential_co_authors(cx);
3149
3150 let (tooltip_label, icon) = if self.add_coauthors {
3151 ("Remove co-authored-by", IconName::Person)
3152 } else {
3153 ("Add co-authored-by", IconName::UserCheck)
3154 };
3155
3156 if potential_co_authors.is_empty() {
3157 None
3158 } else {
3159 Some(
3160 IconButton::new("co-authors", icon)
3161 .shape(ui::IconButtonShape::Square)
3162 .icon_color(Color::Disabled)
3163 .selected_icon_color(Color::Selected)
3164 .toggle_state(self.add_coauthors)
3165 .tooltip(move |_, cx| {
3166 let title = format!(
3167 "{}:{}{}",
3168 tooltip_label,
3169 if potential_co_authors.len() == 1 {
3170 ""
3171 } else {
3172 "\n"
3173 },
3174 potential_co_authors
3175 .iter()
3176 .map(|(name, email)| format!(" {} <{}>", name, email))
3177 .join("\n")
3178 );
3179 Tooltip::simple(title, cx)
3180 })
3181 .on_click(cx.listener(|this, _, _, cx| {
3182 this.add_coauthors = !this.add_coauthors;
3183 cx.notify();
3184 }))
3185 .into_any_element(),
3186 )
3187 }
3188 }
3189
3190 fn render_git_commit_menu(
3191 &self,
3192 id: impl Into<ElementId>,
3193 keybinding_target: Option<FocusHandle>,
3194 cx: &mut Context<Self>,
3195 ) -> impl IntoElement {
3196 PopoverMenu::new(id.into())
3197 .trigger(
3198 ui::ButtonLike::new_rounded_right("commit-split-button-right")
3199 .layer(ui::ElevationIndex::ModalSurface)
3200 .size(ButtonSize::None)
3201 .child(
3202 h_flex()
3203 .px_1()
3204 .h_full()
3205 .justify_center()
3206 .border_l_1()
3207 .border_color(cx.theme().colors().border)
3208 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3209 ),
3210 )
3211 .menu({
3212 let git_panel = cx.entity();
3213 let has_previous_commit = self.head_commit(cx).is_some();
3214 let amend = self.amend_pending();
3215 let signoff = self.signoff_enabled;
3216
3217 move |window, cx| {
3218 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3219 context_menu
3220 .when_some(keybinding_target.clone(), |el, keybinding_target| {
3221 el.context(keybinding_target.clone())
3222 })
3223 .when(has_previous_commit, |this| {
3224 this.toggleable_entry(
3225 "Amend",
3226 amend,
3227 IconPosition::Start,
3228 Some(Box::new(Amend)),
3229 {
3230 let git_panel = git_panel.downgrade();
3231 move |_, cx| {
3232 git_panel
3233 .update(cx, |git_panel, cx| {
3234 git_panel.toggle_amend_pending(cx);
3235 })
3236 .ok();
3237 }
3238 },
3239 )
3240 })
3241 .toggleable_entry(
3242 "Signoff",
3243 signoff,
3244 IconPosition::Start,
3245 Some(Box::new(Signoff)),
3246 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3247 )
3248 }))
3249 }
3250 })
3251 .anchor(Corner::TopRight)
3252 }
3253
3254 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3255 if self.has_unstaged_conflicts() {
3256 (false, "You must resolve conflicts before committing")
3257 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
3258 (false, "No changes to commit")
3259 } else if self.pending_commit.is_some() {
3260 (false, "Commit in progress")
3261 } else if !self.has_commit_message(cx) {
3262 (false, "No commit message")
3263 } else if !self.has_write_access(cx) {
3264 (false, "You do not have write access to this project")
3265 } else {
3266 (true, self.commit_button_title())
3267 }
3268 }
3269
3270 pub fn commit_button_title(&self) -> &'static str {
3271 if self.amend_pending {
3272 if self.has_staged_changes() {
3273 "Amend"
3274 } else {
3275 "Amend Tracked"
3276 }
3277 } else {
3278 if self.has_staged_changes() {
3279 "Commit"
3280 } else {
3281 "Commit Tracked"
3282 }
3283 }
3284 }
3285
3286 fn expand_commit_editor(
3287 &mut self,
3288 _: &git::ExpandCommitEditor,
3289 window: &mut Window,
3290 cx: &mut Context<Self>,
3291 ) {
3292 let workspace = self.workspace.clone();
3293 window.defer(cx, move |window, cx| {
3294 workspace
3295 .update(cx, |workspace, cx| {
3296 CommitModal::toggle(workspace, None, window, cx)
3297 })
3298 .ok();
3299 })
3300 }
3301
3302 fn render_panel_header(
3303 &self,
3304 window: &mut Window,
3305 cx: &mut Context<Self>,
3306 ) -> Option<impl IntoElement> {
3307 self.active_repository.as_ref()?;
3308
3309 let text;
3310 let action;
3311 let tooltip;
3312 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3313 text = "Unstage All";
3314 action = git::UnstageAll.boxed_clone();
3315 tooltip = "git reset";
3316 } else {
3317 text = "Stage All";
3318 action = git::StageAll.boxed_clone();
3319 tooltip = "git add --all ."
3320 }
3321
3322 let change_string = match self.entry_count {
3323 0 => "No Changes".to_string(),
3324 1 => "1 Change".to_string(),
3325 _ => format!("{} Changes", self.entry_count),
3326 };
3327
3328 Some(
3329 self.panel_header_container(window, cx)
3330 .px_2()
3331 .justify_between()
3332 .child(
3333 panel_button(change_string)
3334 .color(Color::Muted)
3335 .tooltip(Tooltip::for_action_title_in(
3336 "Open Diff",
3337 &Diff,
3338 &self.focus_handle,
3339 ))
3340 .on_click(|_, _, cx| {
3341 cx.defer(|cx| {
3342 cx.dispatch_action(&Diff);
3343 })
3344 }),
3345 )
3346 .child(
3347 h_flex()
3348 .gap_1()
3349 .child(self.render_overflow_menu("overflow_menu"))
3350 .child(
3351 panel_filled_button(text)
3352 .tooltip(Tooltip::for_action_title_in(
3353 tooltip,
3354 action.as_ref(),
3355 &self.focus_handle,
3356 ))
3357 .disabled(self.entry_count == 0)
3358 .on_click(move |_, _, cx| {
3359 let action = action.boxed_clone();
3360 cx.defer(move |cx| {
3361 cx.dispatch_action(action.as_ref());
3362 })
3363 }),
3364 ),
3365 ),
3366 )
3367 }
3368
3369 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3370 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3371 if !self.can_push_and_pull(cx) {
3372 return None;
3373 }
3374 Some(
3375 h_flex()
3376 .gap_1()
3377 .flex_shrink_0()
3378 .when_some(branch, |this, branch| {
3379 let focus_handle = Some(self.focus_handle(cx));
3380
3381 this.children(render_remote_button(
3382 "remote-button",
3383 &branch,
3384 focus_handle,
3385 true,
3386 ))
3387 })
3388 .into_any_element(),
3389 )
3390 }
3391
3392 pub fn render_footer(
3393 &self,
3394 window: &mut Window,
3395 cx: &mut Context<Self>,
3396 ) -> Option<impl IntoElement> {
3397 let active_repository = self.active_repository.clone()?;
3398 let panel_editor_style = panel_editor_style(true, window, cx);
3399
3400 let enable_coauthors = self.render_co_authors(cx);
3401
3402 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3403 let expand_tooltip_focus_handle = editor_focus_handle.clone();
3404
3405 let branch = active_repository.read(cx).branch.clone();
3406 let head_commit = active_repository.read(cx).head_commit.clone();
3407
3408 let footer_size = px(32.);
3409 let gap = px(9.0);
3410 let max_height = panel_editor_style
3411 .text
3412 .line_height_in_pixels(window.rem_size())
3413 * MAX_PANEL_EDITOR_LINES
3414 + gap;
3415
3416 let git_panel = cx.entity();
3417 let display_name = SharedString::from(Arc::from(
3418 active_repository
3419 .read(cx)
3420 .display_name()
3421 .trim_end_matches("/"),
3422 ));
3423 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3424 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3425 });
3426
3427 let footer = v_flex()
3428 .child(PanelRepoFooter::new(
3429 display_name,
3430 branch,
3431 head_commit,
3432 Some(git_panel.clone()),
3433 ))
3434 .child(
3435 panel_editor_container(window, cx)
3436 .id("commit-editor-container")
3437 .relative()
3438 .w_full()
3439 .h(max_height + footer_size)
3440 .border_t_1()
3441 .border_color(cx.theme().colors().border)
3442 .cursor_text()
3443 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3444 window.focus(&this.commit_editor.focus_handle(cx));
3445 }))
3446 .child(
3447 h_flex()
3448 .id("commit-footer")
3449 .border_t_1()
3450 .when(editor_is_long, |el| {
3451 el.border_color(cx.theme().colors().border_variant)
3452 })
3453 .absolute()
3454 .bottom_0()
3455 .left_0()
3456 .w_full()
3457 .px_2()
3458 .h(footer_size)
3459 .flex_none()
3460 .justify_between()
3461 .child(
3462 self.render_generate_commit_message_button(cx)
3463 .unwrap_or_else(|| div().into_any_element()),
3464 )
3465 .child(
3466 h_flex()
3467 .gap_0p5()
3468 .children(enable_coauthors)
3469 .child(self.render_commit_button(cx)),
3470 ),
3471 )
3472 .child(
3473 div()
3474 .pr_2p5()
3475 .on_action(|&editor::actions::MoveUp, _, cx| {
3476 cx.stop_propagation();
3477 })
3478 .on_action(|&editor::actions::MoveDown, _, cx| {
3479 cx.stop_propagation();
3480 })
3481 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3482 )
3483 .child(
3484 h_flex()
3485 .absolute()
3486 .top_2()
3487 .right_2()
3488 .opacity(0.5)
3489 .hover(|this| this.opacity(1.0))
3490 .child(
3491 panel_icon_button("expand-commit-editor", IconName::Maximize)
3492 .icon_size(IconSize::Small)
3493 .size(ui::ButtonSize::Default)
3494 .tooltip(move |window, cx| {
3495 Tooltip::for_action_in(
3496 "Open Commit Modal",
3497 &git::ExpandCommitEditor,
3498 &expand_tooltip_focus_handle,
3499 window,
3500 cx,
3501 )
3502 })
3503 .on_click(cx.listener({
3504 move |_, _, window, cx| {
3505 window.dispatch_action(
3506 git::ExpandCommitEditor.boxed_clone(),
3507 cx,
3508 )
3509 }
3510 })),
3511 ),
3512 ),
3513 );
3514
3515 Some(footer)
3516 }
3517
3518 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3519 let (can_commit, tooltip) = self.configure_commit_button(cx);
3520 let title = self.commit_button_title();
3521 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3522 let amend = self.amend_pending();
3523 let signoff = self.signoff_enabled;
3524
3525 div()
3526 .id("commit-wrapper")
3527 .on_hover(cx.listener(move |this, hovered, _, cx| {
3528 this.show_placeholders =
3529 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3530 cx.notify()
3531 }))
3532 .child(SplitButton::new(
3533 ui::ButtonLike::new_rounded_left(ElementId::Name(
3534 format!("split-button-left-{}", title).into(),
3535 ))
3536 .layer(ui::ElevationIndex::ModalSurface)
3537 .size(ui::ButtonSize::Compact)
3538 .child(
3539 div()
3540 .child(Label::new(title).size(LabelSize::Small))
3541 .mr_0p5(),
3542 )
3543 .on_click({
3544 let git_panel = cx.weak_entity();
3545 move |_, window, cx| {
3546 telemetry::event!("Git Committed", source = "Git Panel");
3547 git_panel
3548 .update(cx, |git_panel, cx| {
3549 git_panel.set_amend_pending(false, cx);
3550 git_panel.commit_changes(
3551 CommitOptions { amend, signoff },
3552 window,
3553 cx,
3554 );
3555 })
3556 .ok();
3557 }
3558 })
3559 .disabled(!can_commit || self.modal_open)
3560 .tooltip({
3561 let handle = commit_tooltip_focus_handle.clone();
3562 move |window, cx| {
3563 if can_commit {
3564 Tooltip::with_meta_in(
3565 tooltip,
3566 Some(&git::Commit),
3567 format!(
3568 "git commit{}{}",
3569 if amend { " --amend" } else { "" },
3570 if signoff { " --signoff" } else { "" }
3571 ),
3572 &handle.clone(),
3573 window,
3574 cx,
3575 )
3576 } else {
3577 Tooltip::simple(tooltip, cx)
3578 }
3579 }
3580 }),
3581 self.render_git_commit_menu(
3582 ElementId::Name(format!("split-button-right-{}", title).into()),
3583 Some(commit_tooltip_focus_handle.clone()),
3584 cx,
3585 )
3586 .into_any_element(),
3587 ))
3588 }
3589
3590 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3591 h_flex()
3592 .py_1p5()
3593 .px_2()
3594 .gap_1p5()
3595 .justify_between()
3596 .border_t_1()
3597 .border_color(cx.theme().colors().border.opacity(0.8))
3598 .child(
3599 div()
3600 .flex_grow()
3601 .overflow_hidden()
3602 .max_w(relative(0.85))
3603 .child(
3604 Label::new("This will update your most recent commit.")
3605 .size(LabelSize::Small)
3606 .truncate(),
3607 ),
3608 )
3609 .child(
3610 panel_button("Cancel")
3611 .size(ButtonSize::Default)
3612 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3613 )
3614 }
3615
3616 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3617 let active_repository = self.active_repository.as_ref()?;
3618 let branch = active_repository.read(cx).branch.as_ref()?;
3619 let commit = branch.most_recent_commit.as_ref()?.clone();
3620 let workspace = self.workspace.clone();
3621 let this = cx.entity();
3622
3623 Some(
3624 h_flex()
3625 .py_1p5()
3626 .px_2()
3627 .gap_1p5()
3628 .justify_between()
3629 .border_t_1()
3630 .border_color(cx.theme().colors().border.opacity(0.8))
3631 .child(
3632 div()
3633 .flex_grow()
3634 .overflow_hidden()
3635 .max_w(relative(0.85))
3636 .child(
3637 Label::new(commit.subject.clone())
3638 .size(LabelSize::Small)
3639 .truncate(),
3640 )
3641 .id("commit-msg-hover")
3642 .on_click({
3643 let commit = commit.clone();
3644 let repo = active_repository.downgrade();
3645 move |_, window, cx| {
3646 CommitView::open(
3647 commit.clone(),
3648 repo.clone(),
3649 workspace.clone().clone(),
3650 window,
3651 cx,
3652 );
3653 }
3654 })
3655 .hoverable_tooltip({
3656 let repo = active_repository.clone();
3657 move |window, cx| {
3658 GitPanelMessageTooltip::new(
3659 this.clone(),
3660 commit.sha.clone(),
3661 repo.clone(),
3662 window,
3663 cx,
3664 )
3665 .into()
3666 }
3667 }),
3668 )
3669 .when(commit.has_parent, |this| {
3670 let has_unstaged = self.has_unstaged_changes();
3671 this.child(
3672 panel_icon_button("undo", IconName::Undo)
3673 .icon_size(IconSize::XSmall)
3674 .icon_color(Color::Muted)
3675 .tooltip(move |window, cx| {
3676 Tooltip::with_meta(
3677 "Uncommit",
3678 Some(&git::Uncommit),
3679 if has_unstaged {
3680 "git reset HEAD^ --soft"
3681 } else {
3682 "git reset HEAD^"
3683 },
3684 window,
3685 cx,
3686 )
3687 })
3688 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3689 )
3690 }),
3691 )
3692 }
3693
3694 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3695 h_flex().h_full().flex_grow().justify_center().child(
3696 v_flex()
3697 .gap_2()
3698 .child(h_flex().w_full().justify_around().child(
3699 if self.active_repository.is_some() {
3700 "No changes to commit"
3701 } else {
3702 "No Git repositories"
3703 },
3704 ))
3705 .children({
3706 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3707 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3708 h_flex().w_full().justify_around().child(
3709 panel_filled_button("Initialize Repository")
3710 .tooltip(Tooltip::for_action_title_in(
3711 "git init",
3712 &git::Init,
3713 &self.focus_handle,
3714 ))
3715 .on_click(move |_, _, cx| {
3716 cx.defer(move |cx| {
3717 cx.dispatch_action(&git::Init);
3718 })
3719 }),
3720 )
3721 })
3722 })
3723 .text_ui_sm(cx)
3724 .mx_auto()
3725 .text_color(Color::Placeholder.color(cx)),
3726 )
3727 }
3728
3729 fn render_vertical_scrollbar(
3730 &self,
3731 show_horizontal_scrollbar_container: bool,
3732 cx: &mut Context<Self>,
3733 ) -> impl IntoElement {
3734 div()
3735 .id("git-panel-vertical-scroll")
3736 .occlude()
3737 .flex_none()
3738 .h_full()
3739 .cursor_default()
3740 .absolute()
3741 .right_0()
3742 .top_0()
3743 .bottom_0()
3744 .w(px(12.))
3745 .when(show_horizontal_scrollbar_container, |this| {
3746 this.pb_neg_3p5()
3747 })
3748 .on_mouse_move(cx.listener(|_, _, _, cx| {
3749 cx.notify();
3750 cx.stop_propagation()
3751 }))
3752 .on_hover(|_, _, cx| {
3753 cx.stop_propagation();
3754 })
3755 .on_any_mouse_down(|_, _, cx| {
3756 cx.stop_propagation();
3757 })
3758 .on_mouse_up(
3759 MouseButton::Left,
3760 cx.listener(|this, _, window, cx| {
3761 if !this.vertical_scrollbar.state.is_dragging()
3762 && !this.focus_handle.contains_focused(window, cx)
3763 {
3764 this.vertical_scrollbar.hide(window, cx);
3765 cx.notify();
3766 }
3767
3768 cx.stop_propagation();
3769 }),
3770 )
3771 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3772 cx.notify();
3773 }))
3774 .children(Scrollbar::vertical(
3775 // percentage as f32..end_offset as f32,
3776 self.vertical_scrollbar.state.clone(),
3777 ))
3778 }
3779
3780 /// Renders the horizontal scrollbar.
3781 ///
3782 /// The right offset is used to determine how far to the right the
3783 /// scrollbar should extend to, useful for ensuring it doesn't collide
3784 /// with the vertical scrollbar when visible.
3785 fn render_horizontal_scrollbar(
3786 &self,
3787 right_offset: Pixels,
3788 cx: &mut Context<Self>,
3789 ) -> impl IntoElement {
3790 div()
3791 .id("git-panel-horizontal-scroll")
3792 .occlude()
3793 .flex_none()
3794 .w_full()
3795 .cursor_default()
3796 .absolute()
3797 .bottom_neg_px()
3798 .left_0()
3799 .right_0()
3800 .pr(right_offset)
3801 .on_mouse_move(cx.listener(|_, _, _, cx| {
3802 cx.notify();
3803 cx.stop_propagation()
3804 }))
3805 .on_hover(|_, _, cx| {
3806 cx.stop_propagation();
3807 })
3808 .on_any_mouse_down(|_, _, cx| {
3809 cx.stop_propagation();
3810 })
3811 .on_mouse_up(
3812 MouseButton::Left,
3813 cx.listener(|this, _, window, cx| {
3814 if !this.horizontal_scrollbar.state.is_dragging()
3815 && !this.focus_handle.contains_focused(window, cx)
3816 {
3817 this.horizontal_scrollbar.hide(window, cx);
3818 cx.notify();
3819 }
3820
3821 cx.stop_propagation();
3822 }),
3823 )
3824 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3825 cx.notify();
3826 }))
3827 .children(Scrollbar::horizontal(
3828 // percentage as f32..end_offset as f32,
3829 self.horizontal_scrollbar.state.clone(),
3830 ))
3831 }
3832
3833 fn render_buffer_header_controls(
3834 &self,
3835 entity: &Entity<Self>,
3836 file: &Arc<dyn File>,
3837 _: &Window,
3838 cx: &App,
3839 ) -> Option<AnyElement> {
3840 let repo = self.active_repository.as_ref()?.read(cx);
3841 let project_path = (file.worktree_id(cx), file.path()).into();
3842 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3843 let ix = self.entry_by_path(&repo_path, cx)?;
3844 let entry = self.entries.get(ix)?;
3845
3846 let entry_staging = self.entry_staging(entry.status_entry()?);
3847
3848 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3849 .disabled(!self.has_write_access(cx))
3850 .fill()
3851 .elevation(ElevationIndex::Surface)
3852 .on_click({
3853 let entry = entry.clone();
3854 let git_panel = entity.downgrade();
3855 move |_, window, cx| {
3856 git_panel
3857 .update(cx, |this, cx| {
3858 this.toggle_staged_for_entry(&entry, window, cx);
3859 cx.stop_propagation();
3860 })
3861 .ok();
3862 }
3863 });
3864 Some(
3865 h_flex()
3866 .id("start-slot")
3867 .text_lg()
3868 .child(checkbox)
3869 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3870 // prevent the list item active state triggering when toggling checkbox
3871 cx.stop_propagation();
3872 })
3873 .into_any_element(),
3874 )
3875 }
3876
3877 fn render_entries(
3878 &self,
3879 has_write_access: bool,
3880 _: &Window,
3881 cx: &mut Context<Self>,
3882 ) -> impl IntoElement {
3883 let entry_count = self.entries.len();
3884
3885 let scroll_track_size = px(16.);
3886
3887 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3888 // magic number
3889 px(3.)
3890 } else {
3891 px(0.)
3892 };
3893
3894 v_flex()
3895 .flex_1()
3896 .size_full()
3897 .overflow_hidden()
3898 .relative()
3899 // Show a border on the top and bottom of the container when
3900 // the vertical scrollbar container is visible so we don't have a
3901 // floating left border in the panel.
3902 .when(self.vertical_scrollbar.show_track, |this| {
3903 this.border_t_1()
3904 .border_b_1()
3905 .border_color(cx.theme().colors().border)
3906 })
3907 .child(
3908 h_flex()
3909 .flex_1()
3910 .size_full()
3911 .relative()
3912 .overflow_hidden()
3913 .child(
3914 uniform_list(
3915 "entries",
3916 entry_count,
3917 cx.processor(move |this, range: Range<usize>, window, cx| {
3918 let mut items = Vec::with_capacity(range.end - range.start);
3919
3920 for ix in range {
3921 match &this.entries.get(ix) {
3922 Some(GitListEntry::Status(entry)) => {
3923 items.push(this.render_entry(
3924 ix,
3925 entry,
3926 has_write_access,
3927 window,
3928 cx,
3929 ));
3930 }
3931 Some(GitListEntry::Header(header)) => {
3932 items.push(this.render_list_header(
3933 ix,
3934 header,
3935 has_write_access,
3936 window,
3937 cx,
3938 ));
3939 }
3940 None => {}
3941 }
3942 }
3943
3944 items
3945 }),
3946 )
3947 .when(
3948 !self.horizontal_scrollbar.show_track
3949 && self.horizontal_scrollbar.show_scrollbar,
3950 |this| {
3951 // when not showing the horizontal scrollbar track, make sure we don't
3952 // obscure the last entry
3953 this.pb(scroll_track_size)
3954 },
3955 )
3956 .size_full()
3957 .flex_grow()
3958 .with_sizing_behavior(ListSizingBehavior::Auto)
3959 .with_horizontal_sizing_behavior(
3960 ListHorizontalSizingBehavior::Unconstrained,
3961 )
3962 .with_width_from_item(self.max_width_item_index)
3963 .track_scroll(self.scroll_handle.clone()),
3964 )
3965 .on_mouse_down(
3966 MouseButton::Right,
3967 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3968 this.deploy_panel_context_menu(event.position, window, cx)
3969 }),
3970 )
3971 .when(self.vertical_scrollbar.show_track, |this| {
3972 this.child(
3973 v_flex()
3974 .h_full()
3975 .flex_none()
3976 .w(scroll_track_size)
3977 .bg(cx.theme().colors().panel_background)
3978 .child(
3979 div()
3980 .size_full()
3981 .flex_1()
3982 .border_l_1()
3983 .border_color(cx.theme().colors().border),
3984 ),
3985 )
3986 })
3987 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3988 this.child(
3989 self.render_vertical_scrollbar(
3990 self.horizontal_scrollbar.show_track,
3991 cx,
3992 ),
3993 )
3994 }),
3995 )
3996 .when(self.horizontal_scrollbar.show_track, |this| {
3997 this.child(
3998 h_flex()
3999 .w_full()
4000 .h(scroll_track_size)
4001 .flex_none()
4002 .relative()
4003 .child(
4004 div()
4005 .w_full()
4006 .flex_1()
4007 // for some reason the horizontal scrollbar is 1px
4008 // taller than the vertical scrollbar??
4009 .h(scroll_track_size - px(1.))
4010 .bg(cx.theme().colors().panel_background)
4011 .border_t_1()
4012 .border_color(cx.theme().colors().border),
4013 )
4014 .when(self.vertical_scrollbar.show_track, |this| {
4015 this.child(
4016 div()
4017 .flex_none()
4018 // -1px prevents a missing pixel between the two container borders
4019 .w(scroll_track_size - px(1.))
4020 .h_full(),
4021 )
4022 .child(
4023 // HACK: Fill the missing 1px 🥲
4024 div()
4025 .absolute()
4026 .right(scroll_track_size - px(1.))
4027 .bottom(scroll_track_size - px(1.))
4028 .size_px()
4029 .bg(cx.theme().colors().border),
4030 )
4031 }),
4032 )
4033 })
4034 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
4035 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
4036 })
4037 }
4038
4039 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4040 Label::new(label.into()).color(color).single_line()
4041 }
4042
4043 fn list_item_height(&self) -> Rems {
4044 rems(1.75)
4045 }
4046
4047 fn render_list_header(
4048 &self,
4049 ix: usize,
4050 header: &GitHeaderEntry,
4051 _: bool,
4052 _: &Window,
4053 _: &Context<Self>,
4054 ) -> AnyElement {
4055 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4056
4057 h_flex()
4058 .id(id)
4059 .h(self.list_item_height())
4060 .w_full()
4061 .items_end()
4062 .px(rems(0.75)) // ~12px
4063 .pb(rems(0.3125)) // ~ 5px
4064 .child(
4065 Label::new(header.title())
4066 .color(Color::Muted)
4067 .size(LabelSize::Small)
4068 .line_height_style(LineHeightStyle::UiLabel)
4069 .single_line(),
4070 )
4071 .into_any_element()
4072 }
4073
4074 pub fn load_commit_details(
4075 &self,
4076 sha: String,
4077 cx: &mut Context<Self>,
4078 ) -> Task<anyhow::Result<CommitDetails>> {
4079 let Some(repo) = self.active_repository.clone() else {
4080 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4081 };
4082 repo.update(cx, |repo, cx| {
4083 let show = repo.show(sha);
4084 cx.spawn(async move |_, _| show.await?)
4085 })
4086 }
4087
4088 fn deploy_entry_context_menu(
4089 &mut self,
4090 position: Point<Pixels>,
4091 ix: usize,
4092 window: &mut Window,
4093 cx: &mut Context<Self>,
4094 ) {
4095 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4096 return;
4097 };
4098 let stage_title = if entry.status.staging().is_fully_staged() {
4099 "Unstage File"
4100 } else {
4101 "Stage File"
4102 };
4103 let restore_title = if entry.status.is_created() {
4104 "Trash File"
4105 } else {
4106 "Restore File"
4107 };
4108 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4109 context_menu
4110 .context(self.focus_handle.clone())
4111 .action(stage_title, ToggleStaged.boxed_clone())
4112 .action(restore_title, git::RestoreFile::default().boxed_clone())
4113 .separator()
4114 .action("Open Diff", Confirm.boxed_clone())
4115 .action("Open File", SecondaryConfirm.boxed_clone())
4116 });
4117 self.selected_entry = Some(ix);
4118 self.set_context_menu(context_menu, position, window, cx);
4119 }
4120
4121 fn deploy_panel_context_menu(
4122 &mut self,
4123 position: Point<Pixels>,
4124 window: &mut Window,
4125 cx: &mut Context<Self>,
4126 ) {
4127 let context_menu = git_panel_context_menu(
4128 self.focus_handle.clone(),
4129 GitMenuState {
4130 has_tracked_changes: self.has_tracked_changes(),
4131 has_staged_changes: self.has_staged_changes(),
4132 has_unstaged_changes: self.has_unstaged_changes(),
4133 has_new_changes: self.new_count > 0,
4134 },
4135 window,
4136 cx,
4137 );
4138 self.set_context_menu(context_menu, position, window, cx);
4139 }
4140
4141 fn set_context_menu(
4142 &mut self,
4143 context_menu: Entity<ContextMenu>,
4144 position: Point<Pixels>,
4145 window: &Window,
4146 cx: &mut Context<Self>,
4147 ) {
4148 let subscription = cx.subscribe_in(
4149 &context_menu,
4150 window,
4151 |this, _, _: &DismissEvent, window, cx| {
4152 if this.context_menu.as_ref().is_some_and(|context_menu| {
4153 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4154 }) {
4155 cx.focus_self(window);
4156 }
4157 this.context_menu.take();
4158 cx.notify();
4159 },
4160 );
4161 self.context_menu = Some((context_menu, position, subscription));
4162 cx.notify();
4163 }
4164
4165 fn render_entry(
4166 &self,
4167 ix: usize,
4168 entry: &GitStatusEntry,
4169 has_write_access: bool,
4170 window: &Window,
4171 cx: &Context<Self>,
4172 ) -> AnyElement {
4173 let display_name = entry.display_name();
4174
4175 let selected = self.selected_entry == Some(ix);
4176 let marked = self.marked_entries.contains(&ix);
4177 let status_style = GitPanelSettings::get_global(cx).status_style;
4178 let status = entry.status;
4179
4180 let has_conflict = status.is_conflicted();
4181 let is_modified = status.is_modified();
4182 let is_deleted = status.is_deleted();
4183
4184 let label_color = if status_style == StatusStyle::LabelColor {
4185 if has_conflict {
4186 Color::VersionControlConflict
4187 } else if is_modified {
4188 Color::VersionControlModified
4189 } else if is_deleted {
4190 // We don't want a bunch of red labels in the list
4191 Color::Disabled
4192 } else {
4193 Color::VersionControlAdded
4194 }
4195 } else {
4196 Color::Default
4197 };
4198
4199 let path_color = if status.is_deleted() {
4200 Color::Disabled
4201 } else {
4202 Color::Muted
4203 };
4204
4205 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4206 let checkbox_wrapper_id: ElementId =
4207 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4208 let checkbox_id: ElementId =
4209 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4210
4211 let entry_staging = self.entry_staging(entry);
4212 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4213 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4214 is_staged = ToggleState::Selected;
4215 }
4216
4217 let handle = cx.weak_entity();
4218
4219 let selected_bg_alpha = 0.08;
4220 let marked_bg_alpha = 0.12;
4221 let state_opacity_step = 0.04;
4222
4223 let base_bg = match (selected, marked) {
4224 (true, true) => cx
4225 .theme()
4226 .status()
4227 .info
4228 .alpha(selected_bg_alpha + marked_bg_alpha),
4229 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4230 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4231 _ => cx.theme().colors().ghost_element_background,
4232 };
4233
4234 let hover_bg = if selected {
4235 cx.theme()
4236 .status()
4237 .info
4238 .alpha(selected_bg_alpha + state_opacity_step)
4239 } else {
4240 cx.theme().colors().ghost_element_hover
4241 };
4242
4243 let active_bg = if selected {
4244 cx.theme()
4245 .status()
4246 .info
4247 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4248 } else {
4249 cx.theme().colors().ghost_element_active
4250 };
4251
4252 h_flex()
4253 .id(id)
4254 .h(self.list_item_height())
4255 .w_full()
4256 .items_center()
4257 .border_1()
4258 .when(selected && self.focus_handle.is_focused(window), |el| {
4259 el.border_color(cx.theme().colors().border_focused)
4260 })
4261 .px(rems(0.75)) // ~12px
4262 .overflow_hidden()
4263 .flex_none()
4264 .gap_1p5()
4265 .bg(base_bg)
4266 .hover(|this| this.bg(hover_bg))
4267 .active(|this| this.bg(active_bg))
4268 .on_click({
4269 cx.listener(move |this, event: &ClickEvent, window, cx| {
4270 this.selected_entry = Some(ix);
4271 cx.notify();
4272 if event.modifiers().secondary() {
4273 this.open_file(&Default::default(), window, cx)
4274 } else {
4275 this.open_diff(&Default::default(), window, cx);
4276 this.focus_handle.focus(window);
4277 }
4278 })
4279 })
4280 .on_mouse_down(
4281 MouseButton::Right,
4282 move |event: &MouseDownEvent, window, cx| {
4283 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4284 if event.button != MouseButton::Right {
4285 return;
4286 }
4287
4288 let Some(this) = handle.upgrade() else {
4289 return;
4290 };
4291 this.update(cx, |this, cx| {
4292 this.deploy_entry_context_menu(event.position, ix, window, cx);
4293 });
4294 cx.stop_propagation();
4295 },
4296 )
4297 .child(
4298 div()
4299 .id(checkbox_wrapper_id)
4300 .flex_none()
4301 .occlude()
4302 .cursor_pointer()
4303 .child(
4304 Checkbox::new(checkbox_id, is_staged)
4305 .disabled(!has_write_access)
4306 .fill()
4307 .elevation(ElevationIndex::Surface)
4308 .on_click_ext({
4309 let entry = entry.clone();
4310 let this = cx.weak_entity();
4311 move |_, click, window, cx| {
4312 this.update(cx, |this, cx| {
4313 if !has_write_access {
4314 return;
4315 }
4316 if click.modifiers().shift {
4317 this.stage_bulk(ix, cx);
4318 } else {
4319 this.toggle_staged_for_entry(
4320 &GitListEntry::Status(entry.clone()),
4321 window,
4322 cx,
4323 );
4324 }
4325 cx.stop_propagation();
4326 })
4327 .ok();
4328 }
4329 })
4330 .tooltip(move |window, cx| {
4331 let is_staged = entry_staging.is_fully_staged();
4332
4333 let action = if is_staged { "Unstage" } else { "Stage" };
4334 let tooltip_name = action.to_string();
4335
4336 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4337 }),
4338 ),
4339 )
4340 .child(git_status_icon(status))
4341 .child(
4342 h_flex()
4343 .items_center()
4344 .flex_1()
4345 // .overflow_hidden()
4346 .when_some(entry.parent_dir(), |this, parent| {
4347 if !parent.is_empty() {
4348 this.child(
4349 self.entry_label(format!("{}/", parent), path_color)
4350 .when(status.is_deleted(), |this| this.strikethrough()),
4351 )
4352 } else {
4353 this
4354 }
4355 })
4356 .child(
4357 self.entry_label(display_name.clone(), label_color)
4358 .when(status.is_deleted(), |this| this.strikethrough()),
4359 ),
4360 )
4361 .into_any_element()
4362 }
4363
4364 fn has_write_access(&self, cx: &App) -> bool {
4365 !self.project.read(cx).is_read_only(cx)
4366 }
4367
4368 pub fn amend_pending(&self) -> bool {
4369 self.amend_pending
4370 }
4371
4372 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4373 self.amend_pending = value;
4374 self.serialize(cx);
4375 cx.notify();
4376 }
4377
4378 pub fn signoff_enabled(&self) -> bool {
4379 self.signoff_enabled
4380 }
4381
4382 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4383 self.signoff_enabled = value;
4384 self.serialize(cx);
4385 cx.notify();
4386 }
4387
4388 pub fn toggle_signoff_enabled(
4389 &mut self,
4390 _: &Signoff,
4391 _window: &mut Window,
4392 cx: &mut Context<Self>,
4393 ) {
4394 self.set_signoff_enabled(!self.signoff_enabled, cx);
4395 }
4396
4397 pub async fn load(
4398 workspace: WeakEntity<Workspace>,
4399 mut cx: AsyncWindowContext,
4400 ) -> anyhow::Result<Entity<Self>> {
4401 let serialized_panel = match workspace
4402 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4403 .ok()
4404 .flatten()
4405 {
4406 Some(serialization_key) => cx
4407 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4408 .await
4409 .context("loading git panel")
4410 .log_err()
4411 .flatten()
4412 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4413 .transpose()
4414 .log_err()
4415 .flatten(),
4416 None => None,
4417 };
4418
4419 workspace.update_in(&mut cx, |workspace, window, cx| {
4420 let panel = GitPanel::new(workspace, window, cx);
4421
4422 if let Some(serialized_panel) = serialized_panel {
4423 panel.update(cx, |panel, cx| {
4424 panel.width = serialized_panel.width;
4425 panel.amend_pending = serialized_panel.amend_pending;
4426 panel.signoff_enabled = serialized_panel.signoff_enabled;
4427 cx.notify();
4428 })
4429 }
4430
4431 panel
4432 })
4433 }
4434
4435 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4436 let Some(op) = self.bulk_staging.as_ref() else {
4437 return;
4438 };
4439 let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4440 return;
4441 };
4442 if let Some(entry) = self.entries.get(index)
4443 && let Some(entry) = entry.status_entry()
4444 {
4445 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4446 }
4447 if index < anchor_index {
4448 std::mem::swap(&mut index, &mut anchor_index);
4449 }
4450 let entries = self
4451 .entries
4452 .get(anchor_index..=index)
4453 .unwrap_or_default()
4454 .iter()
4455 .filter_map(|entry| entry.status_entry().cloned())
4456 .collect::<Vec<_>>();
4457 self.change_file_stage(true, entries, cx);
4458 }
4459
4460 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4461 let Some(repo) = self.active_repository.as_ref() else {
4462 return;
4463 };
4464 self.bulk_staging = Some(BulkStaging {
4465 repo_id: repo.read(cx).id,
4466 anchor: path,
4467 });
4468 }
4469
4470 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4471 self.set_amend_pending(!self.amend_pending, cx);
4472 if self.amend_pending {
4473 self.load_last_commit_message_if_empty(cx);
4474 }
4475 }
4476}
4477
4478fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4479 let is_enabled = agent_settings::AgentSettings::get_global(cx).enabled
4480 && !DisableAiSettings::get_global(cx).disable_ai;
4481
4482 is_enabled
4483 .then(|| {
4484 let ConfiguredModel { provider, model } =
4485 LanguageModelRegistry::read_global(cx).commit_message_model()?;
4486
4487 provider.is_authenticated(cx).then(|| model)
4488 })
4489 .flatten()
4490}
4491
4492impl Render for GitPanel {
4493 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4494 let project = self.project.read(cx);
4495 let has_entries = self.entries.len() > 0;
4496 let room = self
4497 .workspace
4498 .upgrade()
4499 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4500
4501 let has_write_access = self.has_write_access(cx);
4502
4503 let has_co_authors = room.map_or(false, |room| {
4504 self.load_local_committer(cx);
4505 let room = room.read(cx);
4506 room.remote_participants()
4507 .values()
4508 .any(|remote_participant| remote_participant.can_write())
4509 });
4510
4511 v_flex()
4512 .id("git_panel")
4513 .key_context(self.dispatch_context(window, cx))
4514 .track_focus(&self.focus_handle)
4515 .when(has_write_access && !project.is_read_only(cx), |this| {
4516 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4517 .on_action(cx.listener(Self::stage_range))
4518 .on_action(cx.listener(GitPanel::commit))
4519 .on_action(cx.listener(GitPanel::amend))
4520 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4521 .on_action(cx.listener(Self::stage_all))
4522 .on_action(cx.listener(Self::unstage_all))
4523 .on_action(cx.listener(Self::stage_selected))
4524 .on_action(cx.listener(Self::unstage_selected))
4525 .on_action(cx.listener(Self::restore_tracked_files))
4526 .on_action(cx.listener(Self::revert_selected))
4527 .on_action(cx.listener(Self::clean_all))
4528 .on_action(cx.listener(Self::generate_commit_message_action))
4529 .on_action(cx.listener(Self::stash_all))
4530 .on_action(cx.listener(Self::stash_pop))
4531 })
4532 .on_action(cx.listener(Self::select_first))
4533 .on_action(cx.listener(Self::select_next))
4534 .on_action(cx.listener(Self::select_previous))
4535 .on_action(cx.listener(Self::select_last))
4536 .on_action(cx.listener(Self::close_panel))
4537 .on_action(cx.listener(Self::open_diff))
4538 .on_action(cx.listener(Self::open_file))
4539 .on_action(cx.listener(Self::focus_changes_list))
4540 .on_action(cx.listener(Self::focus_editor))
4541 .on_action(cx.listener(Self::expand_commit_editor))
4542 .when(has_write_access && has_co_authors, |git_panel| {
4543 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4544 })
4545 .on_hover(cx.listener(move |this, hovered, window, cx| {
4546 if *hovered {
4547 this.horizontal_scrollbar.show(cx);
4548 this.vertical_scrollbar.show(cx);
4549 cx.notify();
4550 } else if !this.focus_handle.contains_focused(window, cx) {
4551 this.hide_scrollbars(window, cx);
4552 }
4553 }))
4554 .size_full()
4555 .overflow_hidden()
4556 .bg(cx.theme().colors().panel_background)
4557 .child(
4558 v_flex()
4559 .size_full()
4560 .children(self.render_panel_header(window, cx))
4561 .map(|this| {
4562 if has_entries {
4563 this.child(self.render_entries(has_write_access, window, cx))
4564 } else {
4565 this.child(self.render_empty_state(cx).into_any_element())
4566 }
4567 })
4568 .children(self.render_footer(window, cx))
4569 .when(self.amend_pending, |this| {
4570 this.child(self.render_pending_amend(cx))
4571 })
4572 .when(!self.amend_pending, |this| {
4573 this.children(self.render_previous_commit(cx))
4574 })
4575 .into_any_element(),
4576 )
4577 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4578 deferred(
4579 anchored()
4580 .position(*position)
4581 .anchor(Corner::TopLeft)
4582 .child(menu.clone()),
4583 )
4584 .with_priority(1)
4585 }))
4586 }
4587}
4588
4589impl Focusable for GitPanel {
4590 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4591 if self.entries.is_empty() {
4592 self.commit_editor.focus_handle(cx)
4593 } else {
4594 self.focus_handle.clone()
4595 }
4596 }
4597}
4598
4599impl EventEmitter<Event> for GitPanel {}
4600
4601impl EventEmitter<PanelEvent> for GitPanel {}
4602
4603pub(crate) struct GitPanelAddon {
4604 pub(crate) workspace: WeakEntity<Workspace>,
4605}
4606
4607impl editor::Addon for GitPanelAddon {
4608 fn to_any(&self) -> &dyn std::any::Any {
4609 self
4610 }
4611
4612 fn render_buffer_header_controls(
4613 &self,
4614 excerpt_info: &ExcerptInfo,
4615 window: &Window,
4616 cx: &App,
4617 ) -> Option<AnyElement> {
4618 let file = excerpt_info.buffer.file()?;
4619 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4620
4621 git_panel
4622 .read(cx)
4623 .render_buffer_header_controls(&git_panel, file, window, cx)
4624 }
4625}
4626
4627impl Panel for GitPanel {
4628 fn persistent_name() -> &'static str {
4629 "GitPanel"
4630 }
4631
4632 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4633 GitPanelSettings::get_global(cx).dock
4634 }
4635
4636 fn position_is_valid(&self, position: DockPosition) -> bool {
4637 matches!(position, DockPosition::Left | DockPosition::Right)
4638 }
4639
4640 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4641 settings::update_settings_file::<GitPanelSettings>(
4642 self.fs.clone(),
4643 cx,
4644 move |settings, _| settings.dock = Some(position),
4645 );
4646 }
4647
4648 fn size(&self, _: &Window, cx: &App) -> Pixels {
4649 self.width
4650 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4651 }
4652
4653 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4654 self.width = size;
4655 self.serialize(cx);
4656 cx.notify();
4657 }
4658
4659 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4660 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4661 }
4662
4663 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4664 Some("Git Panel")
4665 }
4666
4667 fn toggle_action(&self) -> Box<dyn Action> {
4668 Box::new(ToggleFocus)
4669 }
4670
4671 fn activation_priority(&self) -> u32 {
4672 2
4673 }
4674}
4675
4676impl PanelHeader for GitPanel {}
4677
4678struct GitPanelMessageTooltip {
4679 commit_tooltip: Option<Entity<CommitTooltip>>,
4680}
4681
4682impl GitPanelMessageTooltip {
4683 fn new(
4684 git_panel: Entity<GitPanel>,
4685 sha: SharedString,
4686 repository: Entity<Repository>,
4687 window: &mut Window,
4688 cx: &mut App,
4689 ) -> Entity<Self> {
4690 cx.new(|cx| {
4691 cx.spawn_in(window, async move |this, cx| {
4692 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4693 (
4694 git_panel.load_commit_details(sha.to_string(), cx),
4695 git_panel.workspace.clone(),
4696 )
4697 })?;
4698 let details = details.await?;
4699
4700 let commit_details = crate::commit_tooltip::CommitDetails {
4701 sha: details.sha.clone(),
4702 author_name: details.author_name.clone(),
4703 author_email: details.author_email.clone(),
4704 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4705 message: Some(ParsedCommitMessage {
4706 message: details.message.clone(),
4707 ..Default::default()
4708 }),
4709 };
4710
4711 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4712 this.commit_tooltip = Some(cx.new(move |cx| {
4713 CommitTooltip::new(commit_details, repository, workspace, cx)
4714 }));
4715 cx.notify();
4716 })
4717 })
4718 .detach();
4719
4720 Self {
4721 commit_tooltip: None,
4722 }
4723 })
4724 }
4725}
4726
4727impl Render for GitPanelMessageTooltip {
4728 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4729 if let Some(commit_tooltip) = &self.commit_tooltip {
4730 commit_tooltip.clone().into_any_element()
4731 } else {
4732 gpui::Empty.into_any_element()
4733 }
4734 }
4735}
4736
4737#[derive(IntoElement, RegisterComponent)]
4738pub struct PanelRepoFooter {
4739 active_repository: SharedString,
4740 branch: Option<Branch>,
4741 head_commit: Option<CommitDetails>,
4742
4743 // Getting a GitPanel in previews will be difficult.
4744 //
4745 // For now just take an option here, and we won't bind handlers to buttons in previews.
4746 git_panel: Option<Entity<GitPanel>>,
4747}
4748
4749impl PanelRepoFooter {
4750 pub fn new(
4751 active_repository: SharedString,
4752 branch: Option<Branch>,
4753 head_commit: Option<CommitDetails>,
4754 git_panel: Option<Entity<GitPanel>>,
4755 ) -> Self {
4756 Self {
4757 active_repository,
4758 branch,
4759 head_commit,
4760 git_panel,
4761 }
4762 }
4763
4764 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4765 Self {
4766 active_repository,
4767 branch,
4768 head_commit: None,
4769 git_panel: None,
4770 }
4771 }
4772}
4773
4774impl RenderOnce for PanelRepoFooter {
4775 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4776 let project = self
4777 .git_panel
4778 .as_ref()
4779 .map(|panel| panel.read(cx).project.clone());
4780
4781 let repo = self
4782 .git_panel
4783 .as_ref()
4784 .and_then(|panel| panel.read(cx).active_repository.clone());
4785
4786 let single_repo = project
4787 .as_ref()
4788 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4789 .unwrap_or(true);
4790
4791 const MAX_BRANCH_LEN: usize = 16;
4792 const MAX_REPO_LEN: usize = 16;
4793 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4794 const MAX_SHORT_SHA_LEN: usize = 8;
4795
4796 let branch_name = self
4797 .branch
4798 .as_ref()
4799 .map(|branch| branch.name().to_owned())
4800 .or_else(|| {
4801 self.head_commit.as_ref().map(|commit| {
4802 commit
4803 .sha
4804 .chars()
4805 .take(MAX_SHORT_SHA_LEN)
4806 .collect::<String>()
4807 })
4808 })
4809 .unwrap_or_else(|| " (no branch)".to_owned());
4810 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4811
4812 let active_repo_name = self.active_repository.clone();
4813
4814 let branch_actual_len = branch_name.len();
4815 let repo_actual_len = active_repo_name.len();
4816
4817 // ideally, show the whole branch and repo names but
4818 // when we can't, use a budget to allocate space between the two
4819 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4820 <= LABEL_CHARACTER_BUDGET
4821 {
4822 (repo_actual_len, branch_actual_len)
4823 } else {
4824 if branch_actual_len <= MAX_BRANCH_LEN {
4825 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4826 (repo_space, branch_actual_len)
4827 } else if repo_actual_len <= MAX_REPO_LEN {
4828 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4829 (repo_actual_len, branch_space)
4830 } else {
4831 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4832 }
4833 };
4834
4835 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4836 active_repo_name.to_string()
4837 } else {
4838 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4839 };
4840
4841 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4842 branch_name.to_string()
4843 } else {
4844 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4845 };
4846
4847 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4848 .style(ButtonStyle::Transparent)
4849 .size(ButtonSize::None)
4850 .label_size(LabelSize::Small)
4851 .color(Color::Muted);
4852
4853 let repo_selector = PopoverMenu::new("repository-switcher")
4854 .menu({
4855 let project = project.clone();
4856 move |window, cx| {
4857 let project = project.clone()?;
4858 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4859 }
4860 })
4861 .trigger_with_tooltip(
4862 repo_selector_trigger.disabled(single_repo).truncate(true),
4863 Tooltip::text("Switch Active Repository"),
4864 )
4865 .anchor(Corner::BottomLeft)
4866 .into_any_element();
4867
4868 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4869 .style(ButtonStyle::Transparent)
4870 .size(ButtonSize::None)
4871 .label_size(LabelSize::Small)
4872 .truncate(true)
4873 .tooltip(Tooltip::for_action_title(
4874 "Switch Branch",
4875 &zed_actions::git::Switch,
4876 ))
4877 .on_click(|_, window, cx| {
4878 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4879 });
4880
4881 let branch_selector = PopoverMenu::new("popover-button")
4882 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4883 .trigger_with_tooltip(
4884 branch_selector_button,
4885 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4886 )
4887 .anchor(Corner::BottomLeft)
4888 .offset(gpui::Point {
4889 x: px(0.0),
4890 y: px(-2.0),
4891 });
4892
4893 h_flex()
4894 .w_full()
4895 .px_2()
4896 .h(px(36.))
4897 .items_center()
4898 .justify_between()
4899 .gap_1()
4900 .child(
4901 h_flex()
4902 .flex_1()
4903 .overflow_hidden()
4904 .items_center()
4905 .child(
4906 div().child(
4907 Icon::new(IconName::GitBranchAlt)
4908 .size(IconSize::Small)
4909 .color(if single_repo {
4910 Color::Disabled
4911 } else {
4912 Color::Muted
4913 }),
4914 ),
4915 )
4916 .child(repo_selector)
4917 .when(show_separator, |this| {
4918 this.child(
4919 div()
4920 .text_color(cx.theme().colors().text_muted)
4921 .text_sm()
4922 .child("/"),
4923 )
4924 })
4925 .child(branch_selector),
4926 )
4927 .children(if let Some(git_panel) = self.git_panel {
4928 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4929 } else {
4930 None
4931 })
4932 }
4933}
4934
4935impl Component for PanelRepoFooter {
4936 fn scope() -> ComponentScope {
4937 ComponentScope::VersionControl
4938 }
4939
4940 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4941 let unknown_upstream = None;
4942 let no_remote_upstream = Some(UpstreamTracking::Gone);
4943 let ahead_of_upstream = Some(
4944 UpstreamTrackingStatus {
4945 ahead: 2,
4946 behind: 0,
4947 }
4948 .into(),
4949 );
4950 let behind_upstream = Some(
4951 UpstreamTrackingStatus {
4952 ahead: 0,
4953 behind: 2,
4954 }
4955 .into(),
4956 );
4957 let ahead_and_behind_upstream = Some(
4958 UpstreamTrackingStatus {
4959 ahead: 3,
4960 behind: 1,
4961 }
4962 .into(),
4963 );
4964
4965 let not_ahead_or_behind_upstream = Some(
4966 UpstreamTrackingStatus {
4967 ahead: 0,
4968 behind: 0,
4969 }
4970 .into(),
4971 );
4972
4973 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4974 Branch {
4975 is_head: true,
4976 ref_name: "some-branch".into(),
4977 upstream: upstream.map(|tracking| Upstream {
4978 ref_name: "origin/some-branch".into(),
4979 tracking,
4980 }),
4981 most_recent_commit: Some(CommitSummary {
4982 sha: "abc123".into(),
4983 subject: "Modify stuff".into(),
4984 commit_timestamp: 1710932954,
4985 has_parent: true,
4986 }),
4987 }
4988 }
4989
4990 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4991 Branch {
4992 is_head: true,
4993 ref_name: branch_name.to_string().into(),
4994 upstream: upstream.map(|tracking| Upstream {
4995 ref_name: format!("zed/{}", branch_name).into(),
4996 tracking,
4997 }),
4998 most_recent_commit: Some(CommitSummary {
4999 sha: "abc123".into(),
5000 subject: "Modify stuff".into(),
5001 commit_timestamp: 1710932954,
5002 has_parent: true,
5003 }),
5004 }
5005 }
5006
5007 fn active_repository(id: usize) -> SharedString {
5008 format!("repo-{}", id).into()
5009 }
5010
5011 let example_width = px(340.);
5012 Some(
5013 v_flex()
5014 .gap_6()
5015 .w_full()
5016 .flex_none()
5017 .children(vec![
5018 example_group_with_title(
5019 "Action Button States",
5020 vec![
5021 single_example(
5022 "No Branch",
5023 div()
5024 .w(example_width)
5025 .overflow_hidden()
5026 .child(PanelRepoFooter::new_preview(
5027 active_repository(1).clone(),
5028 None,
5029 ))
5030 .into_any_element(),
5031 ),
5032 single_example(
5033 "Remote status unknown",
5034 div()
5035 .w(example_width)
5036 .overflow_hidden()
5037 .child(PanelRepoFooter::new_preview(
5038 active_repository(2).clone(),
5039 Some(branch(unknown_upstream)),
5040 ))
5041 .into_any_element(),
5042 ),
5043 single_example(
5044 "No Remote Upstream",
5045 div()
5046 .w(example_width)
5047 .overflow_hidden()
5048 .child(PanelRepoFooter::new_preview(
5049 active_repository(3).clone(),
5050 Some(branch(no_remote_upstream)),
5051 ))
5052 .into_any_element(),
5053 ),
5054 single_example(
5055 "Not Ahead or Behind",
5056 div()
5057 .w(example_width)
5058 .overflow_hidden()
5059 .child(PanelRepoFooter::new_preview(
5060 active_repository(4).clone(),
5061 Some(branch(not_ahead_or_behind_upstream)),
5062 ))
5063 .into_any_element(),
5064 ),
5065 single_example(
5066 "Behind remote",
5067 div()
5068 .w(example_width)
5069 .overflow_hidden()
5070 .child(PanelRepoFooter::new_preview(
5071 active_repository(5).clone(),
5072 Some(branch(behind_upstream)),
5073 ))
5074 .into_any_element(),
5075 ),
5076 single_example(
5077 "Ahead of remote",
5078 div()
5079 .w(example_width)
5080 .overflow_hidden()
5081 .child(PanelRepoFooter::new_preview(
5082 active_repository(6).clone(),
5083 Some(branch(ahead_of_upstream)),
5084 ))
5085 .into_any_element(),
5086 ),
5087 single_example(
5088 "Ahead and behind remote",
5089 div()
5090 .w(example_width)
5091 .overflow_hidden()
5092 .child(PanelRepoFooter::new_preview(
5093 active_repository(7).clone(),
5094 Some(branch(ahead_and_behind_upstream)),
5095 ))
5096 .into_any_element(),
5097 ),
5098 ],
5099 )
5100 .grow()
5101 .vertical(),
5102 ])
5103 .children(vec![
5104 example_group_with_title(
5105 "Labels",
5106 vec![
5107 single_example(
5108 "Short Branch & Repo",
5109 div()
5110 .w(example_width)
5111 .overflow_hidden()
5112 .child(PanelRepoFooter::new_preview(
5113 SharedString::from("zed"),
5114 Some(custom("main", behind_upstream)),
5115 ))
5116 .into_any_element(),
5117 ),
5118 single_example(
5119 "Long Branch",
5120 div()
5121 .w(example_width)
5122 .overflow_hidden()
5123 .child(PanelRepoFooter::new_preview(
5124 SharedString::from("zed"),
5125 Some(custom(
5126 "redesign-and-update-git-ui-list-entry-style",
5127 behind_upstream,
5128 )),
5129 ))
5130 .into_any_element(),
5131 ),
5132 single_example(
5133 "Long Repo",
5134 div()
5135 .w(example_width)
5136 .overflow_hidden()
5137 .child(PanelRepoFooter::new_preview(
5138 SharedString::from("zed-industries-community-examples"),
5139 Some(custom("gpui", ahead_of_upstream)),
5140 ))
5141 .into_any_element(),
5142 ),
5143 single_example(
5144 "Long Repo & Branch",
5145 div()
5146 .w(example_width)
5147 .overflow_hidden()
5148 .child(PanelRepoFooter::new_preview(
5149 SharedString::from("zed-industries-community-examples"),
5150 Some(custom(
5151 "redesign-and-update-git-ui-list-entry-style",
5152 behind_upstream,
5153 )),
5154 ))
5155 .into_any_element(),
5156 ),
5157 single_example(
5158 "Uppercase Repo",
5159 div()
5160 .w(example_width)
5161 .overflow_hidden()
5162 .child(PanelRepoFooter::new_preview(
5163 SharedString::from("LICENSES"),
5164 Some(custom("main", ahead_of_upstream)),
5165 ))
5166 .into_any_element(),
5167 ),
5168 single_example(
5169 "Uppercase Branch",
5170 div()
5171 .w(example_width)
5172 .overflow_hidden()
5173 .child(PanelRepoFooter::new_preview(
5174 SharedString::from("zed"),
5175 Some(custom("update-README", behind_upstream)),
5176 ))
5177 .into_any_element(),
5178 ),
5179 ],
5180 )
5181 .grow()
5182 .vertical(),
5183 ])
5184 .into_any_element(),
5185 )
5186 }
5187}
5188
5189#[cfg(test)]
5190mod tests {
5191 use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
5192 use gpui::{TestAppContext, VisualTestContext};
5193 use project::{FakeFs, WorktreeSettings};
5194 use serde_json::json;
5195 use settings::SettingsStore;
5196 use theme::LoadThemes;
5197 use util::path;
5198
5199 use super::*;
5200
5201 fn init_test(cx: &mut gpui::TestAppContext) {
5202 zlog::init_test();
5203
5204 cx.update(|cx| {
5205 let settings_store = SettingsStore::test(cx);
5206 cx.set_global(settings_store);
5207 AgentSettings::register(cx);
5208 WorktreeSettings::register(cx);
5209 workspace::init_settings(cx);
5210 theme::init(LoadThemes::JustBase, cx);
5211 language::init(cx);
5212 editor::init(cx);
5213 Project::init_settings(cx);
5214 crate::init(cx);
5215 });
5216 }
5217
5218 #[gpui::test]
5219 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5220 init_test(cx);
5221 let fs = FakeFs::new(cx.background_executor.clone());
5222 fs.insert_tree(
5223 "/root",
5224 json!({
5225 "zed": {
5226 ".git": {},
5227 "crates": {
5228 "gpui": {
5229 "gpui.rs": "fn main() {}"
5230 },
5231 "util": {
5232 "util.rs": "fn do_it() {}"
5233 }
5234 }
5235 },
5236 }),
5237 )
5238 .await;
5239
5240 fs.set_status_for_repo(
5241 Path::new(path!("/root/zed/.git")),
5242 &[
5243 (
5244 Path::new("crates/gpui/gpui.rs"),
5245 StatusCode::Modified.worktree(),
5246 ),
5247 (
5248 Path::new("crates/util/util.rs"),
5249 StatusCode::Modified.worktree(),
5250 ),
5251 ],
5252 );
5253
5254 let project =
5255 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5256 let workspace =
5257 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5258 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5259
5260 cx.read(|cx| {
5261 project
5262 .read(cx)
5263 .worktrees(cx)
5264 .nth(0)
5265 .unwrap()
5266 .read(cx)
5267 .as_local()
5268 .unwrap()
5269 .scan_complete()
5270 })
5271 .await;
5272
5273 cx.executor().run_until_parked();
5274
5275 let panel = workspace.update(cx, GitPanel::new).unwrap();
5276
5277 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5278 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5279 });
5280 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5281 handle.await;
5282
5283 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5284 pretty_assertions::assert_eq!(
5285 entries,
5286 [
5287 GitListEntry::Header(GitHeaderEntry {
5288 header: Section::Tracked
5289 }),
5290 GitListEntry::Status(GitStatusEntry {
5291 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5292 repo_path: "crates/gpui/gpui.rs".into(),
5293 status: StatusCode::Modified.worktree(),
5294 staging: StageStatus::Unstaged,
5295 }),
5296 GitListEntry::Status(GitStatusEntry {
5297 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5298 repo_path: "crates/util/util.rs".into(),
5299 status: StatusCode::Modified.worktree(),
5300 staging: StageStatus::Unstaged,
5301 },),
5302 ],
5303 );
5304
5305 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5306 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5307 });
5308 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5309 handle.await;
5310 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5311 pretty_assertions::assert_eq!(
5312 entries,
5313 [
5314 GitListEntry::Header(GitHeaderEntry {
5315 header: Section::Tracked
5316 }),
5317 GitListEntry::Status(GitStatusEntry {
5318 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5319 repo_path: "crates/gpui/gpui.rs".into(),
5320 status: StatusCode::Modified.worktree(),
5321 staging: StageStatus::Unstaged,
5322 }),
5323 GitListEntry::Status(GitStatusEntry {
5324 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5325 repo_path: "crates/util/util.rs".into(),
5326 status: StatusCode::Modified.worktree(),
5327 staging: StageStatus::Unstaged,
5328 },),
5329 ],
5330 );
5331 }
5332
5333 #[gpui::test]
5334 async fn test_bulk_staging(cx: &mut TestAppContext) {
5335 use GitListEntry::*;
5336
5337 init_test(cx);
5338 let fs = FakeFs::new(cx.background_executor.clone());
5339 fs.insert_tree(
5340 "/root",
5341 json!({
5342 "project": {
5343 ".git": {},
5344 "src": {
5345 "main.rs": "fn main() {}",
5346 "lib.rs": "pub fn hello() {}",
5347 "utils.rs": "pub fn util() {}"
5348 },
5349 "tests": {
5350 "test.rs": "fn test() {}"
5351 },
5352 "new_file.txt": "new content",
5353 "another_new.rs": "// new file",
5354 "conflict.txt": "conflicted content"
5355 }
5356 }),
5357 )
5358 .await;
5359
5360 fs.set_status_for_repo(
5361 Path::new(path!("/root/project/.git")),
5362 &[
5363 (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5364 (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5365 (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5366 (Path::new("new_file.txt"), FileStatus::Untracked),
5367 (Path::new("another_new.rs"), FileStatus::Untracked),
5368 (Path::new("src/utils.rs"), FileStatus::Untracked),
5369 (
5370 Path::new("conflict.txt"),
5371 UnmergedStatus {
5372 first_head: UnmergedStatusCode::Updated,
5373 second_head: UnmergedStatusCode::Updated,
5374 }
5375 .into(),
5376 ),
5377 ],
5378 );
5379
5380 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5381 let workspace =
5382 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5383 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5384
5385 cx.read(|cx| {
5386 project
5387 .read(cx)
5388 .worktrees(cx)
5389 .nth(0)
5390 .unwrap()
5391 .read(cx)
5392 .as_local()
5393 .unwrap()
5394 .scan_complete()
5395 })
5396 .await;
5397
5398 cx.executor().run_until_parked();
5399
5400 let panel = workspace.update(cx, GitPanel::new).unwrap();
5401
5402 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5403 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5404 });
5405 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5406 handle.await;
5407
5408 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5409 #[rustfmt::skip]
5410 pretty_assertions::assert_matches!(
5411 entries.as_slice(),
5412 &[
5413 Header(GitHeaderEntry { header: Section::Conflict }),
5414 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5415 Header(GitHeaderEntry { header: Section::Tracked }),
5416 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5417 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5418 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5419 Header(GitHeaderEntry { header: Section::New }),
5420 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5421 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5422 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5423 ],
5424 );
5425
5426 let second_status_entry = entries[3].clone();
5427 panel.update_in(cx, |panel, window, cx| {
5428 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5429 });
5430
5431 panel.update_in(cx, |panel, window, cx| {
5432 panel.selected_entry = Some(7);
5433 panel.stage_range(&git::StageRange, window, cx);
5434 });
5435
5436 cx.read(|cx| {
5437 project
5438 .read(cx)
5439 .worktrees(cx)
5440 .nth(0)
5441 .unwrap()
5442 .read(cx)
5443 .as_local()
5444 .unwrap()
5445 .scan_complete()
5446 })
5447 .await;
5448
5449 cx.executor().run_until_parked();
5450
5451 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5452 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5453 });
5454 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5455 handle.await;
5456
5457 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5458 #[rustfmt::skip]
5459 pretty_assertions::assert_matches!(
5460 entries.as_slice(),
5461 &[
5462 Header(GitHeaderEntry { header: Section::Conflict }),
5463 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5464 Header(GitHeaderEntry { header: Section::Tracked }),
5465 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5466 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5467 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5468 Header(GitHeaderEntry { header: Section::New }),
5469 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5470 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5471 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5472 ],
5473 );
5474
5475 let third_status_entry = entries[4].clone();
5476 panel.update_in(cx, |panel, window, cx| {
5477 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5478 });
5479
5480 panel.update_in(cx, |panel, window, cx| {
5481 panel.selected_entry = Some(9);
5482 panel.stage_range(&git::StageRange, window, cx);
5483 });
5484
5485 cx.read(|cx| {
5486 project
5487 .read(cx)
5488 .worktrees(cx)
5489 .nth(0)
5490 .unwrap()
5491 .read(cx)
5492 .as_local()
5493 .unwrap()
5494 .scan_complete()
5495 })
5496 .await;
5497
5498 cx.executor().run_until_parked();
5499
5500 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5501 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5502 });
5503 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5504 handle.await;
5505
5506 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5507 #[rustfmt::skip]
5508 pretty_assertions::assert_matches!(
5509 entries.as_slice(),
5510 &[
5511 Header(GitHeaderEntry { header: Section::Conflict }),
5512 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5513 Header(GitHeaderEntry { header: Section::Tracked }),
5514 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5515 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5516 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5517 Header(GitHeaderEntry { header: Section::New }),
5518 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5519 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5520 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5521 ],
5522 );
5523 }
5524}