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