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