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