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