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