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