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