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, 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 fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
1438 let Some(active_repository) = self.active_repository.as_ref() else {
1439 return;
1440 };
1441 let Some(branch) = active_repository.read(cx).branch.as_ref() else {
1442 return;
1443 };
1444 let Some(recent_sha) = branch
1445 .most_recent_commit
1446 .as_ref()
1447 .map(|commit| commit.sha.to_string())
1448 else {
1449 return;
1450 };
1451 if self
1452 .commit_editor
1453 .focus_handle(cx)
1454 .contains_focused(window, cx)
1455 {
1456 if !self.amend_pending {
1457 self.amend_pending = true;
1458 cx.notify();
1459 if self.commit_editor.read(cx).is_empty(cx) {
1460 let detail_task = self.load_commit_details(recent_sha, cx);
1461 cx.spawn(async move |this, cx| {
1462 if let Ok(message) = detail_task.await.map(|detail| detail.message) {
1463 this.update(cx, |this, cx| {
1464 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1465 let start = buffer.anchor_before(0);
1466 let end = buffer.anchor_after(buffer.len());
1467 buffer.edit([(start..end, message)], None, cx);
1468 });
1469 })
1470 .log_err();
1471 }
1472 })
1473 .detach();
1474 }
1475 } else {
1476 telemetry::event!("Git Amended", source = "Git Panel");
1477 self.amend_pending = false;
1478 self.commit_changes(CommitOptions { amend: true }, window, cx);
1479 }
1480 } else {
1481 cx.propagate();
1482 }
1483 }
1484
1485 fn cancel(&mut self, _: &git::Cancel, _: &mut Window, cx: &mut Context<Self>) {
1486 if self.amend_pending {
1487 self.amend_pending = false;
1488 cx.notify();
1489 }
1490 }
1491
1492 fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1493 let message = self.commit_editor.read(cx).text(cx);
1494
1495 if !message.trim().is_empty() {
1496 return Some(message);
1497 }
1498
1499 self.suggest_commit_message(cx)
1500 .filter(|message| !message.trim().is_empty())
1501 }
1502
1503 pub(crate) fn commit_changes(
1504 &mut self,
1505 options: CommitOptions,
1506 window: &mut Window,
1507 cx: &mut Context<Self>,
1508 ) {
1509 let Some(active_repository) = self.active_repository.clone() else {
1510 return;
1511 };
1512 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1513 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1514 cx.spawn(async move |_| {
1515 prompt.await.ok();
1516 })
1517 .detach();
1518 };
1519
1520 if self.has_unstaged_conflicts() {
1521 error_spawn(
1522 "There are still conflicts. You must stage these before committing",
1523 window,
1524 cx,
1525 );
1526 return;
1527 }
1528
1529 let commit_message = self.custom_or_suggested_commit_message(cx);
1530
1531 let Some(mut message) = commit_message else {
1532 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1533 return;
1534 };
1535
1536 if self.add_coauthors {
1537 self.fill_co_authors(&mut message, cx);
1538 }
1539
1540 let task = if self.has_staged_changes() {
1541 // Repository serializes all git operations, so we can just send a commit immediately
1542 let commit_task = active_repository.update(cx, |repo, cx| {
1543 repo.commit(message.into(), None, options, cx)
1544 });
1545 cx.background_spawn(async move { commit_task.await? })
1546 } else {
1547 let changed_files = self
1548 .entries
1549 .iter()
1550 .filter_map(|entry| entry.status_entry())
1551 .filter(|status_entry| !status_entry.status.is_created())
1552 .map(|status_entry| status_entry.repo_path.clone())
1553 .collect::<Vec<_>>();
1554
1555 if changed_files.is_empty() {
1556 error_spawn("No changes to commit", window, cx);
1557 return;
1558 }
1559
1560 let stage_task =
1561 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1562 cx.spawn(async move |_, cx| {
1563 stage_task.await?;
1564 let commit_task = active_repository.update(cx, |repo, cx| {
1565 repo.commit(message.into(), None, options, cx)
1566 })?;
1567 commit_task.await?
1568 })
1569 };
1570 let task = cx.spawn_in(window, async move |this, cx| {
1571 let result = task.await;
1572 this.update_in(cx, |this, window, cx| {
1573 this.pending_commit.take();
1574 match result {
1575 Ok(()) => {
1576 this.commit_editor
1577 .update(cx, |editor, cx| editor.clear(window, cx));
1578 }
1579 Err(e) => this.show_error_toast("commit", e, cx),
1580 }
1581 })
1582 .ok();
1583 });
1584
1585 self.pending_commit = Some(task);
1586 }
1587
1588 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1589 let Some(repo) = self.active_repository.clone() else {
1590 return;
1591 };
1592 telemetry::event!("Git Uncommitted");
1593
1594 let confirmation = self.check_for_pushed_commits(window, cx);
1595 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1596
1597 let task = cx.spawn_in(window, async move |this, cx| {
1598 let result = maybe!(async {
1599 if let Ok(true) = confirmation.await {
1600 let prior_head = prior_head.await?;
1601
1602 repo.update(cx, |repo, cx| {
1603 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1604 })?
1605 .await??;
1606
1607 Ok(Some(prior_head))
1608 } else {
1609 Ok(None)
1610 }
1611 })
1612 .await;
1613
1614 this.update_in(cx, |this, window, cx| {
1615 this.pending_commit.take();
1616 match result {
1617 Ok(None) => {}
1618 Ok(Some(prior_commit)) => {
1619 this.commit_editor.update(cx, |editor, cx| {
1620 editor.set_text(prior_commit.message, window, cx)
1621 });
1622 }
1623 Err(e) => this.show_error_toast("reset", e, cx),
1624 }
1625 })
1626 .ok();
1627 });
1628
1629 self.pending_commit = Some(task);
1630 }
1631
1632 fn check_for_pushed_commits(
1633 &mut self,
1634 window: &mut Window,
1635 cx: &mut Context<Self>,
1636 ) -> impl Future<Output = Result<bool, anyhow::Error>> + use<> {
1637 let repo = self.active_repository.clone();
1638 let mut cx = window.to_async(cx);
1639
1640 async move {
1641 let Some(repo) = repo else {
1642 return Err(anyhow::anyhow!("No active repository"));
1643 };
1644
1645 let pushed_to: Vec<SharedString> = repo
1646 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1647 .await??;
1648
1649 if pushed_to.is_empty() {
1650 Ok(true)
1651 } else {
1652 #[derive(strum::EnumIter, strum::VariantNames)]
1653 #[strum(serialize_all = "title_case")]
1654 enum CancelUncommit {
1655 Uncommit,
1656 Cancel,
1657 }
1658 let detail = format!(
1659 "This commit was already pushed to {}.",
1660 pushed_to.into_iter().join(", ")
1661 );
1662 let result = cx
1663 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1664 .await?;
1665
1666 match result {
1667 CancelUncommit::Cancel => Ok(false),
1668 CancelUncommit::Uncommit => Ok(true),
1669 }
1670 }
1671 }
1672 }
1673
1674 /// Suggests a commit message based on the changed files and their statuses
1675 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1676 if let Some(merge_message) = self
1677 .active_repository
1678 .as_ref()
1679 .and_then(|repo| repo.read(cx).merge_message.as_ref())
1680 {
1681 return Some(merge_message.to_string());
1682 }
1683
1684 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1685 Some(staged_entry)
1686 } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1687 Some(single_tracked_entry)
1688 } else {
1689 None
1690 }?;
1691
1692 let action_text = if git_status_entry.status.is_deleted() {
1693 Some("Delete")
1694 } else if git_status_entry.status.is_created() {
1695 Some("Create")
1696 } else if git_status_entry.status.is_modified() {
1697 Some("Update")
1698 } else {
1699 None
1700 }?;
1701
1702 let file_name = git_status_entry
1703 .repo_path
1704 .file_name()
1705 .unwrap_or_default()
1706 .to_string_lossy();
1707
1708 Some(format!("{} {}", action_text, file_name))
1709 }
1710
1711 fn generate_commit_message_action(
1712 &mut self,
1713 _: &git::GenerateCommitMessage,
1714 _window: &mut Window,
1715 cx: &mut Context<Self>,
1716 ) {
1717 self.generate_commit_message(cx);
1718 }
1719
1720 /// Generates a commit message using an LLM.
1721 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1722 if !self.can_commit() {
1723 return;
1724 }
1725
1726 let model = match current_language_model(cx) {
1727 Some(value) => value,
1728 None => return,
1729 };
1730
1731 let Some(repo) = self.active_repository.as_ref() else {
1732 return;
1733 };
1734
1735 telemetry::event!("Git Commit Message Generated");
1736
1737 let diff = repo.update(cx, |repo, cx| {
1738 if self.has_staged_changes() {
1739 repo.diff(DiffType::HeadToIndex, cx)
1740 } else {
1741 repo.diff(DiffType::HeadToWorktree, cx)
1742 }
1743 });
1744
1745 self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1746 async move {
1747 let _defer = cx.on_drop(&this, |this, _cx| {
1748 this.generate_commit_message_task.take();
1749 });
1750
1751 let mut diff_text = diff.await??;
1752
1753 const ONE_MB: usize = 1_000_000;
1754 if diff_text.len() > ONE_MB {
1755 diff_text = diff_text.chars().take(ONE_MB).collect()
1756 }
1757
1758 let subject = this.update(cx, |this, cx| {
1759 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1760 })?;
1761
1762 let text_empty = subject.trim().is_empty();
1763
1764 let content = if text_empty {
1765 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1766 } else {
1767 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1768 };
1769
1770 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1771
1772 let request = LanguageModelRequest {
1773 messages: vec![LanguageModelRequestMessage {
1774 role: Role::User,
1775 content: vec![content.into()],
1776 cache: false,
1777 }],
1778 tools: Vec::new(),
1779 stop: Vec::new(),
1780 temperature: None,
1781 };
1782
1783 let stream = model.stream_completion_text(request, &cx);
1784 let mut messages = stream.await?;
1785
1786 if !text_empty {
1787 this.update(cx, |this, cx| {
1788 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1789 let insert_position = buffer.anchor_before(buffer.len());
1790 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1791 });
1792 })?;
1793 }
1794
1795 while let Some(message) = messages.stream.next().await {
1796 let text = message?;
1797
1798 this.update(cx, |this, cx| {
1799 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1800 let insert_position = buffer.anchor_before(buffer.len());
1801 buffer.edit([(insert_position..insert_position, text)], None, cx);
1802 });
1803 })?;
1804 }
1805
1806 anyhow::Ok(())
1807 }
1808 .log_err().await
1809 }));
1810 }
1811
1812 pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1813 if !self.can_push_and_pull(cx) {
1814 return;
1815 }
1816
1817 let Some(repo) = self.active_repository.clone() else {
1818 return;
1819 };
1820 telemetry::event!("Git Fetched");
1821 let askpass = self.askpass_delegate("git fetch", window, cx);
1822 let this = cx.weak_entity();
1823 window
1824 .spawn(cx, async move |cx| {
1825 let fetch = repo.update(cx, |repo, cx| repo.fetch(askpass, cx))?;
1826
1827 let remote_message = fetch.await?;
1828 this.update(cx, |this, cx| {
1829 let action = RemoteAction::Fetch;
1830 match remote_message {
1831 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1832 Err(e) => {
1833 log::error!("Error while fetching {:?}", e);
1834 this.show_error_toast(action.name(), e, cx)
1835 }
1836 }
1837
1838 anyhow::Ok(())
1839 })
1840 .ok();
1841 anyhow::Ok(())
1842 })
1843 .detach_and_log_err(cx);
1844 }
1845
1846 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1847 let worktrees = self
1848 .project
1849 .read(cx)
1850 .visible_worktrees(cx)
1851 .collect::<Vec<_>>();
1852
1853 let worktree = if worktrees.len() == 1 {
1854 Task::ready(Some(worktrees.first().unwrap().clone()))
1855 } else if worktrees.len() == 0 {
1856 let result = window.prompt(
1857 PromptLevel::Warning,
1858 "Unable to initialize a git repository",
1859 Some("Open a directory first"),
1860 &["Ok"],
1861 cx,
1862 );
1863 cx.background_executor()
1864 .spawn(async move {
1865 result.await.ok();
1866 })
1867 .detach();
1868 return;
1869 } else {
1870 let worktree_directories = worktrees
1871 .iter()
1872 .map(|worktree| worktree.read(cx).abs_path())
1873 .map(|worktree_abs_path| {
1874 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1875 Path::new("~")
1876 .join(path)
1877 .to_string_lossy()
1878 .to_string()
1879 .into()
1880 } else {
1881 worktree_abs_path.to_string_lossy().to_string().into()
1882 }
1883 })
1884 .collect_vec();
1885 let prompt = picker_prompt::prompt(
1886 "Where would you like to initialize this git repository?",
1887 worktree_directories,
1888 self.workspace.clone(),
1889 window,
1890 cx,
1891 );
1892
1893 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
1894 };
1895
1896 cx.spawn_in(window, async move |this, cx| {
1897 let worktree = match worktree.await {
1898 Some(worktree) => worktree,
1899 None => {
1900 return;
1901 }
1902 };
1903
1904 let Ok(result) = this.update(cx, |this, cx| {
1905 let fallback_branch_name = GitPanelSettings::get_global(cx)
1906 .fallback_branch_name
1907 .clone();
1908 this.project.read(cx).git_init(
1909 worktree.read(cx).abs_path(),
1910 fallback_branch_name,
1911 cx,
1912 )
1913 }) else {
1914 return;
1915 };
1916
1917 let result = result.await;
1918
1919 this.update_in(cx, |this, _, cx| match result {
1920 Ok(()) => {}
1921 Err(e) => this.show_error_toast("init", e, cx),
1922 })
1923 .ok();
1924 })
1925 .detach();
1926 }
1927
1928 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1929 if !self.can_push_and_pull(cx) {
1930 return;
1931 }
1932 let Some(repo) = self.active_repository.clone() else {
1933 return;
1934 };
1935 let Some(branch) = repo.read(cx).branch.as_ref() else {
1936 return;
1937 };
1938 telemetry::event!("Git Pulled");
1939 let branch = branch.clone();
1940 let remote = self.get_current_remote(window, cx);
1941 cx.spawn_in(window, async move |this, cx| {
1942 let remote = match remote.await {
1943 Ok(Some(remote)) => remote,
1944 Ok(None) => {
1945 return Ok(());
1946 }
1947 Err(e) => {
1948 log::error!("Failed to get current remote: {}", e);
1949 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
1950 .ok();
1951 return Ok(());
1952 }
1953 };
1954
1955 let askpass = this.update_in(cx, |this, window, cx| {
1956 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1957 })?;
1958
1959 let pull = repo.update(cx, |repo, cx| {
1960 repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1961 })?;
1962
1963 let remote_message = pull.await?;
1964
1965 let action = RemoteAction::Pull(remote);
1966 this.update(cx, |this, cx| match remote_message {
1967 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1968 Err(e) => {
1969 log::error!("Error while pulling {:?}", e);
1970 this.show_error_toast(action.name(), e, cx)
1971 }
1972 })
1973 .ok();
1974
1975 anyhow::Ok(())
1976 })
1977 .detach_and_log_err(cx);
1978 }
1979
1980 pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1981 if !self.can_push_and_pull(cx) {
1982 return;
1983 }
1984 let Some(repo) = self.active_repository.clone() else {
1985 return;
1986 };
1987 let Some(branch) = repo.read(cx).branch.as_ref() else {
1988 return;
1989 };
1990 telemetry::event!("Git Pushed");
1991 let branch = branch.clone();
1992
1993 let options = if force_push {
1994 Some(PushOptions::Force)
1995 } else {
1996 match branch.upstream {
1997 Some(Upstream {
1998 tracking: UpstreamTracking::Gone,
1999 ..
2000 })
2001 | None => Some(PushOptions::SetUpstream),
2002 _ => None,
2003 }
2004 };
2005 let remote = self.get_current_remote(window, cx);
2006
2007 cx.spawn_in(window, async move |this, cx| {
2008 let remote = match remote.await {
2009 Ok(Some(remote)) => remote,
2010 Ok(None) => {
2011 return Ok(());
2012 }
2013 Err(e) => {
2014 log::error!("Failed to get current remote: {}", e);
2015 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2016 .ok();
2017 return Ok(());
2018 }
2019 };
2020
2021 let askpass_delegate = this.update_in(cx, |this, window, cx| {
2022 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2023 })?;
2024
2025 let push = repo.update(cx, |repo, cx| {
2026 repo.push(
2027 branch.name.clone(),
2028 remote.name.clone(),
2029 options,
2030 askpass_delegate,
2031 cx,
2032 )
2033 })?;
2034
2035 let remote_output = push.await?;
2036
2037 let action = RemoteAction::Push(branch.name, remote);
2038 this.update(cx, |this, cx| match remote_output {
2039 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2040 Err(e) => {
2041 log::error!("Error while pushing {:?}", e);
2042 this.show_error_toast(action.name(), e, cx)
2043 }
2044 })?;
2045
2046 anyhow::Ok(())
2047 })
2048 .detach_and_log_err(cx);
2049 }
2050
2051 fn askpass_delegate(
2052 &self,
2053 operation: impl Into<SharedString>,
2054 window: &mut Window,
2055 cx: &mut Context<Self>,
2056 ) -> AskPassDelegate {
2057 let this = cx.weak_entity();
2058 let operation = operation.into();
2059 let window = window.window_handle();
2060 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2061 window
2062 .update(cx, |_, window, cx| {
2063 this.update(cx, |this, cx| {
2064 this.workspace.update(cx, |workspace, cx| {
2065 workspace.toggle_modal(window, cx, |window, cx| {
2066 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2067 });
2068 })
2069 })
2070 })
2071 .ok();
2072 })
2073 }
2074
2075 fn can_push_and_pull(&self, cx: &App) -> bool {
2076 !self.project.read(cx).is_via_collab()
2077 }
2078
2079 fn get_current_remote(
2080 &mut self,
2081 window: &mut Window,
2082 cx: &mut Context<Self>,
2083 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2084 let repo = self.active_repository.clone();
2085 let workspace = self.workspace.clone();
2086 let mut cx = window.to_async(cx);
2087
2088 async move {
2089 let Some(repo) = repo else {
2090 return Err(anyhow::anyhow!("No active repository"));
2091 };
2092
2093 let mut current_remotes: Vec<Remote> = repo
2094 .update(&mut cx, |repo, _| {
2095 let Some(current_branch) = repo.branch.as_ref() else {
2096 return Err(anyhow::anyhow!("No active branch"));
2097 };
2098
2099 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
2100 })??
2101 .await??;
2102
2103 if current_remotes.len() == 0 {
2104 return Err(anyhow::anyhow!("No active remote"));
2105 } else if current_remotes.len() == 1 {
2106 return Ok(Some(current_remotes.pop().unwrap()));
2107 } else {
2108 let current_remotes: Vec<_> = current_remotes
2109 .into_iter()
2110 .map(|remotes| remotes.name)
2111 .collect();
2112 let selection = cx
2113 .update(|window, cx| {
2114 picker_prompt::prompt(
2115 "Pick which remote to push to",
2116 current_remotes.clone(),
2117 workspace,
2118 window,
2119 cx,
2120 )
2121 })?
2122 .await;
2123
2124 Ok(selection.map(|selection| Remote {
2125 name: current_remotes[selection].clone(),
2126 }))
2127 }
2128 }
2129 }
2130
2131 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2132 let mut new_co_authors = Vec::new();
2133 let project = self.project.read(cx);
2134
2135 let Some(room) = self
2136 .workspace
2137 .upgrade()
2138 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2139 else {
2140 return Vec::default();
2141 };
2142
2143 let room = room.read(cx);
2144
2145 for (peer_id, collaborator) in project.collaborators() {
2146 if collaborator.is_host {
2147 continue;
2148 }
2149
2150 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2151 continue;
2152 };
2153 if participant.can_write() && participant.user.email.is_some() {
2154 let email = participant.user.email.clone().unwrap();
2155
2156 new_co_authors.push((
2157 participant
2158 .user
2159 .name
2160 .clone()
2161 .unwrap_or_else(|| participant.user.github_login.clone()),
2162 email,
2163 ))
2164 }
2165 }
2166 if !project.is_local() && !project.is_read_only(cx) {
2167 if let Some(user) = room.local_participant_user(cx) {
2168 if let Some(email) = user.email.clone() {
2169 new_co_authors.push((
2170 user.name
2171 .clone()
2172 .unwrap_or_else(|| user.github_login.clone()),
2173 email.clone(),
2174 ))
2175 }
2176 }
2177 }
2178 new_co_authors
2179 }
2180
2181 fn toggle_fill_co_authors(
2182 &mut self,
2183 _: &ToggleFillCoAuthors,
2184 _: &mut Window,
2185 cx: &mut Context<Self>,
2186 ) {
2187 self.add_coauthors = !self.add_coauthors;
2188 cx.notify();
2189 }
2190
2191 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2192 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2193
2194 let existing_text = message.to_ascii_lowercase();
2195 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2196 let mut ends_with_co_authors = false;
2197 let existing_co_authors = existing_text
2198 .lines()
2199 .filter_map(|line| {
2200 let line = line.trim();
2201 if line.starts_with(&lowercase_co_author_prefix) {
2202 ends_with_co_authors = true;
2203 Some(line)
2204 } else {
2205 ends_with_co_authors = false;
2206 None
2207 }
2208 })
2209 .collect::<HashSet<_>>();
2210
2211 let new_co_authors = self
2212 .potential_co_authors(cx)
2213 .into_iter()
2214 .filter(|(_, email)| {
2215 !existing_co_authors
2216 .iter()
2217 .any(|existing| existing.contains(email.as_str()))
2218 })
2219 .collect::<Vec<_>>();
2220
2221 if new_co_authors.is_empty() {
2222 return;
2223 }
2224
2225 if !ends_with_co_authors {
2226 message.push('\n');
2227 }
2228 for (name, email) in new_co_authors {
2229 message.push('\n');
2230 message.push_str(CO_AUTHOR_PREFIX);
2231 message.push_str(&name);
2232 message.push_str(" <");
2233 message.push_str(&email);
2234 message.push('>');
2235 }
2236 message.push('\n');
2237 }
2238
2239 fn schedule_update(
2240 &mut self,
2241 clear_pending: bool,
2242 window: &mut Window,
2243 cx: &mut Context<Self>,
2244 ) {
2245 let handle = cx.entity().downgrade();
2246 self.reopen_commit_buffer(window, cx);
2247 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2248 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2249 if let Some(git_panel) = handle.upgrade() {
2250 git_panel
2251 .update_in(cx, |git_panel, window, cx| {
2252 if clear_pending {
2253 git_panel.clear_pending();
2254 }
2255 git_panel.update_visible_entries(cx);
2256 git_panel.update_scrollbar_properties(window, cx);
2257 })
2258 .ok();
2259 }
2260 });
2261 }
2262
2263 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2264 let Some(active_repo) = self.active_repository.as_ref() else {
2265 return;
2266 };
2267 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2268 let project = self.project.read(cx);
2269 active_repo.open_commit_buffer(
2270 Some(project.languages().clone()),
2271 project.buffer_store().clone(),
2272 cx,
2273 )
2274 });
2275
2276 cx.spawn_in(window, async move |git_panel, cx| {
2277 let buffer = load_buffer.await?;
2278 git_panel.update_in(cx, |git_panel, window, cx| {
2279 if git_panel
2280 .commit_editor
2281 .read(cx)
2282 .buffer()
2283 .read(cx)
2284 .as_singleton()
2285 .as_ref()
2286 != Some(&buffer)
2287 {
2288 git_panel.commit_editor = cx.new(|cx| {
2289 commit_message_editor(
2290 buffer,
2291 git_panel.suggest_commit_message(cx).map(SharedString::from),
2292 git_panel.project.clone(),
2293 true,
2294 window,
2295 cx,
2296 )
2297 });
2298 }
2299 })
2300 })
2301 .detach_and_log_err(cx);
2302 }
2303
2304 fn clear_pending(&mut self) {
2305 self.pending.retain(|v| !v.finished)
2306 }
2307
2308 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2309 self.entries.clear();
2310 self.single_staged_entry.take();
2311 self.single_tracked_entry.take();
2312 self.conflicted_count = 0;
2313 self.conflicted_staged_count = 0;
2314 self.new_count = 0;
2315 self.tracked_count = 0;
2316 self.new_staged_count = 0;
2317 self.tracked_staged_count = 0;
2318 self.entry_count = 0;
2319
2320 let mut changed_entries = Vec::new();
2321 let mut new_entries = Vec::new();
2322 let mut conflict_entries = Vec::new();
2323 let mut last_staged = None;
2324 let mut staged_count = 0;
2325 let mut max_width_item: Option<(RepoPath, usize)> = None;
2326
2327 let Some(repo) = self.active_repository.as_ref() else {
2328 // Just clear entries if no repository is active.
2329 cx.notify();
2330 return;
2331 };
2332
2333 let repo = repo.read(cx);
2334
2335 for entry in repo.cached_status() {
2336 let is_conflict = repo.has_conflict(&entry.repo_path);
2337 let is_new = entry.status.is_created();
2338 let staging = entry.status.staging();
2339
2340 if self.pending.iter().any(|pending| {
2341 pending.target_status == TargetStatus::Reverted
2342 && !pending.finished
2343 && pending
2344 .entries
2345 .iter()
2346 .any(|pending| pending.repo_path == entry.repo_path)
2347 }) {
2348 continue;
2349 }
2350
2351 let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2352 let entry = GitStatusEntry {
2353 repo_path: entry.repo_path.clone(),
2354 abs_path,
2355 status: entry.status,
2356 staging,
2357 };
2358
2359 if staging.has_staged() {
2360 staged_count += 1;
2361 last_staged = Some(entry.clone());
2362 }
2363
2364 let width_estimate = Self::item_width_estimate(
2365 entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2366 entry.display_name().len(),
2367 );
2368
2369 match max_width_item.as_mut() {
2370 Some((repo_path, estimate)) => {
2371 if width_estimate > *estimate {
2372 *repo_path = entry.repo_path.clone();
2373 *estimate = width_estimate;
2374 }
2375 }
2376 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2377 }
2378
2379 if is_conflict {
2380 conflict_entries.push(entry);
2381 } else if is_new {
2382 new_entries.push(entry);
2383 } else {
2384 changed_entries.push(entry);
2385 }
2386 }
2387
2388 let mut pending_staged_count = 0;
2389 let mut last_pending_staged = None;
2390 let mut pending_status_for_last_staged = None;
2391 for pending in self.pending.iter() {
2392 if pending.target_status == TargetStatus::Staged {
2393 pending_staged_count += pending.entries.len();
2394 last_pending_staged = pending.entries.iter().next().cloned();
2395 }
2396 if let Some(last_staged) = &last_staged {
2397 if pending
2398 .entries
2399 .iter()
2400 .any(|entry| entry.repo_path == last_staged.repo_path)
2401 {
2402 pending_status_for_last_staged = Some(pending.target_status);
2403 }
2404 }
2405 }
2406
2407 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2408 match pending_status_for_last_staged {
2409 Some(TargetStatus::Staged) | None => {
2410 self.single_staged_entry = last_staged;
2411 }
2412 _ => {}
2413 }
2414 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2415 self.single_staged_entry = last_pending_staged;
2416 }
2417
2418 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2419 self.single_tracked_entry = changed_entries.first().cloned();
2420 }
2421
2422 if conflict_entries.len() > 0 {
2423 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2424 header: Section::Conflict,
2425 }));
2426 self.entries.extend(
2427 conflict_entries
2428 .into_iter()
2429 .map(GitListEntry::GitStatusEntry),
2430 );
2431 }
2432
2433 if changed_entries.len() > 0 {
2434 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2435 header: Section::Tracked,
2436 }));
2437 self.entries.extend(
2438 changed_entries
2439 .into_iter()
2440 .map(GitListEntry::GitStatusEntry),
2441 );
2442 }
2443 if new_entries.len() > 0 {
2444 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2445 header: Section::New,
2446 }));
2447 self.entries
2448 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2449 }
2450
2451 if let Some((repo_path, _)) = max_width_item {
2452 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2453 GitListEntry::GitStatusEntry(git_status_entry) => {
2454 git_status_entry.repo_path == repo_path
2455 }
2456 GitListEntry::Header(_) => false,
2457 });
2458 }
2459
2460 self.update_counts(repo);
2461
2462 self.select_first_entry_if_none(cx);
2463
2464 let suggested_commit_message = self.suggest_commit_message(cx);
2465 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2466
2467 self.commit_editor.update(cx, |editor, cx| {
2468 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2469 });
2470
2471 cx.notify();
2472 }
2473
2474 fn header_state(&self, header_type: Section) -> ToggleState {
2475 let (staged_count, count) = match header_type {
2476 Section::New => (self.new_staged_count, self.new_count),
2477 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2478 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2479 };
2480 if staged_count == 0 {
2481 ToggleState::Unselected
2482 } else if count == staged_count {
2483 ToggleState::Selected
2484 } else {
2485 ToggleState::Indeterminate
2486 }
2487 }
2488
2489 fn update_counts(&mut self, repo: &Repository) {
2490 self.conflicted_count = 0;
2491 self.conflicted_staged_count = 0;
2492 self.new_count = 0;
2493 self.tracked_count = 0;
2494 self.new_staged_count = 0;
2495 self.tracked_staged_count = 0;
2496 self.entry_count = 0;
2497 for entry in &self.entries {
2498 let Some(status_entry) = entry.status_entry() else {
2499 continue;
2500 };
2501 self.entry_count += 1;
2502 if repo.has_conflict(&status_entry.repo_path) {
2503 self.conflicted_count += 1;
2504 if self.entry_staging(status_entry).has_staged() {
2505 self.conflicted_staged_count += 1;
2506 }
2507 } else if status_entry.status.is_created() {
2508 self.new_count += 1;
2509 if self.entry_staging(status_entry).has_staged() {
2510 self.new_staged_count += 1;
2511 }
2512 } else {
2513 self.tracked_count += 1;
2514 if self.entry_staging(status_entry).has_staged() {
2515 self.tracked_staged_count += 1;
2516 }
2517 }
2518 }
2519 }
2520
2521 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2522 for pending in self.pending.iter().rev() {
2523 if pending
2524 .entries
2525 .iter()
2526 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2527 {
2528 match pending.target_status {
2529 TargetStatus::Staged => return StageStatus::Staged,
2530 TargetStatus::Unstaged => return StageStatus::Unstaged,
2531 TargetStatus::Reverted => continue,
2532 TargetStatus::Unchanged => continue,
2533 }
2534 }
2535 }
2536 entry.staging
2537 }
2538
2539 pub(crate) fn has_staged_changes(&self) -> bool {
2540 self.tracked_staged_count > 0
2541 || self.new_staged_count > 0
2542 || self.conflicted_staged_count > 0
2543 }
2544
2545 pub(crate) fn has_unstaged_changes(&self) -> bool {
2546 self.tracked_count > self.tracked_staged_count
2547 || self.new_count > self.new_staged_count
2548 || self.conflicted_count > self.conflicted_staged_count
2549 }
2550
2551 fn has_conflicts(&self) -> bool {
2552 self.conflicted_count > 0
2553 }
2554
2555 fn has_tracked_changes(&self) -> bool {
2556 self.tracked_count > 0
2557 }
2558
2559 pub fn has_unstaged_conflicts(&self) -> bool {
2560 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2561 }
2562
2563 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2564 let action = action.into();
2565 let Some(workspace) = self.workspace.upgrade() else {
2566 return;
2567 };
2568
2569 let message = e.to_string().trim().to_string();
2570 if message
2571 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2572 .next()
2573 .is_some()
2574 {
2575 return; // Hide the cancelled by user message
2576 } else {
2577 workspace.update(cx, |workspace, cx| {
2578 let workspace_weak = cx.weak_entity();
2579 let toast =
2580 StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2581 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2582 .action("View Log", move |window, cx| {
2583 let message = message.clone();
2584 let action = action.clone();
2585 workspace_weak
2586 .update(cx, move |workspace, cx| {
2587 Self::open_output(action, workspace, &message, window, cx)
2588 })
2589 .ok();
2590 })
2591 });
2592 workspace.toggle_status_toast(toast, cx)
2593 });
2594 }
2595 }
2596
2597 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2598 let Some(workspace) = self.workspace.upgrade() else {
2599 return;
2600 };
2601
2602 workspace.update(cx, |workspace, cx| {
2603 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2604 let workspace_weak = cx.weak_entity();
2605 let operation = action.name();
2606
2607 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2608 use remote_output::SuccessStyle::*;
2609 match style {
2610 Toast { .. } => this,
2611 ToastWithLog { output } => this
2612 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2613 .action("View Log", move |window, cx| {
2614 let output = output.clone();
2615 let output =
2616 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2617 workspace_weak
2618 .update(cx, move |workspace, cx| {
2619 Self::open_output(operation, workspace, &output, window, cx)
2620 })
2621 .ok();
2622 }),
2623 PushPrLink { link } => this
2624 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2625 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2626 }
2627 });
2628 workspace.toggle_status_toast(status_toast, cx)
2629 });
2630 }
2631
2632 fn open_output(
2633 operation: impl Into<SharedString>,
2634 workspace: &mut Workspace,
2635 output: &str,
2636 window: &mut Window,
2637 cx: &mut Context<Workspace>,
2638 ) {
2639 let operation = operation.into();
2640 let buffer = cx.new(|cx| Buffer::local(output, cx));
2641 buffer.update(cx, |buffer, cx| {
2642 buffer.set_capability(language::Capability::ReadOnly, cx);
2643 });
2644 let editor = cx.new(|cx| {
2645 let mut editor = Editor::for_buffer(buffer, None, window, cx);
2646 editor.buffer().update(cx, |buffer, cx| {
2647 buffer.set_title(format!("Output from git {operation}"), cx);
2648 });
2649 editor.set_read_only(true);
2650 editor
2651 });
2652
2653 workspace.add_item_to_center(Box::new(editor), window, cx);
2654 }
2655
2656 pub fn can_commit(&self) -> bool {
2657 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2658 }
2659
2660 pub fn can_stage_all(&self) -> bool {
2661 self.has_unstaged_changes()
2662 }
2663
2664 pub fn can_unstage_all(&self) -> bool {
2665 self.has_staged_changes()
2666 }
2667
2668 // eventually we'll need to take depth into account here
2669 // if we add a tree view
2670 fn item_width_estimate(path: usize, file_name: usize) -> usize {
2671 path + file_name
2672 }
2673
2674 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2675 let focus_handle = self.focus_handle.clone();
2676 let has_tracked_changes = self.has_tracked_changes();
2677 let has_staged_changes = self.has_staged_changes();
2678 let has_unstaged_changes = self.has_unstaged_changes();
2679 let has_new_changes = self.new_count > 0;
2680
2681 PopoverMenu::new(id.into())
2682 .trigger(
2683 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2684 .icon_size(IconSize::Small)
2685 .icon_color(Color::Muted),
2686 )
2687 .menu(move |window, cx| {
2688 Some(git_panel_context_menu(
2689 focus_handle.clone(),
2690 GitMenuState {
2691 has_tracked_changes,
2692 has_staged_changes,
2693 has_unstaged_changes,
2694 has_new_changes,
2695 },
2696 window,
2697 cx,
2698 ))
2699 })
2700 .anchor(Corner::TopRight)
2701 }
2702
2703 pub(crate) fn render_generate_commit_message_button(
2704 &self,
2705 cx: &Context<Self>,
2706 ) -> Option<AnyElement> {
2707 current_language_model(cx).is_some().then(|| {
2708 if self.generate_commit_message_task.is_some() {
2709 return h_flex()
2710 .gap_1()
2711 .child(
2712 Icon::new(IconName::ArrowCircle)
2713 .size(IconSize::XSmall)
2714 .color(Color::Info)
2715 .with_animation(
2716 "arrow-circle",
2717 Animation::new(Duration::from_secs(2)).repeat(),
2718 |icon, delta| {
2719 icon.transform(Transformation::rotate(percentage(delta)))
2720 },
2721 ),
2722 )
2723 .child(
2724 Label::new("Generating Commit...")
2725 .size(LabelSize::Small)
2726 .color(Color::Muted),
2727 )
2728 .into_any_element();
2729 }
2730
2731 let can_commit = self.can_commit();
2732 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2733 IconButton::new("generate-commit-message", IconName::AiEdit)
2734 .shape(ui::IconButtonShape::Square)
2735 .icon_color(Color::Muted)
2736 .tooltip(move |window, cx| {
2737 if can_commit {
2738 Tooltip::for_action_in(
2739 "Generate Commit Message",
2740 &git::GenerateCommitMessage,
2741 &editor_focus_handle,
2742 window,
2743 cx,
2744 )
2745 } else {
2746 Tooltip::simple("No changes to commit", cx)
2747 }
2748 })
2749 .disabled(!can_commit)
2750 .on_click(cx.listener(move |this, _event, _window, cx| {
2751 this.generate_commit_message(cx);
2752 }))
2753 .into_any_element()
2754 })
2755 }
2756
2757 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2758 let potential_co_authors = self.potential_co_authors(cx);
2759 if potential_co_authors.is_empty() {
2760 None
2761 } else {
2762 Some(
2763 IconButton::new("co-authors", IconName::Person)
2764 .shape(ui::IconButtonShape::Square)
2765 .icon_color(Color::Disabled)
2766 .selected_icon_color(Color::Selected)
2767 .toggle_state(self.add_coauthors)
2768 .tooltip(move |_, cx| {
2769 let title = format!(
2770 "Add co-authored-by:{}{}",
2771 if potential_co_authors.len() == 1 {
2772 ""
2773 } else {
2774 "\n"
2775 },
2776 potential_co_authors
2777 .iter()
2778 .map(|(name, email)| format!(" {} <{}>", name, email))
2779 .join("\n")
2780 );
2781 Tooltip::simple(title, cx)
2782 })
2783 .on_click(cx.listener(|this, _, _, cx| {
2784 this.add_coauthors = !this.add_coauthors;
2785 cx.notify();
2786 }))
2787 .into_any_element(),
2788 )
2789 }
2790 }
2791
2792 fn render_git_commit_menu(
2793 &self,
2794 id: impl Into<ElementId>,
2795 keybinding_target: Option<FocusHandle>,
2796 ) -> impl IntoElement {
2797 PopoverMenu::new(id.into())
2798 .trigger(
2799 ui::ButtonLike::new_rounded_right("commit-split-button-right")
2800 .layer(ui::ElevationIndex::ModalSurface)
2801 .size(ui::ButtonSize::None)
2802 .child(
2803 div()
2804 .px_1()
2805 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
2806 ),
2807 )
2808 .menu(move |window, cx| {
2809 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
2810 context_menu
2811 .when_some(keybinding_target.clone(), |el, keybinding_target| {
2812 el.context(keybinding_target.clone())
2813 })
2814 .action("Amend...", Amend.boxed_clone())
2815 }))
2816 })
2817 .anchor(Corner::TopRight)
2818 }
2819
2820 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2821 if self.has_unstaged_conflicts() {
2822 (false, "You must resolve conflicts before committing")
2823 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2824 (false, "No changes to commit")
2825 } else if self.pending_commit.is_some() {
2826 (false, "Commit in progress")
2827 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2828 (false, "No commit message")
2829 } else if !self.has_write_access(cx) {
2830 (false, "You do not have write access to this project")
2831 } else {
2832 (true, self.commit_button_title())
2833 }
2834 }
2835
2836 pub fn commit_button_title(&self) -> &'static str {
2837 if self.amend_pending {
2838 if self.has_staged_changes() {
2839 "Amend"
2840 } else {
2841 "Amend Tracked"
2842 }
2843 } else {
2844 if self.has_staged_changes() {
2845 "Commit"
2846 } else {
2847 "Commit Tracked"
2848 }
2849 }
2850 }
2851
2852 fn expand_commit_editor(
2853 &mut self,
2854 _: &git::ExpandCommitEditor,
2855 window: &mut Window,
2856 cx: &mut Context<Self>,
2857 ) {
2858 let workspace = self.workspace.clone();
2859 window.defer(cx, move |window, cx| {
2860 workspace
2861 .update(cx, |workspace, cx| {
2862 CommitModal::toggle(workspace, window, cx)
2863 })
2864 .ok();
2865 })
2866 }
2867
2868 fn render_panel_header(
2869 &self,
2870 window: &mut Window,
2871 cx: &mut Context<Self>,
2872 ) -> Option<impl IntoElement> {
2873 self.active_repository.as_ref()?;
2874
2875 let text;
2876 let action;
2877 let tooltip;
2878 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2879 text = "Unstage All";
2880 action = git::UnstageAll.boxed_clone();
2881 tooltip = "git reset";
2882 } else {
2883 text = "Stage All";
2884 action = git::StageAll.boxed_clone();
2885 tooltip = "git add --all ."
2886 }
2887
2888 let change_string = match self.entry_count {
2889 0 => "No Changes".to_string(),
2890 1 => "1 Change".to_string(),
2891 _ => format!("{} Changes", self.entry_count),
2892 };
2893
2894 Some(
2895 self.panel_header_container(window, cx)
2896 .px_2()
2897 .child(
2898 panel_button(change_string)
2899 .color(Color::Muted)
2900 .tooltip(Tooltip::for_action_title_in(
2901 "Open Diff",
2902 &Diff,
2903 &self.focus_handle,
2904 ))
2905 .on_click(|_, _, cx| {
2906 cx.defer(|cx| {
2907 cx.dispatch_action(&Diff);
2908 })
2909 }),
2910 )
2911 .child(div().flex_grow()) // spacer
2912 .child(self.render_overflow_menu("overflow_menu"))
2913 .child(div().w_2()) // another spacer
2914 .child(
2915 panel_filled_button(text)
2916 .tooltip(Tooltip::for_action_title_in(
2917 tooltip,
2918 action.as_ref(),
2919 &self.focus_handle,
2920 ))
2921 .disabled(self.entry_count == 0)
2922 .on_click(move |_, _, cx| {
2923 let action = action.boxed_clone();
2924 cx.defer(move |cx| {
2925 cx.dispatch_action(action.as_ref());
2926 })
2927 }),
2928 ),
2929 )
2930 }
2931
2932 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2933 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
2934 if !self.can_push_and_pull(cx) {
2935 return None;
2936 }
2937 Some(
2938 h_flex()
2939 .gap_1()
2940 .flex_shrink_0()
2941 .when_some(branch, |this, branch| {
2942 let focus_handle = Some(self.focus_handle(cx));
2943
2944 this.children(render_remote_button(
2945 "remote-button",
2946 &branch,
2947 focus_handle,
2948 true,
2949 ))
2950 })
2951 .into_any_element(),
2952 )
2953 }
2954
2955 pub fn render_footer(
2956 &self,
2957 window: &mut Window,
2958 cx: &mut Context<Self>,
2959 ) -> Option<impl IntoElement> {
2960 let active_repository = self.active_repository.clone()?;
2961 let (can_commit, tooltip) = self.configure_commit_button(cx);
2962 let panel_editor_style = panel_editor_style(true, window, cx);
2963
2964 let enable_coauthors = self.render_co_authors(cx);
2965 let title = self.commit_button_title();
2966
2967 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2968 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2969 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2970
2971 let branch = active_repository.read(cx).branch.clone();
2972
2973 let footer_size = px(32.);
2974 let gap = px(9.0);
2975 let max_height = panel_editor_style
2976 .text
2977 .line_height_in_pixels(window.rem_size())
2978 * MAX_PANEL_EDITOR_LINES
2979 + gap;
2980
2981 let git_panel = cx.entity().clone();
2982 let display_name = SharedString::from(Arc::from(
2983 active_repository
2984 .read(cx)
2985 .display_name()
2986 .trim_end_matches("/"),
2987 ));
2988 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
2989 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
2990 });
2991 let has_previous_commit = branch
2992 .as_ref()
2993 .and_then(|branch| branch.most_recent_commit.as_ref())
2994 .is_some();
2995
2996 let footer = v_flex()
2997 .child(PanelRepoFooter::new(display_name, branch, Some(git_panel)))
2998 .child(
2999 panel_editor_container(window, cx)
3000 .id("commit-editor-container")
3001 .relative()
3002 .w_full()
3003 .h(max_height + footer_size)
3004 .border_t_1()
3005 .border_color(cx.theme().colors().border_variant)
3006 .cursor_text()
3007 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3008 window.focus(&this.commit_editor.focus_handle(cx));
3009 }))
3010 .child(
3011 h_flex()
3012 .id("commit-footer")
3013 .border_t_1()
3014 .when(editor_is_long, |el| {
3015 el.border_color(cx.theme().colors().border_variant)
3016 })
3017 .absolute()
3018 .bottom_0()
3019 .left_0()
3020 .w_full()
3021 .px_2()
3022 .h(footer_size)
3023 .flex_none()
3024 .justify_between()
3025 .child(
3026 self.render_generate_commit_message_button(cx)
3027 .unwrap_or_else(|| div().into_any_element()),
3028 )
3029 .child(
3030 h_flex()
3031 .gap_0p5()
3032 .children(enable_coauthors)
3033 .when(self.amend_pending, {
3034 |this| {
3035 this.h_flex()
3036 .gap_1()
3037 .child(
3038 panel_filled_button("Cancel")
3039 .tooltip({
3040 let handle =
3041 commit_tooltip_focus_handle.clone();
3042 move |window, cx| {
3043 Tooltip::for_action_in(
3044 "Cancel amend",
3045 &git::Cancel,
3046 &handle,
3047 window,
3048 cx,
3049 )
3050 }
3051 })
3052 .on_click(move |_, window, cx| {
3053 window.dispatch_action(
3054 Box::new(git::Cancel),
3055 cx,
3056 );
3057 }),
3058 )
3059 .child(
3060 panel_filled_button(title)
3061 .tooltip({
3062 let handle =
3063 commit_tooltip_focus_handle.clone();
3064 move |window, cx| {
3065 if can_commit {
3066 Tooltip::for_action_in(
3067 tooltip, &Amend, &handle,
3068 window, cx,
3069 )
3070 } else {
3071 Tooltip::simple(tooltip, cx)
3072 }
3073 }
3074 })
3075 .disabled(!can_commit || self.modal_open)
3076 .on_click(move |_, window, cx| {
3077 window.dispatch_action(
3078 Box::new(git::Amend),
3079 cx,
3080 );
3081 }),
3082 )
3083 }
3084 })
3085 .when(!self.amend_pending, |this| {
3086 this.when(has_previous_commit, |this| {
3087 this.child(SplitButton::new(
3088 ui::ButtonLike::new_rounded_left(ElementId::Name(
3089 format!("split-button-left-{}", title).into(),
3090 ))
3091 .layer(ui::ElevationIndex::ModalSurface)
3092 .size(ui::ButtonSize::Compact)
3093 .child(
3094 div()
3095 .child(
3096 Label::new(title)
3097 .size(LabelSize::Small),
3098 )
3099 .mr_0p5(),
3100 )
3101 .on_click(move |_, window, cx| {
3102 window
3103 .dispatch_action(Box::new(git::Commit), cx);
3104 })
3105 .disabled(!can_commit || self.modal_open)
3106 .tooltip({
3107 let handle =
3108 commit_tooltip_focus_handle.clone();
3109 move |window, cx| {
3110 if can_commit {
3111 Tooltip::with_meta_in(
3112 tooltip,
3113 Some(&git::Commit),
3114 "git commit",
3115 &handle.clone(),
3116 window,
3117 cx,
3118 )
3119 } else {
3120 Tooltip::simple(tooltip, cx)
3121 }
3122 }
3123 }),
3124 self.render_git_commit_menu(
3125 ElementId::Name(
3126 format!("split-button-right-{}", title)
3127 .into(),
3128 ),
3129 Some(commit_tooltip_focus_handle.clone()),
3130 )
3131 .into_any_element(),
3132 ))
3133 })
3134 .when(
3135 !has_previous_commit,
3136 |this| {
3137 this.child(
3138 panel_filled_button(title)
3139 .tooltip(move |window, cx| {
3140 if can_commit {
3141 Tooltip::with_meta_in(
3142 tooltip,
3143 Some(&git::Commit),
3144 "git commit",
3145 &commit_tooltip_focus_handle,
3146 window,
3147 cx,
3148 )
3149 } else {
3150 Tooltip::simple(tooltip, cx)
3151 }
3152 })
3153 .disabled(!can_commit || self.modal_open)
3154 .on_click(move |_, window, cx| {
3155 window.dispatch_action(
3156 Box::new(git::Commit),
3157 cx,
3158 );
3159 }),
3160 )
3161 },
3162 )
3163 }),
3164 ),
3165 )
3166 .child(
3167 div()
3168 .pr_2p5()
3169 .on_action(|&editor::actions::MoveUp, _, cx| {
3170 cx.stop_propagation();
3171 })
3172 .on_action(|&editor::actions::MoveDown, _, cx| {
3173 cx.stop_propagation();
3174 })
3175 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3176 )
3177 .child(
3178 h_flex()
3179 .absolute()
3180 .top_2()
3181 .right_2()
3182 .opacity(0.5)
3183 .hover(|this| this.opacity(1.0))
3184 .child(
3185 panel_icon_button("expand-commit-editor", IconName::Maximize)
3186 .icon_size(IconSize::Small)
3187 .size(ui::ButtonSize::Default)
3188 .tooltip(move |window, cx| {
3189 Tooltip::for_action_in(
3190 "Open Commit Modal",
3191 &git::ExpandCommitEditor,
3192 &expand_tooltip_focus_handle,
3193 window,
3194 cx,
3195 )
3196 })
3197 .on_click(cx.listener({
3198 move |_, _, window, cx| {
3199 window.dispatch_action(
3200 git::ExpandCommitEditor.boxed_clone(),
3201 cx,
3202 )
3203 }
3204 })),
3205 ),
3206 ),
3207 );
3208
3209 Some(footer)
3210 }
3211
3212 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3213 div()
3214 .py_2()
3215 .px(px(8.))
3216 .border_color(cx.theme().colors().border)
3217 .child(
3218 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.")
3219 .size(LabelSize::Small),
3220 )
3221 }
3222
3223 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3224 let active_repository = self.active_repository.as_ref()?;
3225 let branch = active_repository.read(cx).branch.as_ref()?;
3226 let commit = branch.most_recent_commit.as_ref()?.clone();
3227 let workspace = self.workspace.clone();
3228
3229 let this = cx.entity();
3230 Some(
3231 h_flex()
3232 .items_center()
3233 .py_2()
3234 .px(px(8.))
3235 .border_color(cx.theme().colors().border)
3236 .gap_1p5()
3237 .child(
3238 div()
3239 .flex_grow()
3240 .overflow_hidden()
3241 .items_center()
3242 .max_w(relative(0.85))
3243 .h_full()
3244 .child(
3245 Label::new(commit.subject.clone())
3246 .size(LabelSize::Small)
3247 .truncate(),
3248 )
3249 .id("commit-msg-hover")
3250 .on_click({
3251 let commit = commit.clone();
3252 let repo = active_repository.downgrade();
3253 move |_, window, cx| {
3254 CommitView::open(
3255 commit.clone(),
3256 repo.clone(),
3257 workspace.clone().clone(),
3258 window,
3259 cx,
3260 );
3261 }
3262 })
3263 .hoverable_tooltip({
3264 let repo = active_repository.clone();
3265 move |window, cx| {
3266 GitPanelMessageTooltip::new(
3267 this.clone(),
3268 commit.sha.clone(),
3269 repo.clone(),
3270 window,
3271 cx,
3272 )
3273 .into()
3274 }
3275 }),
3276 )
3277 .child(div().flex_1())
3278 .when(commit.has_parent, |this| {
3279 let has_unstaged = self.has_unstaged_changes();
3280 this.child(
3281 panel_icon_button("undo", IconName::Undo)
3282 .icon_size(IconSize::Small)
3283 .icon_color(Color::Muted)
3284 .tooltip(move |window, cx| {
3285 Tooltip::with_meta(
3286 "Uncommit",
3287 Some(&git::Uncommit),
3288 if has_unstaged {
3289 "git reset HEAD^ --soft"
3290 } else {
3291 "git reset HEAD^"
3292 },
3293 window,
3294 cx,
3295 )
3296 })
3297 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3298 )
3299 }),
3300 )
3301 }
3302
3303 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3304 h_flex()
3305 .h_full()
3306 .flex_grow()
3307 .justify_center()
3308 .items_center()
3309 .child(
3310 v_flex()
3311 .gap_2()
3312 .child(h_flex().w_full().justify_around().child(
3313 if self.active_repository.is_some() {
3314 "No changes to commit"
3315 } else {
3316 "No Git repositories"
3317 },
3318 ))
3319 .children({
3320 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3321 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3322 h_flex().w_full().justify_around().child(
3323 panel_filled_button("Initialize Repository")
3324 .tooltip(Tooltip::for_action_title_in(
3325 "git init",
3326 &git::Init,
3327 &self.focus_handle,
3328 ))
3329 .on_click(move |_, _, cx| {
3330 cx.defer(move |cx| {
3331 cx.dispatch_action(&git::Init);
3332 })
3333 }),
3334 )
3335 })
3336 })
3337 .text_ui_sm(cx)
3338 .mx_auto()
3339 .text_color(Color::Placeholder.color(cx)),
3340 )
3341 }
3342
3343 fn render_vertical_scrollbar(
3344 &self,
3345 show_horizontal_scrollbar_container: bool,
3346 cx: &mut Context<Self>,
3347 ) -> impl IntoElement {
3348 div()
3349 .id("git-panel-vertical-scroll")
3350 .occlude()
3351 .flex_none()
3352 .h_full()
3353 .cursor_default()
3354 .absolute()
3355 .right_0()
3356 .top_0()
3357 .bottom_0()
3358 .w(px(12.))
3359 .when(show_horizontal_scrollbar_container, |this| {
3360 this.pb_neg_3p5()
3361 })
3362 .on_mouse_move(cx.listener(|_, _, _, cx| {
3363 cx.notify();
3364 cx.stop_propagation()
3365 }))
3366 .on_hover(|_, _, cx| {
3367 cx.stop_propagation();
3368 })
3369 .on_any_mouse_down(|_, _, cx| {
3370 cx.stop_propagation();
3371 })
3372 .on_mouse_up(
3373 MouseButton::Left,
3374 cx.listener(|this, _, window, cx| {
3375 if !this.vertical_scrollbar.state.is_dragging()
3376 && !this.focus_handle.contains_focused(window, cx)
3377 {
3378 this.vertical_scrollbar.hide(window, cx);
3379 cx.notify();
3380 }
3381
3382 cx.stop_propagation();
3383 }),
3384 )
3385 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3386 cx.notify();
3387 }))
3388 .children(Scrollbar::vertical(
3389 // percentage as f32..end_offset as f32,
3390 self.vertical_scrollbar.state.clone(),
3391 ))
3392 }
3393
3394 /// Renders the horizontal scrollbar.
3395 ///
3396 /// The right offset is used to determine how far to the right the
3397 /// scrollbar should extend to, useful for ensuring it doesn't collide
3398 /// with the vertical scrollbar when visible.
3399 fn render_horizontal_scrollbar(
3400 &self,
3401 right_offset: Pixels,
3402 cx: &mut Context<Self>,
3403 ) -> impl IntoElement {
3404 div()
3405 .id("git-panel-horizontal-scroll")
3406 .occlude()
3407 .flex_none()
3408 .w_full()
3409 .cursor_default()
3410 .absolute()
3411 .bottom_neg_px()
3412 .left_0()
3413 .right_0()
3414 .pr(right_offset)
3415 .on_mouse_move(cx.listener(|_, _, _, cx| {
3416 cx.notify();
3417 cx.stop_propagation()
3418 }))
3419 .on_hover(|_, _, cx| {
3420 cx.stop_propagation();
3421 })
3422 .on_any_mouse_down(|_, _, cx| {
3423 cx.stop_propagation();
3424 })
3425 .on_mouse_up(
3426 MouseButton::Left,
3427 cx.listener(|this, _, window, cx| {
3428 if !this.horizontal_scrollbar.state.is_dragging()
3429 && !this.focus_handle.contains_focused(window, cx)
3430 {
3431 this.horizontal_scrollbar.hide(window, cx);
3432 cx.notify();
3433 }
3434
3435 cx.stop_propagation();
3436 }),
3437 )
3438 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3439 cx.notify();
3440 }))
3441 .children(Scrollbar::horizontal(
3442 // percentage as f32..end_offset as f32,
3443 self.horizontal_scrollbar.state.clone(),
3444 ))
3445 }
3446
3447 fn render_buffer_header_controls(
3448 &self,
3449 entity: &Entity<Self>,
3450 file: &Arc<dyn File>,
3451 _: &Window,
3452 cx: &App,
3453 ) -> Option<AnyElement> {
3454 let repo = self.active_repository.as_ref()?.read(cx);
3455 let project_path = (file.worktree_id(cx), file.path()).into();
3456 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3457 let ix = self.entry_by_path(&repo_path)?;
3458 let entry = self.entries.get(ix)?;
3459
3460 let entry_staging = self.entry_staging(entry.status_entry()?);
3461
3462 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3463 .disabled(!self.has_write_access(cx))
3464 .fill()
3465 .elevation(ElevationIndex::Surface)
3466 .on_click({
3467 let entry = entry.clone();
3468 let git_panel = entity.downgrade();
3469 move |_, window, cx| {
3470 git_panel
3471 .update(cx, |this, cx| {
3472 this.toggle_staged_for_entry(&entry, window, cx);
3473 cx.stop_propagation();
3474 })
3475 .ok();
3476 }
3477 });
3478 Some(
3479 h_flex()
3480 .id("start-slot")
3481 .text_lg()
3482 .child(checkbox)
3483 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3484 // prevent the list item active state triggering when toggling checkbox
3485 cx.stop_propagation();
3486 })
3487 .into_any_element(),
3488 )
3489 }
3490
3491 fn render_entries(
3492 &self,
3493 has_write_access: bool,
3494 _: &Window,
3495 cx: &mut Context<Self>,
3496 ) -> impl IntoElement {
3497 let entry_count = self.entries.len();
3498
3499 let scroll_track_size = px(16.);
3500
3501 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3502 // magic number
3503 px(3.)
3504 } else {
3505 px(0.)
3506 };
3507
3508 v_flex()
3509 .flex_1()
3510 .size_full()
3511 .overflow_hidden()
3512 .relative()
3513 // Show a border on the top and bottom of the container when
3514 // the vertical scrollbar container is visible so we don't have a
3515 // floating left border in the panel.
3516 .when(self.vertical_scrollbar.show_track, |this| {
3517 this.border_t_1()
3518 .border_b_1()
3519 .border_color(cx.theme().colors().border)
3520 })
3521 .child(
3522 h_flex()
3523 .flex_1()
3524 .size_full()
3525 .relative()
3526 .overflow_hidden()
3527 .child(
3528 uniform_list(cx.entity().clone(), "entries", entry_count, {
3529 move |this, range, window, cx| {
3530 let mut items = Vec::with_capacity(range.end - range.start);
3531
3532 for ix in range {
3533 match &this.entries.get(ix) {
3534 Some(GitListEntry::GitStatusEntry(entry)) => {
3535 items.push(this.render_entry(
3536 ix,
3537 entry,
3538 has_write_access,
3539 window,
3540 cx,
3541 ));
3542 }
3543 Some(GitListEntry::Header(header)) => {
3544 items.push(this.render_list_header(
3545 ix,
3546 header,
3547 has_write_access,
3548 window,
3549 cx,
3550 ));
3551 }
3552 None => {}
3553 }
3554 }
3555
3556 items
3557 }
3558 })
3559 .size_full()
3560 .flex_grow()
3561 .with_sizing_behavior(ListSizingBehavior::Auto)
3562 .with_horizontal_sizing_behavior(
3563 ListHorizontalSizingBehavior::Unconstrained,
3564 )
3565 .with_width_from_item(self.max_width_item_index)
3566 .track_scroll(self.scroll_handle.clone()),
3567 )
3568 .on_mouse_down(
3569 MouseButton::Right,
3570 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3571 this.deploy_panel_context_menu(event.position, window, cx)
3572 }),
3573 )
3574 .when(self.vertical_scrollbar.show_track, |this| {
3575 this.child(
3576 v_flex()
3577 .h_full()
3578 .flex_none()
3579 .w(scroll_track_size)
3580 .bg(cx.theme().colors().panel_background)
3581 .child(
3582 div()
3583 .size_full()
3584 .flex_1()
3585 .border_l_1()
3586 .border_color(cx.theme().colors().border),
3587 ),
3588 )
3589 })
3590 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3591 this.child(
3592 self.render_vertical_scrollbar(
3593 self.horizontal_scrollbar.show_track,
3594 cx,
3595 ),
3596 )
3597 }),
3598 )
3599 .when(self.horizontal_scrollbar.show_track, |this| {
3600 this.child(
3601 h_flex()
3602 .w_full()
3603 .h(scroll_track_size)
3604 .flex_none()
3605 .relative()
3606 .child(
3607 div()
3608 .w_full()
3609 .flex_1()
3610 // for some reason the horizontal scrollbar is 1px
3611 // taller than the vertical scrollbar??
3612 .h(scroll_track_size - px(1.))
3613 .bg(cx.theme().colors().panel_background)
3614 .border_t_1()
3615 .border_color(cx.theme().colors().border),
3616 )
3617 .when(self.vertical_scrollbar.show_track, |this| {
3618 this.child(
3619 div()
3620 .flex_none()
3621 // -1px prevents a missing pixel between the two container borders
3622 .w(scroll_track_size - px(1.))
3623 .h_full(),
3624 )
3625 .child(
3626 // HACK: Fill the missing 1px 🥲
3627 div()
3628 .absolute()
3629 .right(scroll_track_size - px(1.))
3630 .bottom(scroll_track_size - px(1.))
3631 .size_px()
3632 .bg(cx.theme().colors().border),
3633 )
3634 }),
3635 )
3636 })
3637 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3638 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3639 })
3640 }
3641
3642 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3643 Label::new(label.into()).color(color).single_line()
3644 }
3645
3646 fn list_item_height(&self) -> Rems {
3647 rems(1.75)
3648 }
3649
3650 fn render_list_header(
3651 &self,
3652 ix: usize,
3653 header: &GitHeaderEntry,
3654 _: bool,
3655 _: &Window,
3656 _: &Context<Self>,
3657 ) -> AnyElement {
3658 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3659
3660 h_flex()
3661 .id(id)
3662 .h(self.list_item_height())
3663 .w_full()
3664 .items_end()
3665 .px(rems(0.75)) // ~12px
3666 .pb(rems(0.3125)) // ~ 5px
3667 .child(
3668 Label::new(header.title())
3669 .color(Color::Muted)
3670 .size(LabelSize::Small)
3671 .line_height_style(LineHeightStyle::UiLabel)
3672 .single_line(),
3673 )
3674 .into_any_element()
3675 }
3676
3677 pub fn load_commit_details(
3678 &self,
3679 sha: String,
3680 cx: &mut Context<Self>,
3681 ) -> Task<anyhow::Result<CommitDetails>> {
3682 let Some(repo) = self.active_repository.clone() else {
3683 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3684 };
3685 repo.update(cx, |repo, cx| {
3686 let show = repo.show(sha);
3687 cx.spawn(async move |_, _| show.await?)
3688 })
3689 }
3690
3691 fn deploy_entry_context_menu(
3692 &mut self,
3693 position: Point<Pixels>,
3694 ix: usize,
3695 window: &mut Window,
3696 cx: &mut Context<Self>,
3697 ) {
3698 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3699 return;
3700 };
3701 let stage_title = if entry.status.staging().is_fully_staged() {
3702 "Unstage File"
3703 } else {
3704 "Stage File"
3705 };
3706 let restore_title = if entry.status.is_created() {
3707 "Trash File"
3708 } else {
3709 "Restore File"
3710 };
3711 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3712 context_menu
3713 .context(self.focus_handle.clone())
3714 .action(stage_title, ToggleStaged.boxed_clone())
3715 .action(restore_title, git::RestoreFile::default().boxed_clone())
3716 .separator()
3717 .action("Open Diff", Confirm.boxed_clone())
3718 .action("Open File", SecondaryConfirm.boxed_clone())
3719 });
3720 self.selected_entry = Some(ix);
3721 self.set_context_menu(context_menu, position, window, cx);
3722 }
3723
3724 fn deploy_panel_context_menu(
3725 &mut self,
3726 position: Point<Pixels>,
3727 window: &mut Window,
3728 cx: &mut Context<Self>,
3729 ) {
3730 let context_menu = git_panel_context_menu(
3731 self.focus_handle.clone(),
3732 GitMenuState {
3733 has_tracked_changes: self.has_tracked_changes(),
3734 has_staged_changes: self.has_staged_changes(),
3735 has_unstaged_changes: self.has_unstaged_changes(),
3736 has_new_changes: self.new_count > 0,
3737 },
3738 window,
3739 cx,
3740 );
3741 self.set_context_menu(context_menu, position, window, cx);
3742 }
3743
3744 fn set_context_menu(
3745 &mut self,
3746 context_menu: Entity<ContextMenu>,
3747 position: Point<Pixels>,
3748 window: &Window,
3749 cx: &mut Context<Self>,
3750 ) {
3751 let subscription = cx.subscribe_in(
3752 &context_menu,
3753 window,
3754 |this, _, _: &DismissEvent, window, cx| {
3755 if this.context_menu.as_ref().is_some_and(|context_menu| {
3756 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3757 }) {
3758 cx.focus_self(window);
3759 }
3760 this.context_menu.take();
3761 cx.notify();
3762 },
3763 );
3764 self.context_menu = Some((context_menu, position, subscription));
3765 cx.notify();
3766 }
3767
3768 fn render_entry(
3769 &self,
3770 ix: usize,
3771 entry: &GitStatusEntry,
3772 has_write_access: bool,
3773 window: &Window,
3774 cx: &Context<Self>,
3775 ) -> AnyElement {
3776 let display_name = entry.display_name();
3777
3778 let selected = self.selected_entry == Some(ix);
3779 let marked = self.marked_entries.contains(&ix);
3780 let status_style = GitPanelSettings::get_global(cx).status_style;
3781 let status = entry.status;
3782 let modifiers = self.current_modifiers;
3783 let shift_held = modifiers.shift;
3784
3785 let has_conflict = status.is_conflicted();
3786 let is_modified = status.is_modified();
3787 let is_deleted = status.is_deleted();
3788
3789 let label_color = if status_style == StatusStyle::LabelColor {
3790 if has_conflict {
3791 Color::VersionControlConflict
3792 } else if is_modified {
3793 Color::VersionControlModified
3794 } else if is_deleted {
3795 // We don't want a bunch of red labels in the list
3796 Color::Disabled
3797 } else {
3798 Color::VersionControlAdded
3799 }
3800 } else {
3801 Color::Default
3802 };
3803
3804 let path_color = if status.is_deleted() {
3805 Color::Disabled
3806 } else {
3807 Color::Muted
3808 };
3809
3810 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3811 let checkbox_wrapper_id: ElementId =
3812 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3813 let checkbox_id: ElementId =
3814 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3815
3816 let entry_staging = self.entry_staging(entry);
3817 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3818
3819 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3820 is_staged = ToggleState::Selected;
3821 }
3822
3823 let handle = cx.weak_entity();
3824
3825 let selected_bg_alpha = 0.08;
3826 let marked_bg_alpha = 0.12;
3827 let state_opacity_step = 0.04;
3828
3829 let base_bg = match (selected, marked) {
3830 (true, true) => cx
3831 .theme()
3832 .status()
3833 .info
3834 .alpha(selected_bg_alpha + marked_bg_alpha),
3835 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3836 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3837 _ => cx.theme().colors().ghost_element_background,
3838 };
3839
3840 let hover_bg = if selected {
3841 cx.theme()
3842 .status()
3843 .info
3844 .alpha(selected_bg_alpha + state_opacity_step)
3845 } else {
3846 cx.theme().colors().ghost_element_hover
3847 };
3848
3849 let active_bg = if selected {
3850 cx.theme()
3851 .status()
3852 .info
3853 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3854 } else {
3855 cx.theme().colors().ghost_element_active
3856 };
3857
3858 h_flex()
3859 .id(id)
3860 .h(self.list_item_height())
3861 .w_full()
3862 .items_center()
3863 .border_1()
3864 .when(selected && self.focus_handle.is_focused(window), |el| {
3865 el.border_color(cx.theme().colors().border_focused)
3866 })
3867 .px(rems(0.75)) // ~12px
3868 .overflow_hidden()
3869 .flex_none()
3870 .gap_1p5()
3871 .bg(base_bg)
3872 .hover(|this| this.bg(hover_bg))
3873 .active(|this| this.bg(active_bg))
3874 .on_click({
3875 cx.listener(move |this, event: &ClickEvent, window, cx| {
3876 this.selected_entry = Some(ix);
3877 cx.notify();
3878 if event.modifiers().secondary() {
3879 this.open_file(&Default::default(), window, cx)
3880 } else {
3881 this.open_diff(&Default::default(), window, cx);
3882 this.focus_handle.focus(window);
3883 }
3884 })
3885 })
3886 .on_mouse_down(
3887 MouseButton::Right,
3888 move |event: &MouseDownEvent, window, cx| {
3889 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3890 if event.button != MouseButton::Right {
3891 return;
3892 }
3893
3894 let Some(this) = handle.upgrade() else {
3895 return;
3896 };
3897 this.update(cx, |this, cx| {
3898 this.deploy_entry_context_menu(event.position, ix, window, cx);
3899 });
3900 cx.stop_propagation();
3901 },
3902 )
3903 // .on_secondary_mouse_down(cx.listener(
3904 // move |this, event: &MouseDownEvent, window, cx| {
3905 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3906 // cx.stop_propagation();
3907 // },
3908 // ))
3909 .child(
3910 div()
3911 .id(checkbox_wrapper_id)
3912 .flex_none()
3913 .occlude()
3914 .cursor_pointer()
3915 .child(
3916 Checkbox::new(checkbox_id, is_staged)
3917 .disabled(!has_write_access)
3918 .fill()
3919 .placeholder(
3920 !self.has_staged_changes()
3921 && !self.has_conflicts()
3922 && !entry.status.is_created(),
3923 )
3924 .elevation(ElevationIndex::Surface)
3925 .on_click({
3926 let entry = entry.clone();
3927 cx.listener(move |this, _, window, cx| {
3928 if !has_write_access {
3929 return;
3930 }
3931 this.toggle_staged_for_entry(
3932 &GitListEntry::GitStatusEntry(entry.clone()),
3933 window,
3934 cx,
3935 );
3936 cx.stop_propagation();
3937 })
3938 })
3939 .tooltip(move |window, cx| {
3940 let is_staged = entry_staging.is_fully_staged();
3941
3942 let action = if is_staged { "Unstage" } else { "Stage" };
3943 let tooltip_name = if shift_held {
3944 format!("{} section", action)
3945 } else {
3946 action.to_string()
3947 };
3948
3949 let meta = if shift_held {
3950 format!(
3951 "Release shift to {} single entry",
3952 action.to_lowercase()
3953 )
3954 } else {
3955 format!("Shift click to {} section", action.to_lowercase())
3956 };
3957
3958 Tooltip::with_meta(
3959 tooltip_name,
3960 Some(&ToggleStaged),
3961 meta,
3962 window,
3963 cx,
3964 )
3965 }),
3966 ),
3967 )
3968 .child(git_status_icon(status))
3969 .child(
3970 h_flex()
3971 .items_center()
3972 .flex_1()
3973 // .overflow_hidden()
3974 .when_some(entry.parent_dir(), |this, parent| {
3975 if !parent.is_empty() {
3976 this.child(
3977 self.entry_label(format!("{}/", parent), path_color)
3978 .when(status.is_deleted(), |this| this.strikethrough()),
3979 )
3980 } else {
3981 this
3982 }
3983 })
3984 .child(
3985 self.entry_label(display_name.clone(), label_color)
3986 .when(status.is_deleted(), |this| this.strikethrough()),
3987 ),
3988 )
3989 .into_any_element()
3990 }
3991
3992 fn has_write_access(&self, cx: &App) -> bool {
3993 !self.project.read(cx).is_read_only(cx)
3994 }
3995
3996 pub fn amend_pending(&self) -> bool {
3997 self.amend_pending
3998 }
3999
4000 pub fn set_amend_pending(&mut self, value: bool) {
4001 self.amend_pending = value;
4002 }
4003}
4004
4005fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4006 assistant_settings::AssistantSettings::get_global(cx)
4007 .enabled
4008 .then(|| {
4009 let ConfiguredModel { provider, model } =
4010 LanguageModelRegistry::read_global(cx).commit_message_model()?;
4011
4012 provider.is_authenticated(cx).then(|| model)
4013 })
4014 .flatten()
4015}
4016
4017impl Render for GitPanel {
4018 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4019 let project = self.project.read(cx);
4020 let has_entries = self.entries.len() > 0;
4021 let room = self
4022 .workspace
4023 .upgrade()
4024 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4025
4026 let has_write_access = self.has_write_access(cx);
4027
4028 let has_co_authors = room.map_or(false, |room| {
4029 room.read(cx)
4030 .remote_participants()
4031 .values()
4032 .any(|remote_participant| remote_participant.can_write())
4033 });
4034
4035 v_flex()
4036 .id("git_panel")
4037 .key_context(self.dispatch_context(window, cx))
4038 .track_focus(&self.focus_handle)
4039 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
4040 .when(has_write_access && !project.is_read_only(cx), |this| {
4041 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4042 .on_action(cx.listener(GitPanel::commit))
4043 .on_action(cx.listener(GitPanel::amend))
4044 .on_action(cx.listener(GitPanel::cancel))
4045 .on_action(cx.listener(Self::stage_all))
4046 .on_action(cx.listener(Self::unstage_all))
4047 .on_action(cx.listener(Self::stage_selected))
4048 .on_action(cx.listener(Self::unstage_selected))
4049 .on_action(cx.listener(Self::restore_tracked_files))
4050 .on_action(cx.listener(Self::revert_selected))
4051 .on_action(cx.listener(Self::clean_all))
4052 .on_action(cx.listener(Self::generate_commit_message_action))
4053 })
4054 .on_action(cx.listener(Self::select_first))
4055 .on_action(cx.listener(Self::select_next))
4056 .on_action(cx.listener(Self::select_previous))
4057 .on_action(cx.listener(Self::select_last))
4058 .on_action(cx.listener(Self::close_panel))
4059 .on_action(cx.listener(Self::open_diff))
4060 .on_action(cx.listener(Self::open_file))
4061 .on_action(cx.listener(Self::focus_changes_list))
4062 .on_action(cx.listener(Self::focus_editor))
4063 .on_action(cx.listener(Self::expand_commit_editor))
4064 .when(has_write_access && has_co_authors, |git_panel| {
4065 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4066 })
4067 .on_hover(cx.listener(move |this, hovered, window, cx| {
4068 if *hovered {
4069 this.horizontal_scrollbar.show(cx);
4070 this.vertical_scrollbar.show(cx);
4071 cx.notify();
4072 } else if !this.focus_handle.contains_focused(window, cx) {
4073 this.hide_scrollbars(window, cx);
4074 }
4075 }))
4076 .size_full()
4077 .overflow_hidden()
4078 .bg(cx.theme().colors().panel_background)
4079 .child(
4080 v_flex()
4081 .size_full()
4082 .children(self.render_panel_header(window, cx))
4083 .map(|this| {
4084 if has_entries {
4085 this.child(self.render_entries(has_write_access, window, cx))
4086 } else {
4087 this.child(self.render_empty_state(cx).into_any_element())
4088 }
4089 })
4090 .children(self.render_footer(window, cx))
4091 .when(self.amend_pending, |this| {
4092 this.child(self.render_pending_amend(cx))
4093 })
4094 .when(!self.amend_pending, |this| {
4095 this.children(self.render_previous_commit(cx))
4096 })
4097 .into_any_element(),
4098 )
4099 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4100 deferred(
4101 anchored()
4102 .position(*position)
4103 .anchor(Corner::TopLeft)
4104 .child(menu.clone()),
4105 )
4106 .with_priority(1)
4107 }))
4108 }
4109}
4110
4111impl Focusable for GitPanel {
4112 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4113 if self.entries.is_empty() {
4114 self.commit_editor.focus_handle(cx)
4115 } else {
4116 self.focus_handle.clone()
4117 }
4118 }
4119}
4120
4121impl EventEmitter<Event> for GitPanel {}
4122
4123impl EventEmitter<PanelEvent> for GitPanel {}
4124
4125pub(crate) struct GitPanelAddon {
4126 pub(crate) workspace: WeakEntity<Workspace>,
4127}
4128
4129impl editor::Addon for GitPanelAddon {
4130 fn to_any(&self) -> &dyn std::any::Any {
4131 self
4132 }
4133
4134 fn render_buffer_header_controls(
4135 &self,
4136 excerpt_info: &ExcerptInfo,
4137 window: &Window,
4138 cx: &App,
4139 ) -> Option<AnyElement> {
4140 let file = excerpt_info.buffer.file()?;
4141 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4142
4143 git_panel
4144 .read(cx)
4145 .render_buffer_header_controls(&git_panel, &file, window, cx)
4146 }
4147}
4148
4149impl Panel for GitPanel {
4150 fn persistent_name() -> &'static str {
4151 "GitPanel"
4152 }
4153
4154 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4155 GitPanelSettings::get_global(cx).dock
4156 }
4157
4158 fn position_is_valid(&self, position: DockPosition) -> bool {
4159 matches!(position, DockPosition::Left | DockPosition::Right)
4160 }
4161
4162 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4163 settings::update_settings_file::<GitPanelSettings>(
4164 self.fs.clone(),
4165 cx,
4166 move |settings, _| settings.dock = Some(position),
4167 );
4168 }
4169
4170 fn size(&self, _: &Window, cx: &App) -> Pixels {
4171 self.width
4172 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4173 }
4174
4175 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4176 self.width = size;
4177 self.serialize(cx);
4178 cx.notify();
4179 }
4180
4181 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4182 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
4183 }
4184
4185 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4186 Some("Git Panel")
4187 }
4188
4189 fn toggle_action(&self) -> Box<dyn Action> {
4190 Box::new(ToggleFocus)
4191 }
4192
4193 fn activation_priority(&self) -> u32 {
4194 2
4195 }
4196}
4197
4198impl PanelHeader for GitPanel {}
4199
4200struct GitPanelMessageTooltip {
4201 commit_tooltip: Option<Entity<CommitTooltip>>,
4202}
4203
4204impl GitPanelMessageTooltip {
4205 fn new(
4206 git_panel: Entity<GitPanel>,
4207 sha: SharedString,
4208 repository: Entity<Repository>,
4209 window: &mut Window,
4210 cx: &mut App,
4211 ) -> Entity<Self> {
4212 cx.new(|cx| {
4213 cx.spawn_in(window, async move |this, cx| {
4214 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4215 (
4216 git_panel.load_commit_details(sha.to_string(), cx),
4217 git_panel.workspace.clone(),
4218 )
4219 })?;
4220 let details = details.await?;
4221
4222 let commit_details = crate::commit_tooltip::CommitDetails {
4223 sha: details.sha.clone(),
4224 author_name: details.author_name.clone(),
4225 author_email: details.author_email.clone(),
4226 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4227 message: Some(ParsedCommitMessage {
4228 message: details.message.clone(),
4229 ..Default::default()
4230 }),
4231 };
4232
4233 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4234 this.commit_tooltip = Some(cx.new(move |cx| {
4235 CommitTooltip::new(commit_details, repository, workspace, cx)
4236 }));
4237 cx.notify();
4238 })
4239 })
4240 .detach();
4241
4242 Self {
4243 commit_tooltip: None,
4244 }
4245 })
4246 }
4247}
4248
4249impl Render for GitPanelMessageTooltip {
4250 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4251 if let Some(commit_tooltip) = &self.commit_tooltip {
4252 commit_tooltip.clone().into_any_element()
4253 } else {
4254 gpui::Empty.into_any_element()
4255 }
4256 }
4257}
4258
4259#[derive(IntoElement, RegisterComponent)]
4260pub struct PanelRepoFooter {
4261 active_repository: SharedString,
4262 branch: Option<Branch>,
4263 // Getting a GitPanel in previews will be difficult.
4264 //
4265 // For now just take an option here, and we won't bind handlers to buttons in previews.
4266 git_panel: Option<Entity<GitPanel>>,
4267}
4268
4269impl PanelRepoFooter {
4270 pub fn new(
4271 active_repository: SharedString,
4272 branch: Option<Branch>,
4273 git_panel: Option<Entity<GitPanel>>,
4274 ) -> Self {
4275 Self {
4276 active_repository,
4277 branch,
4278 git_panel,
4279 }
4280 }
4281
4282 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4283 Self {
4284 active_repository,
4285 branch,
4286 git_panel: None,
4287 }
4288 }
4289}
4290
4291impl RenderOnce for PanelRepoFooter {
4292 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4293 let project = self
4294 .git_panel
4295 .as_ref()
4296 .map(|panel| panel.read(cx).project.clone());
4297
4298 let repo = self
4299 .git_panel
4300 .as_ref()
4301 .and_then(|panel| panel.read(cx).active_repository.clone());
4302
4303 let single_repo = project
4304 .as_ref()
4305 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4306 .unwrap_or(true);
4307
4308 const MAX_BRANCH_LEN: usize = 16;
4309 const MAX_REPO_LEN: usize = 16;
4310 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4311
4312 let branch = self.branch.clone();
4313 let branch_name = branch
4314 .as_ref()
4315 .map_or(" (no branch)".into(), |branch| branch.name.clone());
4316 let active_repo_name = self.active_repository.clone();
4317
4318 let branch_actual_len = branch_name.len();
4319 let repo_actual_len = active_repo_name.len();
4320
4321 // ideally, show the whole branch and repo names but
4322 // when we can't, use a budget to allocate space between the two
4323 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4324 <= LABEL_CHARACTER_BUDGET
4325 {
4326 (repo_actual_len, branch_actual_len)
4327 } else {
4328 if branch_actual_len <= MAX_BRANCH_LEN {
4329 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4330 (repo_space, branch_actual_len)
4331 } else if repo_actual_len <= MAX_REPO_LEN {
4332 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4333 (repo_actual_len, branch_space)
4334 } else {
4335 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4336 }
4337 };
4338
4339 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4340 active_repo_name.to_string()
4341 } else {
4342 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4343 };
4344
4345 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4346 branch_name.to_string()
4347 } else {
4348 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4349 };
4350
4351 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4352 .style(ButtonStyle::Transparent)
4353 .size(ButtonSize::None)
4354 .label_size(LabelSize::Small)
4355 .color(Color::Muted);
4356
4357 let repo_selector = PopoverMenu::new("repository-switcher")
4358 .menu({
4359 let project = project.clone();
4360 move |window, cx| {
4361 let project = project.clone()?;
4362 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4363 }
4364 })
4365 .trigger_with_tooltip(
4366 repo_selector_trigger.disabled(single_repo).truncate(true),
4367 Tooltip::text("Switch active repository"),
4368 )
4369 .anchor(Corner::BottomLeft)
4370 .into_any_element();
4371
4372 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4373 .style(ButtonStyle::Transparent)
4374 .size(ButtonSize::None)
4375 .label_size(LabelSize::Small)
4376 .truncate(true)
4377 .tooltip(Tooltip::for_action_title(
4378 "Switch Branch",
4379 &zed_actions::git::Switch,
4380 ))
4381 .on_click(|_, window, cx| {
4382 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4383 });
4384
4385 let branch_selector = PopoverMenu::new("popover-button")
4386 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4387 .trigger_with_tooltip(
4388 branch_selector_button,
4389 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4390 )
4391 .anchor(Corner::BottomLeft)
4392 .offset(gpui::Point {
4393 x: px(0.0),
4394 y: px(-2.0),
4395 });
4396
4397 h_flex()
4398 .w_full()
4399 .px_2()
4400 .h(px(36.))
4401 .items_center()
4402 .justify_between()
4403 .gap_1()
4404 .child(
4405 h_flex()
4406 .flex_1()
4407 .overflow_hidden()
4408 .items_center()
4409 .child(
4410 div().child(
4411 Icon::new(IconName::GitBranchSmall)
4412 .size(IconSize::Small)
4413 .color(if single_repo {
4414 Color::Disabled
4415 } else {
4416 Color::Muted
4417 }),
4418 ),
4419 )
4420 .child(repo_selector)
4421 .when_some(branch.clone(), |this, _| {
4422 this.child(
4423 div()
4424 .text_color(cx.theme().colors().text_muted)
4425 .text_sm()
4426 .child("/"),
4427 )
4428 })
4429 .child(branch_selector),
4430 )
4431 .children(if let Some(git_panel) = self.git_panel {
4432 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4433 } else {
4434 None
4435 })
4436 }
4437}
4438
4439impl Component for PanelRepoFooter {
4440 fn scope() -> ComponentScope {
4441 ComponentScope::VersionControl
4442 }
4443
4444 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4445 let unknown_upstream = None;
4446 let no_remote_upstream = Some(UpstreamTracking::Gone);
4447 let ahead_of_upstream = Some(
4448 UpstreamTrackingStatus {
4449 ahead: 2,
4450 behind: 0,
4451 }
4452 .into(),
4453 );
4454 let behind_upstream = Some(
4455 UpstreamTrackingStatus {
4456 ahead: 0,
4457 behind: 2,
4458 }
4459 .into(),
4460 );
4461 let ahead_and_behind_upstream = Some(
4462 UpstreamTrackingStatus {
4463 ahead: 3,
4464 behind: 1,
4465 }
4466 .into(),
4467 );
4468
4469 let not_ahead_or_behind_upstream = Some(
4470 UpstreamTrackingStatus {
4471 ahead: 0,
4472 behind: 0,
4473 }
4474 .into(),
4475 );
4476
4477 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4478 Branch {
4479 is_head: true,
4480 name: "some-branch".into(),
4481 upstream: upstream.map(|tracking| Upstream {
4482 ref_name: "origin/some-branch".into(),
4483 tracking,
4484 }),
4485 most_recent_commit: Some(CommitSummary {
4486 sha: "abc123".into(),
4487 subject: "Modify stuff".into(),
4488 commit_timestamp: 1710932954,
4489 has_parent: true,
4490 }),
4491 }
4492 }
4493
4494 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4495 Branch {
4496 is_head: true,
4497 name: branch_name.to_string().into(),
4498 upstream: upstream.map(|tracking| Upstream {
4499 ref_name: format!("zed/{}", branch_name).into(),
4500 tracking,
4501 }),
4502 most_recent_commit: Some(CommitSummary {
4503 sha: "abc123".into(),
4504 subject: "Modify stuff".into(),
4505 commit_timestamp: 1710932954,
4506 has_parent: true,
4507 }),
4508 }
4509 }
4510
4511 fn active_repository(id: usize) -> SharedString {
4512 format!("repo-{}", id).into()
4513 }
4514
4515 let example_width = px(340.);
4516 Some(
4517 v_flex()
4518 .gap_6()
4519 .w_full()
4520 .flex_none()
4521 .children(vec![
4522 example_group_with_title(
4523 "Action Button States",
4524 vec![
4525 single_example(
4526 "No Branch",
4527 div()
4528 .w(example_width)
4529 .overflow_hidden()
4530 .child(PanelRepoFooter::new_preview(
4531 active_repository(1).clone(),
4532 None,
4533 ))
4534 .into_any_element(),
4535 ),
4536 single_example(
4537 "Remote status unknown",
4538 div()
4539 .w(example_width)
4540 .overflow_hidden()
4541 .child(PanelRepoFooter::new_preview(
4542 active_repository(2).clone(),
4543 Some(branch(unknown_upstream)),
4544 ))
4545 .into_any_element(),
4546 ),
4547 single_example(
4548 "No Remote Upstream",
4549 div()
4550 .w(example_width)
4551 .overflow_hidden()
4552 .child(PanelRepoFooter::new_preview(
4553 active_repository(3).clone(),
4554 Some(branch(no_remote_upstream)),
4555 ))
4556 .into_any_element(),
4557 ),
4558 single_example(
4559 "Not Ahead or Behind",
4560 div()
4561 .w(example_width)
4562 .overflow_hidden()
4563 .child(PanelRepoFooter::new_preview(
4564 active_repository(4).clone(),
4565 Some(branch(not_ahead_or_behind_upstream)),
4566 ))
4567 .into_any_element(),
4568 ),
4569 single_example(
4570 "Behind remote",
4571 div()
4572 .w(example_width)
4573 .overflow_hidden()
4574 .child(PanelRepoFooter::new_preview(
4575 active_repository(5).clone(),
4576 Some(branch(behind_upstream)),
4577 ))
4578 .into_any_element(),
4579 ),
4580 single_example(
4581 "Ahead of remote",
4582 div()
4583 .w(example_width)
4584 .overflow_hidden()
4585 .child(PanelRepoFooter::new_preview(
4586 active_repository(6).clone(),
4587 Some(branch(ahead_of_upstream)),
4588 ))
4589 .into_any_element(),
4590 ),
4591 single_example(
4592 "Ahead and behind remote",
4593 div()
4594 .w(example_width)
4595 .overflow_hidden()
4596 .child(PanelRepoFooter::new_preview(
4597 active_repository(7).clone(),
4598 Some(branch(ahead_and_behind_upstream)),
4599 ))
4600 .into_any_element(),
4601 ),
4602 ],
4603 )
4604 .grow()
4605 .vertical(),
4606 ])
4607 .children(vec![
4608 example_group_with_title(
4609 "Labels",
4610 vec![
4611 single_example(
4612 "Short Branch & Repo",
4613 div()
4614 .w(example_width)
4615 .overflow_hidden()
4616 .child(PanelRepoFooter::new_preview(
4617 SharedString::from("zed"),
4618 Some(custom("main", behind_upstream)),
4619 ))
4620 .into_any_element(),
4621 ),
4622 single_example(
4623 "Long Branch",
4624 div()
4625 .w(example_width)
4626 .overflow_hidden()
4627 .child(PanelRepoFooter::new_preview(
4628 SharedString::from("zed"),
4629 Some(custom(
4630 "redesign-and-update-git-ui-list-entry-style",
4631 behind_upstream,
4632 )),
4633 ))
4634 .into_any_element(),
4635 ),
4636 single_example(
4637 "Long Repo",
4638 div()
4639 .w(example_width)
4640 .overflow_hidden()
4641 .child(PanelRepoFooter::new_preview(
4642 SharedString::from("zed-industries-community-examples"),
4643 Some(custom("gpui", ahead_of_upstream)),
4644 ))
4645 .into_any_element(),
4646 ),
4647 single_example(
4648 "Long Repo & Branch",
4649 div()
4650 .w(example_width)
4651 .overflow_hidden()
4652 .child(PanelRepoFooter::new_preview(
4653 SharedString::from("zed-industries-community-examples"),
4654 Some(custom(
4655 "redesign-and-update-git-ui-list-entry-style",
4656 behind_upstream,
4657 )),
4658 ))
4659 .into_any_element(),
4660 ),
4661 single_example(
4662 "Uppercase Repo",
4663 div()
4664 .w(example_width)
4665 .overflow_hidden()
4666 .child(PanelRepoFooter::new_preview(
4667 SharedString::from("LICENSES"),
4668 Some(custom("main", ahead_of_upstream)),
4669 ))
4670 .into_any_element(),
4671 ),
4672 single_example(
4673 "Uppercase Branch",
4674 div()
4675 .w(example_width)
4676 .overflow_hidden()
4677 .child(PanelRepoFooter::new_preview(
4678 SharedString::from("zed"),
4679 Some(custom("update-README", behind_upstream)),
4680 ))
4681 .into_any_element(),
4682 ),
4683 ],
4684 )
4685 .grow()
4686 .vertical(),
4687 ])
4688 .into_any_element(),
4689 )
4690 }
4691}
4692
4693#[cfg(test)]
4694mod tests {
4695 use git::status::StatusCode;
4696 use gpui::TestAppContext;
4697 use project::{FakeFs, WorktreeSettings};
4698 use serde_json::json;
4699 use settings::SettingsStore;
4700 use theme::LoadThemes;
4701 use util::path;
4702
4703 use super::*;
4704
4705 fn init_test(cx: &mut gpui::TestAppContext) {
4706 if std::env::var("RUST_LOG").is_ok() {
4707 env_logger::try_init().ok();
4708 }
4709
4710 cx.update(|cx| {
4711 let settings_store = SettingsStore::test(cx);
4712 cx.set_global(settings_store);
4713 AssistantSettings::register(cx);
4714 WorktreeSettings::register(cx);
4715 workspace::init_settings(cx);
4716 theme::init(LoadThemes::JustBase, cx);
4717 language::init(cx);
4718 editor::init(cx);
4719 Project::init_settings(cx);
4720 crate::init(cx);
4721 });
4722 }
4723
4724 #[gpui::test]
4725 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4726 init_test(cx);
4727 let fs = FakeFs::new(cx.background_executor.clone());
4728 fs.insert_tree(
4729 "/root",
4730 json!({
4731 "zed": {
4732 ".git": {},
4733 "crates": {
4734 "gpui": {
4735 "gpui.rs": "fn main() {}"
4736 },
4737 "util": {
4738 "util.rs": "fn do_it() {}"
4739 }
4740 }
4741 },
4742 }),
4743 )
4744 .await;
4745
4746 fs.set_status_for_repo(
4747 Path::new(path!("/root/zed/.git")),
4748 &[
4749 (
4750 Path::new("crates/gpui/gpui.rs"),
4751 StatusCode::Modified.worktree(),
4752 ),
4753 (
4754 Path::new("crates/util/util.rs"),
4755 StatusCode::Modified.worktree(),
4756 ),
4757 ],
4758 );
4759
4760 let project =
4761 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4762 let (workspace, cx) =
4763 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4764
4765 cx.read(|cx| {
4766 project
4767 .read(cx)
4768 .worktrees(cx)
4769 .nth(0)
4770 .unwrap()
4771 .read(cx)
4772 .as_local()
4773 .unwrap()
4774 .scan_complete()
4775 })
4776 .await;
4777
4778 cx.executor().run_until_parked();
4779
4780 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4781 let panel = cx.new_window_entity(|window, cx| {
4782 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4783 });
4784
4785 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4786 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4787 });
4788 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4789 handle.await;
4790
4791 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4792 pretty_assertions::assert_eq!(
4793 entries,
4794 [
4795 GitListEntry::Header(GitHeaderEntry {
4796 header: Section::Tracked
4797 }),
4798 GitListEntry::GitStatusEntry(GitStatusEntry {
4799 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4800 repo_path: "crates/gpui/gpui.rs".into(),
4801 status: StatusCode::Modified.worktree(),
4802 staging: StageStatus::Unstaged,
4803 }),
4804 GitListEntry::GitStatusEntry(GitStatusEntry {
4805 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4806 repo_path: "crates/util/util.rs".into(),
4807 status: StatusCode::Modified.worktree(),
4808 staging: StageStatus::Unstaged,
4809 },),
4810 ],
4811 );
4812
4813 // TODO(cole) restore this once repository deduplication is implemented properly.
4814 //cx.update_window_entity(&panel, |panel, window, cx| {
4815 // panel.select_last(&Default::default(), window, cx);
4816 // assert_eq!(panel.selected_entry, Some(2));
4817 // panel.open_diff(&Default::default(), window, cx);
4818 //});
4819 //cx.run_until_parked();
4820
4821 //let worktree_roots = workspace.update(cx, |workspace, cx| {
4822 // workspace
4823 // .worktrees(cx)
4824 // .map(|worktree| worktree.read(cx).abs_path())
4825 // .collect::<Vec<_>>()
4826 //});
4827 //pretty_assertions::assert_eq!(
4828 // worktree_roots,
4829 // vec![
4830 // Path::new(path!("/root/zed/crates/gpui")).into(),
4831 // Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4832 // ]
4833 //);
4834
4835 //project.update(cx, |project, cx| {
4836 // let git_store = project.git_store().read(cx);
4837 // // The repo that comes from the single-file worktree can't be selected through the UI.
4838 // let filtered_entries = filtered_repository_entries(git_store, cx)
4839 // .iter()
4840 // .map(|repo| repo.read(cx).worktree_abs_path.clone())
4841 // .collect::<Vec<_>>();
4842 // assert_eq!(
4843 // filtered_entries,
4844 // [Path::new(path!("/root/zed/crates/gpui")).into()]
4845 // );
4846 // // But we can select it artificially here.
4847 // let repo_from_single_file_worktree = git_store
4848 // .repositories()
4849 // .values()
4850 // .find(|repo| {
4851 // repo.read(cx).worktree_abs_path.as_ref()
4852 // == Path::new(path!("/root/zed/crates/util/util.rs"))
4853 // })
4854 // .unwrap()
4855 // .clone();
4856
4857 // // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4858 // repo_from_single_file_worktree.update(cx, |repo, cx| repo.set_as_active_repository(cx));
4859 //});
4860
4861 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4862 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4863 });
4864 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4865 handle.await;
4866 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4867 pretty_assertions::assert_eq!(
4868 entries,
4869 [
4870 GitListEntry::Header(GitHeaderEntry {
4871 header: Section::Tracked
4872 }),
4873 GitListEntry::GitStatusEntry(GitStatusEntry {
4874 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4875 repo_path: "crates/gpui/gpui.rs".into(),
4876 status: StatusCode::Modified.worktree(),
4877 staging: StageStatus::Unstaged,
4878 }),
4879 GitListEntry::GitStatusEntry(GitStatusEntry {
4880 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4881 repo_path: "crates/util/util.rs".into(),
4882 status: StatusCode::Modified.worktree(),
4883 staging: StageStatus::Unstaged,
4884 },),
4885 ],
4886 );
4887 }
4888}