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