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