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