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