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