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