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 let commit_task = active_repository.update(cx, |repo, cx| {
1578 repo.commit(message.into(), None, options, cx)
1579 });
1580 cx.background_spawn(async move { commit_task.await? })
1581 } else {
1582 let changed_files = self
1583 .entries
1584 .iter()
1585 .filter_map(|entry| entry.status_entry())
1586 .filter(|status_entry| !status_entry.status.is_created())
1587 .map(|status_entry| status_entry.repo_path.clone())
1588 .collect::<Vec<_>>();
1589
1590 if changed_files.is_empty() {
1591 error_spawn("No changes to commit", window, cx);
1592 return;
1593 }
1594
1595 let stage_task =
1596 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1597 cx.spawn(async move |_, cx| {
1598 stage_task.await?;
1599 let commit_task = active_repository.update(cx, |repo, cx| {
1600 repo.commit(message.into(), None, options, cx)
1601 })?;
1602 commit_task.await?
1603 })
1604 };
1605 let task = cx.spawn_in(window, async move |this, cx| {
1606 let result = task.await;
1607 this.update_in(cx, |this, window, cx| {
1608 this.pending_commit.take();
1609 match result {
1610 Ok(()) => {
1611 this.commit_editor
1612 .update(cx, |editor, cx| editor.clear(window, cx));
1613 }
1614 Err(e) => this.show_error_toast("commit", e, cx),
1615 }
1616 })
1617 .ok();
1618 });
1619
1620 self.pending_commit = Some(task);
1621 }
1622
1623 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1624 let Some(repo) = self.active_repository.clone() else {
1625 return;
1626 };
1627 telemetry::event!("Git Uncommitted");
1628
1629 let confirmation = self.check_for_pushed_commits(window, cx);
1630 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1631
1632 let task = cx.spawn_in(window, async move |this, cx| {
1633 let result = maybe!(async {
1634 if let Ok(true) = confirmation.await {
1635 let prior_head = prior_head.await?;
1636
1637 repo.update(cx, |repo, cx| {
1638 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1639 })?
1640 .await??;
1641
1642 Ok(Some(prior_head))
1643 } else {
1644 Ok(None)
1645 }
1646 })
1647 .await;
1648
1649 this.update_in(cx, |this, window, cx| {
1650 this.pending_commit.take();
1651 match result {
1652 Ok(None) => {}
1653 Ok(Some(prior_commit)) => {
1654 this.commit_editor.update(cx, |editor, cx| {
1655 editor.set_text(prior_commit.message, window, cx)
1656 });
1657 }
1658 Err(e) => this.show_error_toast("reset", e, cx),
1659 }
1660 })
1661 .ok();
1662 });
1663
1664 self.pending_commit = Some(task);
1665 }
1666
1667 fn check_for_pushed_commits(
1668 &mut self,
1669 window: &mut Window,
1670 cx: &mut Context<Self>,
1671 ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
1672 let repo = self.active_repository.clone();
1673 let mut cx = window.to_async(cx);
1674
1675 async move {
1676 let repo = repo.context("No active repository")?;
1677
1678 let pushed_to: Vec<SharedString> = repo
1679 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1680 .await??;
1681
1682 if pushed_to.is_empty() {
1683 Ok(true)
1684 } else {
1685 #[derive(strum::EnumIter, strum::VariantNames)]
1686 #[strum(serialize_all = "title_case")]
1687 enum CancelUncommit {
1688 Uncommit,
1689 Cancel,
1690 }
1691 let detail = format!(
1692 "This commit was already pushed to {}.",
1693 pushed_to.into_iter().join(", ")
1694 );
1695 let result = cx
1696 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1697 .await?;
1698
1699 match result {
1700 CancelUncommit::Cancel => Ok(false),
1701 CancelUncommit::Uncommit => Ok(true),
1702 }
1703 }
1704 }
1705 }
1706
1707 /// Suggests a commit message based on the changed files and their statuses
1708 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1709 if let Some(merge_message) = self
1710 .active_repository
1711 .as_ref()
1712 .and_then(|repo| repo.read(cx).merge.message.as_ref())
1713 {
1714 return Some(merge_message.to_string());
1715 }
1716
1717 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1718 Some(staged_entry)
1719 } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1720 Some(single_tracked_entry)
1721 } else {
1722 None
1723 }?;
1724
1725 let action_text = if git_status_entry.status.is_deleted() {
1726 Some("Delete")
1727 } else if git_status_entry.status.is_created() {
1728 Some("Create")
1729 } else if git_status_entry.status.is_modified() {
1730 Some("Update")
1731 } else {
1732 None
1733 }?;
1734
1735 let file_name = git_status_entry
1736 .repo_path
1737 .file_name()
1738 .unwrap_or_default()
1739 .to_string_lossy();
1740
1741 Some(format!("{} {}", action_text, file_name))
1742 }
1743
1744 fn generate_commit_message_action(
1745 &mut self,
1746 _: &git::GenerateCommitMessage,
1747 _window: &mut Window,
1748 cx: &mut Context<Self>,
1749 ) {
1750 self.generate_commit_message(cx);
1751 }
1752
1753 /// Generates a commit message using an LLM.
1754 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1755 if !self.can_commit() {
1756 return;
1757 }
1758
1759 let model = match current_language_model(cx) {
1760 Some(value) => value,
1761 None => return,
1762 };
1763
1764 let Some(repo) = self.active_repository.as_ref() else {
1765 return;
1766 };
1767
1768 telemetry::event!("Git Commit Message Generated");
1769
1770 let diff = repo.update(cx, |repo, cx| {
1771 if self.has_staged_changes() {
1772 repo.diff(DiffType::HeadToIndex, cx)
1773 } else {
1774 repo.diff(DiffType::HeadToWorktree, cx)
1775 }
1776 });
1777
1778 let temperature = AgentSettings::temperature_for_model(&model, cx);
1779
1780 self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1781 async move {
1782 let _defer = cx.on_drop(&this, |this, _cx| {
1783 this.generate_commit_message_task.take();
1784 });
1785
1786 let mut diff_text = match diff.await {
1787 Ok(result) => match result {
1788 Ok(text) => text,
1789 Err(e) => {
1790 Self::show_commit_message_error(&this, &e, cx);
1791 return anyhow::Ok(());
1792 }
1793 },
1794 Err(e) => {
1795 Self::show_commit_message_error(&this, &e, cx);
1796 return anyhow::Ok(());
1797 }
1798 };
1799
1800 const ONE_MB: usize = 1_000_000;
1801 if diff_text.len() > ONE_MB {
1802 diff_text = diff_text.chars().take(ONE_MB).collect()
1803 }
1804
1805 let subject = this.update(cx, |this, cx| {
1806 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1807 })?;
1808
1809 let text_empty = subject.trim().is_empty();
1810
1811 let content = if text_empty {
1812 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1813 } else {
1814 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1815 };
1816
1817 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1818
1819 let request = LanguageModelRequest {
1820 thread_id: None,
1821 prompt_id: None,
1822 intent: Some(CompletionIntent::GenerateGitCommitMessage),
1823 mode: None,
1824 messages: vec![LanguageModelRequestMessage {
1825 role: Role::User,
1826 content: vec![content.into()],
1827 cache: false,
1828 }],
1829 tools: Vec::new(),
1830 tool_choice: None,
1831 stop: Vec::new(),
1832 temperature,
1833 };
1834
1835 let stream = model.stream_completion_text(request, &cx);
1836 match stream.await {
1837 Ok(mut messages) => {
1838 if !text_empty {
1839 this.update(cx, |this, cx| {
1840 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1841 let insert_position = buffer.anchor_before(buffer.len());
1842 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1843 });
1844 })?;
1845 }
1846
1847 while let Some(message) = messages.stream.next().await {
1848 match message {
1849 Ok(text) => {
1850 this.update(cx, |this, cx| {
1851 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1852 let insert_position = buffer.anchor_before(buffer.len());
1853 buffer.edit([(insert_position..insert_position, text)], None, cx);
1854 });
1855 })?;
1856 }
1857 Err(e) => {
1858 Self::show_commit_message_error(&this, &e, cx);
1859 break;
1860 }
1861 }
1862 }
1863 }
1864 Err(e) => {
1865 Self::show_commit_message_error(&this, &e, cx);
1866 }
1867 }
1868
1869 anyhow::Ok(())
1870 }
1871 .log_err().await
1872 }));
1873 }
1874
1875 fn get_fetch_options(
1876 &self,
1877 window: &mut Window,
1878 cx: &mut Context<Self>,
1879 ) -> Task<Option<FetchOptions>> {
1880 let repo = self.active_repository.clone();
1881 let workspace = self.workspace.clone();
1882
1883 cx.spawn_in(window, async move |_, cx| {
1884 let repo = repo?;
1885 let remotes = repo
1886 .update(cx, |repo, _| repo.get_remotes(None))
1887 .ok()?
1888 .await
1889 .ok()?
1890 .log_err()?;
1891
1892 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
1893 if remotes.len() > 1 {
1894 remotes.push(FetchOptions::All);
1895 }
1896 let selection = cx
1897 .update(|window, cx| {
1898 picker_prompt::prompt(
1899 "Pick which remote to fetch",
1900 remotes.iter().map(|r| r.name()).collect(),
1901 workspace,
1902 window,
1903 cx,
1904 )
1905 })
1906 .ok()?
1907 .await?;
1908 remotes.get(selection).cloned()
1909 })
1910 }
1911
1912 pub(crate) fn fetch(
1913 &mut self,
1914 is_fetch_all: bool,
1915 window: &mut Window,
1916 cx: &mut Context<Self>,
1917 ) {
1918 if !self.can_push_and_pull(cx) {
1919 return;
1920 }
1921
1922 let Some(repo) = self.active_repository.clone() else {
1923 return;
1924 };
1925 telemetry::event!("Git Fetched");
1926 let askpass = self.askpass_delegate("git fetch", window, cx);
1927 let this = cx.weak_entity();
1928
1929 let fetch_options = if is_fetch_all {
1930 Task::ready(Some(FetchOptions::All))
1931 } else {
1932 self.get_fetch_options(window, cx)
1933 };
1934
1935 window
1936 .spawn(cx, async move |cx| {
1937 let Some(fetch_options) = fetch_options.await else {
1938 return Ok(());
1939 };
1940 let fetch = repo.update(cx, |repo, cx| {
1941 repo.fetch(fetch_options.clone(), askpass, cx)
1942 })?;
1943
1944 let remote_message = fetch.await?;
1945 this.update(cx, |this, cx| {
1946 let action = match fetch_options {
1947 FetchOptions::All => RemoteAction::Fetch(None),
1948 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
1949 };
1950 match remote_message {
1951 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1952 Err(e) => {
1953 log::error!("Error while fetching {:?}", e);
1954 this.show_error_toast(action.name(), e, cx)
1955 }
1956 }
1957
1958 anyhow::Ok(())
1959 })
1960 .ok();
1961 anyhow::Ok(())
1962 })
1963 .detach_and_log_err(cx);
1964 }
1965
1966 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1967 let worktrees = self
1968 .project
1969 .read(cx)
1970 .visible_worktrees(cx)
1971 .collect::<Vec<_>>();
1972
1973 let worktree = if worktrees.len() == 1 {
1974 Task::ready(Some(worktrees.first().unwrap().clone()))
1975 } else if worktrees.len() == 0 {
1976 let result = window.prompt(
1977 PromptLevel::Warning,
1978 "Unable to initialize a git repository",
1979 Some("Open a directory first"),
1980 &["Ok"],
1981 cx,
1982 );
1983 cx.background_executor()
1984 .spawn(async move {
1985 result.await.ok();
1986 })
1987 .detach();
1988 return;
1989 } else {
1990 let worktree_directories = worktrees
1991 .iter()
1992 .map(|worktree| worktree.read(cx).abs_path())
1993 .map(|worktree_abs_path| {
1994 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
1995 Path::new("~")
1996 .join(path)
1997 .to_string_lossy()
1998 .to_string()
1999 .into()
2000 } else {
2001 worktree_abs_path.to_string_lossy().to_string().into()
2002 }
2003 })
2004 .collect_vec();
2005 let prompt = picker_prompt::prompt(
2006 "Where would you like to initialize this git repository?",
2007 worktree_directories,
2008 self.workspace.clone(),
2009 window,
2010 cx,
2011 );
2012
2013 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2014 };
2015
2016 cx.spawn_in(window, async move |this, cx| {
2017 let worktree = match worktree.await {
2018 Some(worktree) => worktree,
2019 None => {
2020 return;
2021 }
2022 };
2023
2024 let Ok(result) = this.update(cx, |this, cx| {
2025 let fallback_branch_name = GitPanelSettings::get_global(cx)
2026 .fallback_branch_name
2027 .clone();
2028 this.project.read(cx).git_init(
2029 worktree.read(cx).abs_path(),
2030 fallback_branch_name,
2031 cx,
2032 )
2033 }) else {
2034 return;
2035 };
2036
2037 let result = result.await;
2038
2039 this.update_in(cx, |this, _, cx| match result {
2040 Ok(()) => {}
2041 Err(e) => this.show_error_toast("init", e, cx),
2042 })
2043 .ok();
2044 })
2045 .detach();
2046 }
2047
2048 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2049 if !self.can_push_and_pull(cx) {
2050 return;
2051 }
2052 let Some(repo) = self.active_repository.clone() else {
2053 return;
2054 };
2055 let Some(branch) = repo.read(cx).branch.as_ref() else {
2056 return;
2057 };
2058 telemetry::event!("Git Pulled");
2059 let branch = branch.clone();
2060 let remote = self.get_remote(false, window, cx);
2061 cx.spawn_in(window, async move |this, cx| {
2062 let remote = match remote.await {
2063 Ok(Some(remote)) => remote,
2064 Ok(None) => {
2065 return Ok(());
2066 }
2067 Err(e) => {
2068 log::error!("Failed to get current remote: {}", e);
2069 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2070 .ok();
2071 return Ok(());
2072 }
2073 };
2074
2075 let askpass = this.update_in(cx, |this, window, cx| {
2076 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2077 })?;
2078
2079 let pull = repo.update(cx, |repo, cx| {
2080 repo.pull(
2081 branch.name().to_owned().into(),
2082 remote.name.clone(),
2083 askpass,
2084 cx,
2085 )
2086 })?;
2087
2088 let remote_message = pull.await?;
2089
2090 let action = RemoteAction::Pull(remote);
2091 this.update(cx, |this, cx| match remote_message {
2092 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2093 Err(e) => {
2094 log::error!("Error while pulling {:?}", e);
2095 this.show_error_toast(action.name(), e, cx)
2096 }
2097 })
2098 .ok();
2099
2100 anyhow::Ok(())
2101 })
2102 .detach_and_log_err(cx);
2103 }
2104
2105 pub(crate) fn push(
2106 &mut self,
2107 force_push: bool,
2108 select_remote: bool,
2109 window: &mut Window,
2110 cx: &mut Context<Self>,
2111 ) {
2112 if !self.can_push_and_pull(cx) {
2113 return;
2114 }
2115 let Some(repo) = self.active_repository.clone() else {
2116 return;
2117 };
2118 let Some(branch) = repo.read(cx).branch.as_ref() else {
2119 return;
2120 };
2121 telemetry::event!("Git Pushed");
2122 let branch = branch.clone();
2123
2124 let options = if force_push {
2125 Some(PushOptions::Force)
2126 } else {
2127 match branch.upstream {
2128 Some(Upstream {
2129 tracking: UpstreamTracking::Gone,
2130 ..
2131 })
2132 | None => Some(PushOptions::SetUpstream),
2133 _ => None,
2134 }
2135 };
2136 let remote = self.get_remote(select_remote, window, cx);
2137
2138 cx.spawn_in(window, async move |this, cx| {
2139 let remote = match remote.await {
2140 Ok(Some(remote)) => remote,
2141 Ok(None) => {
2142 return Ok(());
2143 }
2144 Err(e) => {
2145 log::error!("Failed to get current remote: {}", e);
2146 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2147 .ok();
2148 return Ok(());
2149 }
2150 };
2151
2152 let askpass_delegate = this.update_in(cx, |this, window, cx| {
2153 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2154 })?;
2155
2156 let push = repo.update(cx, |repo, cx| {
2157 repo.push(
2158 branch.name().to_owned().into(),
2159 remote.name.clone(),
2160 options,
2161 askpass_delegate,
2162 cx,
2163 )
2164 })?;
2165
2166 let remote_output = push.await?;
2167
2168 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2169 this.update(cx, |this, cx| match remote_output {
2170 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2171 Err(e) => {
2172 log::error!("Error while pushing {:?}", e);
2173 this.show_error_toast(action.name(), e, cx)
2174 }
2175 })?;
2176
2177 anyhow::Ok(())
2178 })
2179 .detach_and_log_err(cx);
2180 }
2181
2182 fn askpass_delegate(
2183 &self,
2184 operation: impl Into<SharedString>,
2185 window: &mut Window,
2186 cx: &mut Context<Self>,
2187 ) -> AskPassDelegate {
2188 let this = cx.weak_entity();
2189 let operation = operation.into();
2190 let window = window.window_handle();
2191 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2192 window
2193 .update(cx, |_, window, cx| {
2194 this.update(cx, |this, cx| {
2195 this.workspace.update(cx, |workspace, cx| {
2196 workspace.toggle_modal(window, cx, |window, cx| {
2197 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2198 });
2199 })
2200 })
2201 })
2202 .ok();
2203 })
2204 }
2205
2206 fn can_push_and_pull(&self, cx: &App) -> bool {
2207 !self.project.read(cx).is_via_collab()
2208 }
2209
2210 fn get_remote(
2211 &mut self,
2212 always_select: bool,
2213 window: &mut Window,
2214 cx: &mut Context<Self>,
2215 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2216 let repo = self.active_repository.clone();
2217 let workspace = self.workspace.clone();
2218 let mut cx = window.to_async(cx);
2219
2220 async move {
2221 let repo = repo.context("No active repository")?;
2222 let current_remotes: Vec<Remote> = repo
2223 .update(&mut cx, |repo, _| {
2224 let current_branch = if always_select {
2225 None
2226 } else {
2227 let current_branch = repo.branch.as_ref().context("No active branch")?;
2228 Some(current_branch.name().to_string())
2229 };
2230 anyhow::Ok(repo.get_remotes(current_branch))
2231 })??
2232 .await??;
2233
2234 let current_remotes: Vec<_> = current_remotes
2235 .into_iter()
2236 .map(|remotes| remotes.name)
2237 .collect();
2238 let selection = cx
2239 .update(|window, cx| {
2240 picker_prompt::prompt(
2241 "Pick which remote to push to",
2242 current_remotes.clone(),
2243 workspace,
2244 window,
2245 cx,
2246 )
2247 })?
2248 .await;
2249
2250 Ok(selection.map(|selection| Remote {
2251 name: current_remotes[selection].clone(),
2252 }))
2253 }
2254 }
2255
2256 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2257 if self.local_committer_task.is_none() {
2258 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2259 let committer = get_git_committer(cx).await;
2260 this.update(cx, |this, cx| {
2261 this.local_committer = Some(committer);
2262 cx.notify()
2263 })
2264 .ok();
2265 }));
2266 }
2267 }
2268
2269 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2270 let mut new_co_authors = Vec::new();
2271 let project = self.project.read(cx);
2272
2273 let Some(room) = self
2274 .workspace
2275 .upgrade()
2276 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2277 else {
2278 return Vec::default();
2279 };
2280
2281 let room = room.read(cx);
2282
2283 for (peer_id, collaborator) in project.collaborators() {
2284 if collaborator.is_host {
2285 continue;
2286 }
2287
2288 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2289 continue;
2290 };
2291 if !participant.can_write() {
2292 continue;
2293 }
2294 if let Some(email) = &collaborator.committer_email {
2295 let name = collaborator
2296 .committer_name
2297 .clone()
2298 .or_else(|| participant.user.name.clone())
2299 .unwrap_or_else(|| participant.user.github_login.clone());
2300 new_co_authors.push((name.clone(), email.clone()))
2301 }
2302 }
2303 if !project.is_local() && !project.is_read_only(cx) {
2304 if let Some(local_committer) = self.local_committer(room, cx) {
2305 new_co_authors.push(local_committer);
2306 }
2307 }
2308 new_co_authors
2309 }
2310
2311 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2312 let user = room.local_participant_user(cx)?;
2313 let committer = self.local_committer.as_ref()?;
2314 let email = committer.email.clone()?;
2315 let name = committer
2316 .name
2317 .clone()
2318 .or_else(|| user.name.clone())
2319 .unwrap_or_else(|| user.github_login.clone());
2320 Some((name, email))
2321 }
2322
2323 fn toggle_fill_co_authors(
2324 &mut self,
2325 _: &ToggleFillCoAuthors,
2326 _: &mut Window,
2327 cx: &mut Context<Self>,
2328 ) {
2329 self.add_coauthors = !self.add_coauthors;
2330 cx.notify();
2331 }
2332
2333 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2334 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2335
2336 let existing_text = message.to_ascii_lowercase();
2337 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2338 let mut ends_with_co_authors = false;
2339 let existing_co_authors = existing_text
2340 .lines()
2341 .filter_map(|line| {
2342 let line = line.trim();
2343 if line.starts_with(&lowercase_co_author_prefix) {
2344 ends_with_co_authors = true;
2345 Some(line)
2346 } else {
2347 ends_with_co_authors = false;
2348 None
2349 }
2350 })
2351 .collect::<HashSet<_>>();
2352
2353 let new_co_authors = self
2354 .potential_co_authors(cx)
2355 .into_iter()
2356 .filter(|(_, email)| {
2357 !existing_co_authors
2358 .iter()
2359 .any(|existing| existing.contains(email.as_str()))
2360 })
2361 .collect::<Vec<_>>();
2362
2363 if new_co_authors.is_empty() {
2364 return;
2365 }
2366
2367 if !ends_with_co_authors {
2368 message.push('\n');
2369 }
2370 for (name, email) in new_co_authors {
2371 message.push('\n');
2372 message.push_str(CO_AUTHOR_PREFIX);
2373 message.push_str(&name);
2374 message.push_str(" <");
2375 message.push_str(&email);
2376 message.push('>');
2377 }
2378 message.push('\n');
2379 }
2380
2381 fn schedule_update(
2382 &mut self,
2383 clear_pending: bool,
2384 window: &mut Window,
2385 cx: &mut Context<Self>,
2386 ) {
2387 let handle = cx.entity().downgrade();
2388 self.reopen_commit_buffer(window, cx);
2389 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2390 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2391 if let Some(git_panel) = handle.upgrade() {
2392 git_panel
2393 .update_in(cx, |git_panel, window, cx| {
2394 if clear_pending {
2395 git_panel.clear_pending();
2396 }
2397 git_panel.update_visible_entries(cx);
2398 git_panel.update_scrollbar_properties(window, cx);
2399 })
2400 .ok();
2401 }
2402 });
2403 }
2404
2405 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2406 let Some(active_repo) = self.active_repository.as_ref() else {
2407 return;
2408 };
2409 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2410 let project = self.project.read(cx);
2411 active_repo.open_commit_buffer(
2412 Some(project.languages().clone()),
2413 project.buffer_store().clone(),
2414 cx,
2415 )
2416 });
2417
2418 cx.spawn_in(window, async move |git_panel, cx| {
2419 let buffer = load_buffer.await?;
2420 git_panel.update_in(cx, |git_panel, window, cx| {
2421 if git_panel
2422 .commit_editor
2423 .read(cx)
2424 .buffer()
2425 .read(cx)
2426 .as_singleton()
2427 .as_ref()
2428 != Some(&buffer)
2429 {
2430 git_panel.commit_editor = cx.new(|cx| {
2431 commit_message_editor(
2432 buffer,
2433 git_panel.suggest_commit_message(cx).map(SharedString::from),
2434 git_panel.project.clone(),
2435 true,
2436 window,
2437 cx,
2438 )
2439 });
2440 }
2441 })
2442 })
2443 .detach_and_log_err(cx);
2444 }
2445
2446 fn clear_pending(&mut self) {
2447 self.pending.retain(|v| !v.finished)
2448 }
2449
2450 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2451 self.entries.clear();
2452 self.single_staged_entry.take();
2453 self.single_tracked_entry.take();
2454 self.conflicted_count = 0;
2455 self.conflicted_staged_count = 0;
2456 self.new_count = 0;
2457 self.tracked_count = 0;
2458 self.new_staged_count = 0;
2459 self.tracked_staged_count = 0;
2460 self.entry_count = 0;
2461
2462 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2463
2464 let mut changed_entries = Vec::new();
2465 let mut new_entries = Vec::new();
2466 let mut conflict_entries = Vec::new();
2467 let mut last_staged = None;
2468 let mut staged_count = 0;
2469 let mut max_width_item: Option<(RepoPath, usize)> = None;
2470
2471 let Some(repo) = self.active_repository.as_ref() else {
2472 // Just clear entries if no repository is active.
2473 cx.notify();
2474 return;
2475 };
2476
2477 let repo = repo.read(cx);
2478
2479 for entry in repo.cached_status() {
2480 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2481 let is_new = entry.status.is_created();
2482 let staging = entry.status.staging();
2483
2484 if self.pending.iter().any(|pending| {
2485 pending.target_status == TargetStatus::Reverted
2486 && !pending.finished
2487 && pending
2488 .entries
2489 .iter()
2490 .any(|pending| pending.repo_path == entry.repo_path)
2491 }) {
2492 continue;
2493 }
2494
2495 let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2496 let entry = GitStatusEntry {
2497 repo_path: entry.repo_path.clone(),
2498 abs_path,
2499 status: entry.status,
2500 staging,
2501 };
2502
2503 if staging.has_staged() {
2504 staged_count += 1;
2505 last_staged = Some(entry.clone());
2506 }
2507
2508 let width_estimate = Self::item_width_estimate(
2509 entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2510 entry.display_name().len(),
2511 );
2512
2513 match max_width_item.as_mut() {
2514 Some((repo_path, estimate)) => {
2515 if width_estimate > *estimate {
2516 *repo_path = entry.repo_path.clone();
2517 *estimate = width_estimate;
2518 }
2519 }
2520 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2521 }
2522
2523 if sort_by_path {
2524 changed_entries.push(entry);
2525 } else if is_conflict {
2526 conflict_entries.push(entry);
2527 } else if is_new {
2528 new_entries.push(entry);
2529 } else {
2530 changed_entries.push(entry);
2531 }
2532 }
2533
2534 let mut pending_staged_count = 0;
2535 let mut last_pending_staged = None;
2536 let mut pending_status_for_last_staged = None;
2537 for pending in self.pending.iter() {
2538 if pending.target_status == TargetStatus::Staged {
2539 pending_staged_count += pending.entries.len();
2540 last_pending_staged = pending.entries.iter().next().cloned();
2541 }
2542 if let Some(last_staged) = &last_staged {
2543 if pending
2544 .entries
2545 .iter()
2546 .any(|entry| entry.repo_path == last_staged.repo_path)
2547 {
2548 pending_status_for_last_staged = Some(pending.target_status);
2549 }
2550 }
2551 }
2552
2553 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2554 match pending_status_for_last_staged {
2555 Some(TargetStatus::Staged) | None => {
2556 self.single_staged_entry = last_staged;
2557 }
2558 _ => {}
2559 }
2560 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2561 self.single_staged_entry = last_pending_staged;
2562 }
2563
2564 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2565 self.single_tracked_entry = changed_entries.first().cloned();
2566 }
2567
2568 if conflict_entries.len() > 0 {
2569 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2570 header: Section::Conflict,
2571 }));
2572 self.entries.extend(
2573 conflict_entries
2574 .into_iter()
2575 .map(GitListEntry::GitStatusEntry),
2576 );
2577 }
2578
2579 if changed_entries.len() > 0 {
2580 if !sort_by_path {
2581 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2582 header: Section::Tracked,
2583 }));
2584 }
2585 self.entries.extend(
2586 changed_entries
2587 .into_iter()
2588 .map(GitListEntry::GitStatusEntry),
2589 );
2590 }
2591 if new_entries.len() > 0 {
2592 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2593 header: Section::New,
2594 }));
2595 self.entries
2596 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2597 }
2598
2599 if let Some((repo_path, _)) = max_width_item {
2600 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2601 GitListEntry::GitStatusEntry(git_status_entry) => {
2602 git_status_entry.repo_path == repo_path
2603 }
2604 GitListEntry::Header(_) => false,
2605 });
2606 }
2607
2608 self.update_counts(repo);
2609
2610 self.select_first_entry_if_none(cx);
2611
2612 let suggested_commit_message = self.suggest_commit_message(cx);
2613 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2614
2615 self.commit_editor.update(cx, |editor, cx| {
2616 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2617 });
2618
2619 cx.notify();
2620 }
2621
2622 fn header_state(&self, header_type: Section) -> ToggleState {
2623 let (staged_count, count) = match header_type {
2624 Section::New => (self.new_staged_count, self.new_count),
2625 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2626 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2627 };
2628 if staged_count == 0 {
2629 ToggleState::Unselected
2630 } else if count == staged_count {
2631 ToggleState::Selected
2632 } else {
2633 ToggleState::Indeterminate
2634 }
2635 }
2636
2637 fn update_counts(&mut self, repo: &Repository) {
2638 self.show_placeholders = false;
2639 self.conflicted_count = 0;
2640 self.conflicted_staged_count = 0;
2641 self.new_count = 0;
2642 self.tracked_count = 0;
2643 self.new_staged_count = 0;
2644 self.tracked_staged_count = 0;
2645 self.entry_count = 0;
2646 for entry in &self.entries {
2647 let Some(status_entry) = entry.status_entry() else {
2648 continue;
2649 };
2650 self.entry_count += 1;
2651 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2652 self.conflicted_count += 1;
2653 if self.entry_staging(status_entry).has_staged() {
2654 self.conflicted_staged_count += 1;
2655 }
2656 } else if status_entry.status.is_created() {
2657 self.new_count += 1;
2658 if self.entry_staging(status_entry).has_staged() {
2659 self.new_staged_count += 1;
2660 }
2661 } else {
2662 self.tracked_count += 1;
2663 if self.entry_staging(status_entry).has_staged() {
2664 self.tracked_staged_count += 1;
2665 }
2666 }
2667 }
2668 }
2669
2670 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2671 for pending in self.pending.iter().rev() {
2672 if pending
2673 .entries
2674 .iter()
2675 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2676 {
2677 match pending.target_status {
2678 TargetStatus::Staged => return StageStatus::Staged,
2679 TargetStatus::Unstaged => return StageStatus::Unstaged,
2680 TargetStatus::Reverted => continue,
2681 TargetStatus::Unchanged => continue,
2682 }
2683 }
2684 }
2685 entry.staging
2686 }
2687
2688 pub(crate) fn has_staged_changes(&self) -> bool {
2689 self.tracked_staged_count > 0
2690 || self.new_staged_count > 0
2691 || self.conflicted_staged_count > 0
2692 }
2693
2694 pub(crate) fn has_unstaged_changes(&self) -> bool {
2695 self.tracked_count > self.tracked_staged_count
2696 || self.new_count > self.new_staged_count
2697 || self.conflicted_count > self.conflicted_staged_count
2698 }
2699
2700 fn has_tracked_changes(&self) -> bool {
2701 self.tracked_count > 0
2702 }
2703
2704 pub fn has_unstaged_conflicts(&self) -> bool {
2705 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2706 }
2707
2708 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2709 let action = action.into();
2710 let Some(workspace) = self.workspace.upgrade() else {
2711 return;
2712 };
2713
2714 let message = e.to_string().trim().to_string();
2715 if message
2716 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2717 .next()
2718 .is_some()
2719 {
2720 return; // Hide the cancelled by user message
2721 } else {
2722 workspace.update(cx, |workspace, cx| {
2723 let workspace_weak = cx.weak_entity();
2724 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2725 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2726 .action("View Log", move |window, cx| {
2727 let message = message.clone();
2728 let action = action.clone();
2729 workspace_weak
2730 .update(cx, move |workspace, cx| {
2731 Self::open_output(action, workspace, &message, window, cx)
2732 })
2733 .ok();
2734 })
2735 });
2736 workspace.toggle_status_toast(toast, cx)
2737 });
2738 }
2739 }
2740
2741 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2742 where
2743 E: std::fmt::Debug + std::fmt::Display,
2744 {
2745 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2746 let _ = workspace.update(cx, |workspace, cx| {
2747 struct CommitMessageError;
2748 let notification_id = NotificationId::unique::<CommitMessageError>();
2749 workspace.show_notification(notification_id, cx, |cx| {
2750 cx.new(|cx| {
2751 ErrorMessagePrompt::new(
2752 format!("Failed to generate commit message: {err}"),
2753 cx,
2754 )
2755 })
2756 });
2757 });
2758 }
2759 }
2760
2761 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2762 let Some(workspace) = self.workspace.upgrade() else {
2763 return;
2764 };
2765
2766 workspace.update(cx, |workspace, cx| {
2767 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2768 let workspace_weak = cx.weak_entity();
2769 let operation = action.name();
2770
2771 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2772 use remote_output::SuccessStyle::*;
2773 match style {
2774 Toast { .. } => this,
2775 ToastWithLog { output } => this
2776 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2777 .action("View Log", move |window, cx| {
2778 let output = output.clone();
2779 let output =
2780 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2781 workspace_weak
2782 .update(cx, move |workspace, cx| {
2783 Self::open_output(operation, workspace, &output, window, cx)
2784 })
2785 .ok();
2786 }),
2787 PushPrLink { link } => this
2788 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2789 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2790 }
2791 });
2792 workspace.toggle_status_toast(status_toast, cx)
2793 });
2794 }
2795
2796 fn open_output(
2797 operation: impl Into<SharedString>,
2798 workspace: &mut Workspace,
2799 output: &str,
2800 window: &mut Window,
2801 cx: &mut Context<Workspace>,
2802 ) {
2803 let operation = operation.into();
2804 let buffer = cx.new(|cx| Buffer::local(output, cx));
2805 buffer.update(cx, |buffer, cx| {
2806 buffer.set_capability(language::Capability::ReadOnly, cx);
2807 });
2808 let editor = cx.new(|cx| {
2809 let mut editor = Editor::for_buffer(buffer, None, window, cx);
2810 editor.buffer().update(cx, |buffer, cx| {
2811 buffer.set_title(format!("Output from git {operation}"), cx);
2812 });
2813 editor.set_read_only(true);
2814 editor
2815 });
2816
2817 workspace.add_item_to_center(Box::new(editor), window, cx);
2818 }
2819
2820 pub fn can_commit(&self) -> bool {
2821 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2822 }
2823
2824 pub fn can_stage_all(&self) -> bool {
2825 self.has_unstaged_changes()
2826 }
2827
2828 pub fn can_unstage_all(&self) -> bool {
2829 self.has_staged_changes()
2830 }
2831
2832 // eventually we'll need to take depth into account here
2833 // if we add a tree view
2834 fn item_width_estimate(path: usize, file_name: usize) -> usize {
2835 path + file_name
2836 }
2837
2838 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2839 let focus_handle = self.focus_handle.clone();
2840 let has_tracked_changes = self.has_tracked_changes();
2841 let has_staged_changes = self.has_staged_changes();
2842 let has_unstaged_changes = self.has_unstaged_changes();
2843 let has_new_changes = self.new_count > 0;
2844
2845 PopoverMenu::new(id.into())
2846 .trigger(
2847 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2848 .icon_size(IconSize::Small)
2849 .icon_color(Color::Muted),
2850 )
2851 .menu(move |window, cx| {
2852 Some(git_panel_context_menu(
2853 focus_handle.clone(),
2854 GitMenuState {
2855 has_tracked_changes,
2856 has_staged_changes,
2857 has_unstaged_changes,
2858 has_new_changes,
2859 },
2860 window,
2861 cx,
2862 ))
2863 })
2864 .anchor(Corner::TopRight)
2865 }
2866
2867 pub(crate) fn render_generate_commit_message_button(
2868 &self,
2869 cx: &Context<Self>,
2870 ) -> Option<AnyElement> {
2871 current_language_model(cx).is_some().then(|| {
2872 if self.generate_commit_message_task.is_some() {
2873 return h_flex()
2874 .gap_1()
2875 .child(
2876 Icon::new(IconName::ArrowCircle)
2877 .size(IconSize::XSmall)
2878 .color(Color::Info)
2879 .with_animation(
2880 "arrow-circle",
2881 Animation::new(Duration::from_secs(2)).repeat(),
2882 |icon, delta| {
2883 icon.transform(Transformation::rotate(percentage(delta)))
2884 },
2885 ),
2886 )
2887 .child(
2888 Label::new("Generating Commit...")
2889 .size(LabelSize::Small)
2890 .color(Color::Muted),
2891 )
2892 .into_any_element();
2893 }
2894
2895 let can_commit = self.can_commit();
2896 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2897 IconButton::new("generate-commit-message", IconName::AiEdit)
2898 .shape(ui::IconButtonShape::Square)
2899 .icon_color(Color::Muted)
2900 .tooltip(move |window, cx| {
2901 if can_commit {
2902 Tooltip::for_action_in(
2903 "Generate Commit Message",
2904 &git::GenerateCommitMessage,
2905 &editor_focus_handle,
2906 window,
2907 cx,
2908 )
2909 } else {
2910 Tooltip::simple("No changes to commit", cx)
2911 }
2912 })
2913 .disabled(!can_commit)
2914 .on_click(cx.listener(move |this, _event, _window, cx| {
2915 this.generate_commit_message(cx);
2916 }))
2917 .into_any_element()
2918 })
2919 }
2920
2921 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2922 let potential_co_authors = self.potential_co_authors(cx);
2923
2924 let (tooltip_label, icon) = if self.add_coauthors {
2925 ("Remove co-authored-by", IconName::Person)
2926 } else {
2927 ("Add co-authored-by", IconName::UserCheck)
2928 };
2929
2930 if potential_co_authors.is_empty() {
2931 None
2932 } else {
2933 Some(
2934 IconButton::new("co-authors", icon)
2935 .shape(ui::IconButtonShape::Square)
2936 .icon_color(Color::Disabled)
2937 .selected_icon_color(Color::Selected)
2938 .toggle_state(self.add_coauthors)
2939 .tooltip(move |_, cx| {
2940 let title = format!(
2941 "{}:{}{}",
2942 tooltip_label,
2943 if potential_co_authors.len() == 1 {
2944 ""
2945 } else {
2946 "\n"
2947 },
2948 potential_co_authors
2949 .iter()
2950 .map(|(name, email)| format!(" {} <{}>", name, email))
2951 .join("\n")
2952 );
2953 Tooltip::simple(title, cx)
2954 })
2955 .on_click(cx.listener(|this, _, _, cx| {
2956 this.add_coauthors = !this.add_coauthors;
2957 cx.notify();
2958 }))
2959 .into_any_element(),
2960 )
2961 }
2962 }
2963
2964 fn render_git_commit_menu(
2965 &self,
2966 id: impl Into<ElementId>,
2967 keybinding_target: Option<FocusHandle>,
2968 ) -> impl IntoElement {
2969 PopoverMenu::new(id.into())
2970 .trigger(
2971 ui::ButtonLike::new_rounded_right("commit-split-button-right")
2972 .layer(ui::ElevationIndex::ModalSurface)
2973 .size(ui::ButtonSize::None)
2974 .child(
2975 div()
2976 .px_1()
2977 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
2978 ),
2979 )
2980 .menu(move |window, cx| {
2981 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
2982 context_menu
2983 .when_some(keybinding_target.clone(), |el, keybinding_target| {
2984 el.context(keybinding_target.clone())
2985 })
2986 .action("Amend", Amend.boxed_clone())
2987 }))
2988 })
2989 .anchor(Corner::TopRight)
2990 }
2991
2992 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2993 if self.has_unstaged_conflicts() {
2994 (false, "You must resolve conflicts before committing")
2995 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2996 (false, "No changes to commit")
2997 } else if self.pending_commit.is_some() {
2998 (false, "Commit in progress")
2999 } else if !self.has_commit_message(cx) {
3000 (false, "No commit message")
3001 } else if !self.has_write_access(cx) {
3002 (false, "You do not have write access to this project")
3003 } else {
3004 (true, self.commit_button_title())
3005 }
3006 }
3007
3008 pub fn commit_button_title(&self) -> &'static str {
3009 if self.amend_pending {
3010 if self.has_staged_changes() {
3011 "Amend"
3012 } else {
3013 "Amend Tracked"
3014 }
3015 } else {
3016 if self.has_staged_changes() {
3017 "Commit"
3018 } else {
3019 "Commit Tracked"
3020 }
3021 }
3022 }
3023
3024 fn expand_commit_editor(
3025 &mut self,
3026 _: &git::ExpandCommitEditor,
3027 window: &mut Window,
3028 cx: &mut Context<Self>,
3029 ) {
3030 let workspace = self.workspace.clone();
3031 window.defer(cx, move |window, cx| {
3032 workspace
3033 .update(cx, |workspace, cx| {
3034 CommitModal::toggle(workspace, None, window, cx)
3035 })
3036 .ok();
3037 })
3038 }
3039
3040 fn render_panel_header(
3041 &self,
3042 window: &mut Window,
3043 cx: &mut Context<Self>,
3044 ) -> Option<impl IntoElement> {
3045 self.active_repository.as_ref()?;
3046
3047 let text;
3048 let action;
3049 let tooltip;
3050 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3051 text = "Unstage All";
3052 action = git::UnstageAll.boxed_clone();
3053 tooltip = "git reset";
3054 } else {
3055 text = "Stage All";
3056 action = git::StageAll.boxed_clone();
3057 tooltip = "git add --all ."
3058 }
3059
3060 let change_string = match self.entry_count {
3061 0 => "No Changes".to_string(),
3062 1 => "1 Change".to_string(),
3063 _ => format!("{} Changes", self.entry_count),
3064 };
3065
3066 Some(
3067 self.panel_header_container(window, cx)
3068 .px_2()
3069 .child(
3070 panel_button(change_string)
3071 .color(Color::Muted)
3072 .tooltip(Tooltip::for_action_title_in(
3073 "Open Diff",
3074 &Diff,
3075 &self.focus_handle,
3076 ))
3077 .on_click(|_, _, cx| {
3078 cx.defer(|cx| {
3079 cx.dispatch_action(&Diff);
3080 })
3081 }),
3082 )
3083 .child(div().flex_grow()) // spacer
3084 .child(self.render_overflow_menu("overflow_menu"))
3085 .child(div().w_2()) // another spacer
3086 .child(
3087 panel_filled_button(text)
3088 .tooltip(Tooltip::for_action_title_in(
3089 tooltip,
3090 action.as_ref(),
3091 &self.focus_handle,
3092 ))
3093 .disabled(self.entry_count == 0)
3094 .on_click(move |_, _, cx| {
3095 let action = action.boxed_clone();
3096 cx.defer(move |cx| {
3097 cx.dispatch_action(action.as_ref());
3098 })
3099 }),
3100 ),
3101 )
3102 }
3103
3104 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3105 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3106 if !self.can_push_and_pull(cx) {
3107 return None;
3108 }
3109 Some(
3110 h_flex()
3111 .gap_1()
3112 .flex_shrink_0()
3113 .when_some(branch, |this, branch| {
3114 let focus_handle = Some(self.focus_handle(cx));
3115
3116 this.children(render_remote_button(
3117 "remote-button",
3118 &branch,
3119 focus_handle,
3120 true,
3121 ))
3122 })
3123 .into_any_element(),
3124 )
3125 }
3126
3127 pub fn render_footer(
3128 &self,
3129 window: &mut Window,
3130 cx: &mut Context<Self>,
3131 ) -> Option<impl IntoElement> {
3132 let active_repository = self.active_repository.clone()?;
3133 let panel_editor_style = panel_editor_style(true, window, cx);
3134
3135 let enable_coauthors = self.render_co_authors(cx);
3136
3137 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3138 let expand_tooltip_focus_handle = editor_focus_handle.clone();
3139
3140 let branch = active_repository.read(cx).branch.clone();
3141 let head_commit = active_repository.read(cx).head_commit.clone();
3142
3143 let footer_size = px(32.);
3144 let gap = px(9.0);
3145 let max_height = panel_editor_style
3146 .text
3147 .line_height_in_pixels(window.rem_size())
3148 * MAX_PANEL_EDITOR_LINES
3149 + gap;
3150
3151 let git_panel = cx.entity().clone();
3152 let display_name = SharedString::from(Arc::from(
3153 active_repository
3154 .read(cx)
3155 .display_name()
3156 .trim_end_matches("/"),
3157 ));
3158 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3159 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3160 });
3161 let has_previous_commit = head_commit.is_some();
3162
3163 let footer = v_flex()
3164 .child(PanelRepoFooter::new(
3165 display_name,
3166 branch,
3167 head_commit,
3168 Some(git_panel.clone()),
3169 ))
3170 .child(
3171 panel_editor_container(window, cx)
3172 .id("commit-editor-container")
3173 .relative()
3174 .w_full()
3175 .h(max_height + footer_size)
3176 .border_t_1()
3177 .border_color(cx.theme().colors().border_variant)
3178 .cursor_text()
3179 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3180 window.focus(&this.commit_editor.focus_handle(cx));
3181 }))
3182 .child(
3183 h_flex()
3184 .id("commit-footer")
3185 .border_t_1()
3186 .when(editor_is_long, |el| {
3187 el.border_color(cx.theme().colors().border_variant)
3188 })
3189 .absolute()
3190 .bottom_0()
3191 .left_0()
3192 .w_full()
3193 .px_2()
3194 .h(footer_size)
3195 .flex_none()
3196 .justify_between()
3197 .child(
3198 self.render_generate_commit_message_button(cx)
3199 .unwrap_or_else(|| div().into_any_element()),
3200 )
3201 .child(
3202 h_flex()
3203 .gap_0p5()
3204 .children(enable_coauthors)
3205 .child(self.render_commit_button(has_previous_commit, cx)),
3206 ),
3207 )
3208 .child(
3209 div()
3210 .pr_2p5()
3211 .on_action(|&editor::actions::MoveUp, _, cx| {
3212 cx.stop_propagation();
3213 })
3214 .on_action(|&editor::actions::MoveDown, _, cx| {
3215 cx.stop_propagation();
3216 })
3217 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3218 )
3219 .child(
3220 h_flex()
3221 .absolute()
3222 .top_2()
3223 .right_2()
3224 .opacity(0.5)
3225 .hover(|this| this.opacity(1.0))
3226 .child(
3227 panel_icon_button("expand-commit-editor", IconName::Maximize)
3228 .icon_size(IconSize::Small)
3229 .size(ui::ButtonSize::Default)
3230 .tooltip(move |window, cx| {
3231 Tooltip::for_action_in(
3232 "Open Commit Modal",
3233 &git::ExpandCommitEditor,
3234 &expand_tooltip_focus_handle,
3235 window,
3236 cx,
3237 )
3238 })
3239 .on_click(cx.listener({
3240 move |_, _, window, cx| {
3241 window.dispatch_action(
3242 git::ExpandCommitEditor.boxed_clone(),
3243 cx,
3244 )
3245 }
3246 })),
3247 ),
3248 ),
3249 );
3250
3251 Some(footer)
3252 }
3253
3254 fn render_commit_button(
3255 &self,
3256 has_previous_commit: bool,
3257 cx: &mut Context<Self>,
3258 ) -> impl IntoElement {
3259 let (can_commit, tooltip) = self.configure_commit_button(cx);
3260 let title = self.commit_button_title();
3261 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3262 div()
3263 .id("commit-wrapper")
3264 .on_hover(cx.listener(move |this, hovered, _, cx| {
3265 this.show_placeholders =
3266 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3267 cx.notify()
3268 }))
3269 .when(self.amend_pending, {
3270 |this| {
3271 this.h_flex()
3272 .gap_1()
3273 .child(
3274 panel_filled_button("Cancel")
3275 .tooltip({
3276 let handle = commit_tooltip_focus_handle.clone();
3277 move |window, cx| {
3278 Tooltip::for_action_in(
3279 "Cancel amend",
3280 &git::Cancel,
3281 &handle,
3282 window,
3283 cx,
3284 )
3285 }
3286 })
3287 .on_click(move |_, window, cx| {
3288 window.dispatch_action(Box::new(git::Cancel), cx);
3289 }),
3290 )
3291 .child(
3292 panel_filled_button(title)
3293 .tooltip({
3294 let handle = commit_tooltip_focus_handle.clone();
3295 move |window, cx| {
3296 if can_commit {
3297 Tooltip::for_action_in(
3298 tooltip, &Amend, &handle, window, cx,
3299 )
3300 } else {
3301 Tooltip::simple(tooltip, cx)
3302 }
3303 }
3304 })
3305 .disabled(!can_commit || self.modal_open)
3306 .on_click({
3307 let git_panel = cx.weak_entity();
3308 move |_, window, cx| {
3309 telemetry::event!("Git Amended", source = "Git Panel");
3310 git_panel
3311 .update(cx, |git_panel, cx| {
3312 git_panel.set_amend_pending(false, cx);
3313 git_panel.commit_changes(
3314 CommitOptions { amend: true },
3315 window,
3316 cx,
3317 );
3318 })
3319 .ok();
3320 }
3321 }),
3322 )
3323 }
3324 })
3325 .when(!self.amend_pending, |this| {
3326 this.when(has_previous_commit, |this| {
3327 this.child(SplitButton::new(
3328 ui::ButtonLike::new_rounded_left(ElementId::Name(
3329 format!("split-button-left-{}", title).into(),
3330 ))
3331 .layer(ui::ElevationIndex::ModalSurface)
3332 .size(ui::ButtonSize::Compact)
3333 .child(
3334 div()
3335 .child(Label::new(title).size(LabelSize::Small))
3336 .mr_0p5(),
3337 )
3338 .on_click({
3339 let git_panel = cx.weak_entity();
3340 move |_, window, cx| {
3341 telemetry::event!("Git Committed", source = "Git Panel");
3342 git_panel
3343 .update(cx, |git_panel, cx| {
3344 git_panel.commit_changes(
3345 CommitOptions { amend: false },
3346 window,
3347 cx,
3348 );
3349 })
3350 .ok();
3351 }
3352 })
3353 .disabled(!can_commit || self.modal_open)
3354 .tooltip({
3355 let handle = commit_tooltip_focus_handle.clone();
3356 move |window, cx| {
3357 if can_commit {
3358 Tooltip::with_meta_in(
3359 tooltip,
3360 Some(&git::Commit),
3361 "git commit",
3362 &handle.clone(),
3363 window,
3364 cx,
3365 )
3366 } else {
3367 Tooltip::simple(tooltip, cx)
3368 }
3369 }
3370 }),
3371 self.render_git_commit_menu(
3372 ElementId::Name(format!("split-button-right-{}", title).into()),
3373 Some(commit_tooltip_focus_handle.clone()),
3374 )
3375 .into_any_element(),
3376 ))
3377 })
3378 .when(!has_previous_commit, |this| {
3379 this.child(
3380 panel_filled_button(title)
3381 .tooltip(move |window, cx| {
3382 if can_commit {
3383 Tooltip::with_meta_in(
3384 tooltip,
3385 Some(&git::Commit),
3386 "git commit",
3387 &commit_tooltip_focus_handle,
3388 window,
3389 cx,
3390 )
3391 } else {
3392 Tooltip::simple(tooltip, cx)
3393 }
3394 })
3395 .disabled(!can_commit || self.modal_open)
3396 .on_click({
3397 let git_panel = cx.weak_entity();
3398 move |_, window, cx| {
3399 telemetry::event!("Git Committed", source = "Git Panel");
3400 git_panel
3401 .update(cx, |git_panel, cx| {
3402 git_panel.commit_changes(
3403 CommitOptions { amend: false },
3404 window,
3405 cx,
3406 );
3407 })
3408 .ok();
3409 }
3410 }),
3411 )
3412 })
3413 })
3414 }
3415
3416 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3417 div()
3418 .py_2()
3419 .px(px(8.))
3420 .border_color(cx.theme().colors().border)
3421 .child(
3422 Label::new(
3423 "This will update your most recent commit. Cancel to make a new one instead.",
3424 )
3425 .size(LabelSize::Small),
3426 )
3427 }
3428
3429 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3430 let active_repository = self.active_repository.as_ref()?;
3431 let branch = active_repository.read(cx).branch.as_ref()?;
3432 let commit = branch.most_recent_commit.as_ref()?.clone();
3433 let workspace = self.workspace.clone();
3434
3435 let this = cx.entity();
3436 Some(
3437 h_flex()
3438 .items_center()
3439 .py_2()
3440 .px(px(8.))
3441 .border_color(cx.theme().colors().border)
3442 .gap_1p5()
3443 .child(
3444 div()
3445 .flex_grow()
3446 .overflow_hidden()
3447 .items_center()
3448 .max_w(relative(0.85))
3449 .h_full()
3450 .child(
3451 Label::new(commit.subject.clone())
3452 .size(LabelSize::Small)
3453 .truncate(),
3454 )
3455 .id("commit-msg-hover")
3456 .on_click({
3457 let commit = commit.clone();
3458 let repo = active_repository.downgrade();
3459 move |_, window, cx| {
3460 CommitView::open(
3461 commit.clone(),
3462 repo.clone(),
3463 workspace.clone().clone(),
3464 window,
3465 cx,
3466 );
3467 }
3468 })
3469 .hoverable_tooltip({
3470 let repo = active_repository.clone();
3471 move |window, cx| {
3472 GitPanelMessageTooltip::new(
3473 this.clone(),
3474 commit.sha.clone(),
3475 repo.clone(),
3476 window,
3477 cx,
3478 )
3479 .into()
3480 }
3481 }),
3482 )
3483 .child(div().flex_1())
3484 .when(commit.has_parent, |this| {
3485 let has_unstaged = self.has_unstaged_changes();
3486 this.child(
3487 panel_icon_button("undo", IconName::Undo)
3488 .icon_size(IconSize::Small)
3489 .icon_color(Color::Muted)
3490 .tooltip(move |window, cx| {
3491 Tooltip::with_meta(
3492 "Uncommit",
3493 Some(&git::Uncommit),
3494 if has_unstaged {
3495 "git reset HEAD^ --soft"
3496 } else {
3497 "git reset HEAD^"
3498 },
3499 window,
3500 cx,
3501 )
3502 })
3503 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3504 )
3505 }),
3506 )
3507 }
3508
3509 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3510 h_flex()
3511 .h_full()
3512 .flex_grow()
3513 .justify_center()
3514 .items_center()
3515 .child(
3516 v_flex()
3517 .gap_2()
3518 .child(h_flex().w_full().justify_around().child(
3519 if self.active_repository.is_some() {
3520 "No changes to commit"
3521 } else {
3522 "No Git repositories"
3523 },
3524 ))
3525 .children({
3526 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3527 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3528 h_flex().w_full().justify_around().child(
3529 panel_filled_button("Initialize Repository")
3530 .tooltip(Tooltip::for_action_title_in(
3531 "git init",
3532 &git::Init,
3533 &self.focus_handle,
3534 ))
3535 .on_click(move |_, _, cx| {
3536 cx.defer(move |cx| {
3537 cx.dispatch_action(&git::Init);
3538 })
3539 }),
3540 )
3541 })
3542 })
3543 .text_ui_sm(cx)
3544 .mx_auto()
3545 .text_color(Color::Placeholder.color(cx)),
3546 )
3547 }
3548
3549 fn render_vertical_scrollbar(
3550 &self,
3551 show_horizontal_scrollbar_container: bool,
3552 cx: &mut Context<Self>,
3553 ) -> impl IntoElement {
3554 div()
3555 .id("git-panel-vertical-scroll")
3556 .occlude()
3557 .flex_none()
3558 .h_full()
3559 .cursor_default()
3560 .absolute()
3561 .right_0()
3562 .top_0()
3563 .bottom_0()
3564 .w(px(12.))
3565 .when(show_horizontal_scrollbar_container, |this| {
3566 this.pb_neg_3p5()
3567 })
3568 .on_mouse_move(cx.listener(|_, _, _, cx| {
3569 cx.notify();
3570 cx.stop_propagation()
3571 }))
3572 .on_hover(|_, _, cx| {
3573 cx.stop_propagation();
3574 })
3575 .on_any_mouse_down(|_, _, cx| {
3576 cx.stop_propagation();
3577 })
3578 .on_mouse_up(
3579 MouseButton::Left,
3580 cx.listener(|this, _, window, cx| {
3581 if !this.vertical_scrollbar.state.is_dragging()
3582 && !this.focus_handle.contains_focused(window, cx)
3583 {
3584 this.vertical_scrollbar.hide(window, cx);
3585 cx.notify();
3586 }
3587
3588 cx.stop_propagation();
3589 }),
3590 )
3591 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3592 cx.notify();
3593 }))
3594 .children(Scrollbar::vertical(
3595 // percentage as f32..end_offset as f32,
3596 self.vertical_scrollbar.state.clone(),
3597 ))
3598 }
3599
3600 /// Renders the horizontal scrollbar.
3601 ///
3602 /// The right offset is used to determine how far to the right the
3603 /// scrollbar should extend to, useful for ensuring it doesn't collide
3604 /// with the vertical scrollbar when visible.
3605 fn render_horizontal_scrollbar(
3606 &self,
3607 right_offset: Pixels,
3608 cx: &mut Context<Self>,
3609 ) -> impl IntoElement {
3610 div()
3611 .id("git-panel-horizontal-scroll")
3612 .occlude()
3613 .flex_none()
3614 .w_full()
3615 .cursor_default()
3616 .absolute()
3617 .bottom_neg_px()
3618 .left_0()
3619 .right_0()
3620 .pr(right_offset)
3621 .on_mouse_move(cx.listener(|_, _, _, cx| {
3622 cx.notify();
3623 cx.stop_propagation()
3624 }))
3625 .on_hover(|_, _, cx| {
3626 cx.stop_propagation();
3627 })
3628 .on_any_mouse_down(|_, _, cx| {
3629 cx.stop_propagation();
3630 })
3631 .on_mouse_up(
3632 MouseButton::Left,
3633 cx.listener(|this, _, window, cx| {
3634 if !this.horizontal_scrollbar.state.is_dragging()
3635 && !this.focus_handle.contains_focused(window, cx)
3636 {
3637 this.horizontal_scrollbar.hide(window, cx);
3638 cx.notify();
3639 }
3640
3641 cx.stop_propagation();
3642 }),
3643 )
3644 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3645 cx.notify();
3646 }))
3647 .children(Scrollbar::horizontal(
3648 // percentage as f32..end_offset as f32,
3649 self.horizontal_scrollbar.state.clone(),
3650 ))
3651 }
3652
3653 fn render_buffer_header_controls(
3654 &self,
3655 entity: &Entity<Self>,
3656 file: &Arc<dyn File>,
3657 _: &Window,
3658 cx: &App,
3659 ) -> Option<AnyElement> {
3660 let repo = self.active_repository.as_ref()?.read(cx);
3661 let project_path = (file.worktree_id(cx), file.path()).into();
3662 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3663 let ix = self.entry_by_path(&repo_path, cx)?;
3664 let entry = self.entries.get(ix)?;
3665
3666 let entry_staging = self.entry_staging(entry.status_entry()?);
3667
3668 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3669 .disabled(!self.has_write_access(cx))
3670 .fill()
3671 .elevation(ElevationIndex::Surface)
3672 .on_click({
3673 let entry = entry.clone();
3674 let git_panel = entity.downgrade();
3675 move |_, window, cx| {
3676 git_panel
3677 .update(cx, |this, cx| {
3678 this.toggle_staged_for_entry(&entry, window, cx);
3679 cx.stop_propagation();
3680 })
3681 .ok();
3682 }
3683 });
3684 Some(
3685 h_flex()
3686 .id("start-slot")
3687 .text_lg()
3688 .child(checkbox)
3689 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3690 // prevent the list item active state triggering when toggling checkbox
3691 cx.stop_propagation();
3692 })
3693 .into_any_element(),
3694 )
3695 }
3696
3697 fn render_entries(
3698 &self,
3699 has_write_access: bool,
3700 _: &Window,
3701 cx: &mut Context<Self>,
3702 ) -> impl IntoElement {
3703 let entry_count = self.entries.len();
3704
3705 let scroll_track_size = px(16.);
3706
3707 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3708 // magic number
3709 px(3.)
3710 } else {
3711 px(0.)
3712 };
3713
3714 v_flex()
3715 .flex_1()
3716 .size_full()
3717 .overflow_hidden()
3718 .relative()
3719 // Show a border on the top and bottom of the container when
3720 // the vertical scrollbar container is visible so we don't have a
3721 // floating left border in the panel.
3722 .when(self.vertical_scrollbar.show_track, |this| {
3723 this.border_t_1()
3724 .border_b_1()
3725 .border_color(cx.theme().colors().border)
3726 })
3727 .child(
3728 h_flex()
3729 .flex_1()
3730 .size_full()
3731 .relative()
3732 .overflow_hidden()
3733 .child(
3734 uniform_list(
3735 "entries",
3736 entry_count,
3737 cx.processor(move |this, range: Range<usize>, window, cx| {
3738 let mut items = Vec::with_capacity(range.end - range.start);
3739
3740 for ix in range {
3741 match &this.entries.get(ix) {
3742 Some(GitListEntry::GitStatusEntry(entry)) => {
3743 items.push(this.render_entry(
3744 ix,
3745 entry,
3746 has_write_access,
3747 window,
3748 cx,
3749 ));
3750 }
3751 Some(GitListEntry::Header(header)) => {
3752 items.push(this.render_list_header(
3753 ix,
3754 header,
3755 has_write_access,
3756 window,
3757 cx,
3758 ));
3759 }
3760 None => {}
3761 }
3762 }
3763
3764 items
3765 }),
3766 )
3767 .when(
3768 !self.horizontal_scrollbar.show_track
3769 && self.horizontal_scrollbar.show_scrollbar,
3770 |this| {
3771 // when not showing the horizontal scrollbar track, make sure we don't
3772 // obscure the last entry
3773 this.pb(scroll_track_size)
3774 },
3775 )
3776 .size_full()
3777 .flex_grow()
3778 .with_sizing_behavior(ListSizingBehavior::Auto)
3779 .with_horizontal_sizing_behavior(
3780 ListHorizontalSizingBehavior::Unconstrained,
3781 )
3782 .with_width_from_item(self.max_width_item_index)
3783 .track_scroll(self.scroll_handle.clone()),
3784 )
3785 .on_mouse_down(
3786 MouseButton::Right,
3787 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3788 this.deploy_panel_context_menu(event.position, window, cx)
3789 }),
3790 )
3791 .when(self.vertical_scrollbar.show_track, |this| {
3792 this.child(
3793 v_flex()
3794 .h_full()
3795 .flex_none()
3796 .w(scroll_track_size)
3797 .bg(cx.theme().colors().panel_background)
3798 .child(
3799 div()
3800 .size_full()
3801 .flex_1()
3802 .border_l_1()
3803 .border_color(cx.theme().colors().border),
3804 ),
3805 )
3806 })
3807 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3808 this.child(
3809 self.render_vertical_scrollbar(
3810 self.horizontal_scrollbar.show_track,
3811 cx,
3812 ),
3813 )
3814 }),
3815 )
3816 .when(self.horizontal_scrollbar.show_track, |this| {
3817 this.child(
3818 h_flex()
3819 .w_full()
3820 .h(scroll_track_size)
3821 .flex_none()
3822 .relative()
3823 .child(
3824 div()
3825 .w_full()
3826 .flex_1()
3827 // for some reason the horizontal scrollbar is 1px
3828 // taller than the vertical scrollbar??
3829 .h(scroll_track_size - px(1.))
3830 .bg(cx.theme().colors().panel_background)
3831 .border_t_1()
3832 .border_color(cx.theme().colors().border),
3833 )
3834 .when(self.vertical_scrollbar.show_track, |this| {
3835 this.child(
3836 div()
3837 .flex_none()
3838 // -1px prevents a missing pixel between the two container borders
3839 .w(scroll_track_size - px(1.))
3840 .h_full(),
3841 )
3842 .child(
3843 // HACK: Fill the missing 1px 🥲
3844 div()
3845 .absolute()
3846 .right(scroll_track_size - px(1.))
3847 .bottom(scroll_track_size - px(1.))
3848 .size_px()
3849 .bg(cx.theme().colors().border),
3850 )
3851 }),
3852 )
3853 })
3854 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3855 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3856 })
3857 }
3858
3859 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3860 Label::new(label.into()).color(color).single_line()
3861 }
3862
3863 fn list_item_height(&self) -> Rems {
3864 rems(1.75)
3865 }
3866
3867 fn render_list_header(
3868 &self,
3869 ix: usize,
3870 header: &GitHeaderEntry,
3871 _: bool,
3872 _: &Window,
3873 _: &Context<Self>,
3874 ) -> AnyElement {
3875 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3876
3877 h_flex()
3878 .id(id)
3879 .h(self.list_item_height())
3880 .w_full()
3881 .items_end()
3882 .px(rems(0.75)) // ~12px
3883 .pb(rems(0.3125)) // ~ 5px
3884 .child(
3885 Label::new(header.title())
3886 .color(Color::Muted)
3887 .size(LabelSize::Small)
3888 .line_height_style(LineHeightStyle::UiLabel)
3889 .single_line(),
3890 )
3891 .into_any_element()
3892 }
3893
3894 pub fn load_commit_details(
3895 &self,
3896 sha: String,
3897 cx: &mut Context<Self>,
3898 ) -> Task<anyhow::Result<CommitDetails>> {
3899 let Some(repo) = self.active_repository.clone() else {
3900 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3901 };
3902 repo.update(cx, |repo, cx| {
3903 let show = repo.show(sha);
3904 cx.spawn(async move |_, _| show.await?)
3905 })
3906 }
3907
3908 fn deploy_entry_context_menu(
3909 &mut self,
3910 position: Point<Pixels>,
3911 ix: usize,
3912 window: &mut Window,
3913 cx: &mut Context<Self>,
3914 ) {
3915 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3916 return;
3917 };
3918 let stage_title = if entry.status.staging().is_fully_staged() {
3919 "Unstage File"
3920 } else {
3921 "Stage File"
3922 };
3923 let restore_title = if entry.status.is_created() {
3924 "Trash File"
3925 } else {
3926 "Restore File"
3927 };
3928 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3929 context_menu
3930 .context(self.focus_handle.clone())
3931 .action(stage_title, ToggleStaged.boxed_clone())
3932 .action(restore_title, git::RestoreFile::default().boxed_clone())
3933 .separator()
3934 .action("Open Diff", Confirm.boxed_clone())
3935 .action("Open File", SecondaryConfirm.boxed_clone())
3936 });
3937 self.selected_entry = Some(ix);
3938 self.set_context_menu(context_menu, position, window, cx);
3939 }
3940
3941 fn deploy_panel_context_menu(
3942 &mut self,
3943 position: Point<Pixels>,
3944 window: &mut Window,
3945 cx: &mut Context<Self>,
3946 ) {
3947 let context_menu = git_panel_context_menu(
3948 self.focus_handle.clone(),
3949 GitMenuState {
3950 has_tracked_changes: self.has_tracked_changes(),
3951 has_staged_changes: self.has_staged_changes(),
3952 has_unstaged_changes: self.has_unstaged_changes(),
3953 has_new_changes: self.new_count > 0,
3954 },
3955 window,
3956 cx,
3957 );
3958 self.set_context_menu(context_menu, position, window, cx);
3959 }
3960
3961 fn set_context_menu(
3962 &mut self,
3963 context_menu: Entity<ContextMenu>,
3964 position: Point<Pixels>,
3965 window: &Window,
3966 cx: &mut Context<Self>,
3967 ) {
3968 let subscription = cx.subscribe_in(
3969 &context_menu,
3970 window,
3971 |this, _, _: &DismissEvent, window, cx| {
3972 if this.context_menu.as_ref().is_some_and(|context_menu| {
3973 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3974 }) {
3975 cx.focus_self(window);
3976 }
3977 this.context_menu.take();
3978 cx.notify();
3979 },
3980 );
3981 self.context_menu = Some((context_menu, position, subscription));
3982 cx.notify();
3983 }
3984
3985 fn render_entry(
3986 &self,
3987 ix: usize,
3988 entry: &GitStatusEntry,
3989 has_write_access: bool,
3990 window: &Window,
3991 cx: &Context<Self>,
3992 ) -> AnyElement {
3993 let display_name = entry.display_name();
3994
3995 let selected = self.selected_entry == Some(ix);
3996 let marked = self.marked_entries.contains(&ix);
3997 let status_style = GitPanelSettings::get_global(cx).status_style;
3998 let status = entry.status;
3999 let modifiers = self.current_modifiers;
4000 let shift_held = modifiers.shift;
4001
4002 let has_conflict = status.is_conflicted();
4003 let is_modified = status.is_modified();
4004 let is_deleted = status.is_deleted();
4005
4006 let label_color = if status_style == StatusStyle::LabelColor {
4007 if has_conflict {
4008 Color::VersionControlConflict
4009 } else if is_modified {
4010 Color::VersionControlModified
4011 } else if is_deleted {
4012 // We don't want a bunch of red labels in the list
4013 Color::Disabled
4014 } else {
4015 Color::VersionControlAdded
4016 }
4017 } else {
4018 Color::Default
4019 };
4020
4021 let path_color = if status.is_deleted() {
4022 Color::Disabled
4023 } else {
4024 Color::Muted
4025 };
4026
4027 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4028 let checkbox_wrapper_id: ElementId =
4029 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4030 let checkbox_id: ElementId =
4031 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4032
4033 let entry_staging = self.entry_staging(entry);
4034 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4035 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4036 is_staged = ToggleState::Selected;
4037 }
4038
4039 let handle = cx.weak_entity();
4040
4041 let selected_bg_alpha = 0.08;
4042 let marked_bg_alpha = 0.12;
4043 let state_opacity_step = 0.04;
4044
4045 let base_bg = match (selected, marked) {
4046 (true, true) => cx
4047 .theme()
4048 .status()
4049 .info
4050 .alpha(selected_bg_alpha + marked_bg_alpha),
4051 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4052 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4053 _ => cx.theme().colors().ghost_element_background,
4054 };
4055
4056 let hover_bg = if selected {
4057 cx.theme()
4058 .status()
4059 .info
4060 .alpha(selected_bg_alpha + state_opacity_step)
4061 } else {
4062 cx.theme().colors().ghost_element_hover
4063 };
4064
4065 let active_bg = if selected {
4066 cx.theme()
4067 .status()
4068 .info
4069 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4070 } else {
4071 cx.theme().colors().ghost_element_active
4072 };
4073
4074 h_flex()
4075 .id(id)
4076 .h(self.list_item_height())
4077 .w_full()
4078 .items_center()
4079 .border_1()
4080 .when(selected && self.focus_handle.is_focused(window), |el| {
4081 el.border_color(cx.theme().colors().border_focused)
4082 })
4083 .px(rems(0.75)) // ~12px
4084 .overflow_hidden()
4085 .flex_none()
4086 .gap_1p5()
4087 .bg(base_bg)
4088 .hover(|this| this.bg(hover_bg))
4089 .active(|this| this.bg(active_bg))
4090 .on_click({
4091 cx.listener(move |this, event: &ClickEvent, window, cx| {
4092 this.selected_entry = Some(ix);
4093 cx.notify();
4094 if event.modifiers().secondary() {
4095 this.open_file(&Default::default(), window, cx)
4096 } else {
4097 this.open_diff(&Default::default(), window, cx);
4098 this.focus_handle.focus(window);
4099 }
4100 })
4101 })
4102 .on_mouse_down(
4103 MouseButton::Right,
4104 move |event: &MouseDownEvent, window, cx| {
4105 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4106 if event.button != MouseButton::Right {
4107 return;
4108 }
4109
4110 let Some(this) = handle.upgrade() else {
4111 return;
4112 };
4113 this.update(cx, |this, cx| {
4114 this.deploy_entry_context_menu(event.position, ix, window, cx);
4115 });
4116 cx.stop_propagation();
4117 },
4118 )
4119 // .on_secondary_mouse_down(cx.listener(
4120 // move |this, event: &MouseDownEvent, window, cx| {
4121 // this.deploy_entry_context_menu(event.position, ix, window, cx);
4122 // cx.stop_propagation();
4123 // },
4124 // ))
4125 .child(
4126 div()
4127 .id(checkbox_wrapper_id)
4128 .flex_none()
4129 .occlude()
4130 .cursor_pointer()
4131 .child(
4132 Checkbox::new(checkbox_id, is_staged)
4133 .disabled(!has_write_access)
4134 .fill()
4135 .elevation(ElevationIndex::Surface)
4136 .on_click({
4137 let entry = entry.clone();
4138 cx.listener(move |this, _, window, cx| {
4139 if !has_write_access {
4140 return;
4141 }
4142 this.toggle_staged_for_entry(
4143 &GitListEntry::GitStatusEntry(entry.clone()),
4144 window,
4145 cx,
4146 );
4147 cx.stop_propagation();
4148 })
4149 })
4150 .tooltip(move |window, cx| {
4151 let is_staged = entry_staging.is_fully_staged();
4152
4153 let action = if is_staged { "Unstage" } else { "Stage" };
4154 let tooltip_name = if shift_held {
4155 format!("{} section", action)
4156 } else {
4157 action.to_string()
4158 };
4159
4160 let meta = if shift_held {
4161 format!(
4162 "Release shift to {} single entry",
4163 action.to_lowercase()
4164 )
4165 } else {
4166 format!("Shift click to {} section", action.to_lowercase())
4167 };
4168
4169 Tooltip::with_meta(
4170 tooltip_name,
4171 Some(&ToggleStaged),
4172 meta,
4173 window,
4174 cx,
4175 )
4176 }),
4177 ),
4178 )
4179 .child(git_status_icon(status))
4180 .child(
4181 h_flex()
4182 .items_center()
4183 .flex_1()
4184 // .overflow_hidden()
4185 .when_some(entry.parent_dir(), |this, parent| {
4186 if !parent.is_empty() {
4187 this.child(
4188 self.entry_label(format!("{}/", parent), path_color)
4189 .when(status.is_deleted(), |this| this.strikethrough()),
4190 )
4191 } else {
4192 this
4193 }
4194 })
4195 .child(
4196 self.entry_label(display_name.clone(), label_color)
4197 .when(status.is_deleted(), |this| this.strikethrough()),
4198 ),
4199 )
4200 .into_any_element()
4201 }
4202
4203 fn has_write_access(&self, cx: &App) -> bool {
4204 !self.project.read(cx).is_read_only(cx)
4205 }
4206
4207 pub fn amend_pending(&self) -> bool {
4208 self.amend_pending
4209 }
4210
4211 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4212 self.amend_pending = value;
4213 cx.notify();
4214 }
4215
4216 pub async fn load(
4217 workspace: WeakEntity<Workspace>,
4218 mut cx: AsyncWindowContext,
4219 ) -> anyhow::Result<Entity<Self>> {
4220 let serialized_panel = cx
4221 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&GIT_PANEL_KEY) })
4222 .await
4223 .context("loading git panel")
4224 .log_err()
4225 .flatten()
4226 .and_then(|panel| serde_json::from_str::<SerializedGitPanel>(&panel).log_err());
4227
4228 workspace.update_in(&mut cx, |workspace, window, cx| {
4229 let panel = GitPanel::new(workspace, window, cx);
4230
4231 if let Some(serialized_panel) = serialized_panel {
4232 panel.update(cx, |panel, cx| {
4233 panel.width = serialized_panel.width;
4234 cx.notify();
4235 })
4236 }
4237
4238 panel
4239 })
4240 }
4241}
4242
4243fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4244 agent_settings::AgentSettings::get_global(cx)
4245 .enabled
4246 .then(|| {
4247 let ConfiguredModel { provider, model } =
4248 LanguageModelRegistry::read_global(cx).commit_message_model()?;
4249
4250 provider.is_authenticated(cx).then(|| model)
4251 })
4252 .flatten()
4253}
4254
4255impl Render for GitPanel {
4256 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4257 let project = self.project.read(cx);
4258 let has_entries = self.entries.len() > 0;
4259 let room = self
4260 .workspace
4261 .upgrade()
4262 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4263
4264 let has_write_access = self.has_write_access(cx);
4265
4266 let has_co_authors = room.map_or(false, |room| {
4267 self.load_local_committer(cx);
4268 let room = room.read(cx);
4269 room.remote_participants()
4270 .values()
4271 .any(|remote_participant| remote_participant.can_write())
4272 });
4273
4274 v_flex()
4275 .id("git_panel")
4276 .key_context(self.dispatch_context(window, cx))
4277 .track_focus(&self.focus_handle)
4278 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
4279 .when(has_write_access && !project.is_read_only(cx), |this| {
4280 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4281 .on_action(cx.listener(GitPanel::commit))
4282 .on_action(cx.listener(GitPanel::amend))
4283 .on_action(cx.listener(GitPanel::cancel))
4284 .on_action(cx.listener(Self::stage_all))
4285 .on_action(cx.listener(Self::unstage_all))
4286 .on_action(cx.listener(Self::stage_selected))
4287 .on_action(cx.listener(Self::unstage_selected))
4288 .on_action(cx.listener(Self::restore_tracked_files))
4289 .on_action(cx.listener(Self::revert_selected))
4290 .on_action(cx.listener(Self::clean_all))
4291 .on_action(cx.listener(Self::generate_commit_message_action))
4292 })
4293 .on_action(cx.listener(Self::select_first))
4294 .on_action(cx.listener(Self::select_next))
4295 .on_action(cx.listener(Self::select_previous))
4296 .on_action(cx.listener(Self::select_last))
4297 .on_action(cx.listener(Self::close_panel))
4298 .on_action(cx.listener(Self::open_diff))
4299 .on_action(cx.listener(Self::open_file))
4300 .on_action(cx.listener(Self::focus_changes_list))
4301 .on_action(cx.listener(Self::focus_editor))
4302 .on_action(cx.listener(Self::expand_commit_editor))
4303 .when(has_write_access && has_co_authors, |git_panel| {
4304 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4305 })
4306 .on_hover(cx.listener(move |this, hovered, window, cx| {
4307 if *hovered {
4308 this.horizontal_scrollbar.show(cx);
4309 this.vertical_scrollbar.show(cx);
4310 cx.notify();
4311 } else if !this.focus_handle.contains_focused(window, cx) {
4312 this.hide_scrollbars(window, cx);
4313 }
4314 }))
4315 .size_full()
4316 .overflow_hidden()
4317 .bg(cx.theme().colors().panel_background)
4318 .child(
4319 v_flex()
4320 .size_full()
4321 .children(self.render_panel_header(window, cx))
4322 .map(|this| {
4323 if has_entries {
4324 this.child(self.render_entries(has_write_access, window, cx))
4325 } else {
4326 this.child(self.render_empty_state(cx).into_any_element())
4327 }
4328 })
4329 .children(self.render_footer(window, cx))
4330 .when(self.amend_pending, |this| {
4331 this.child(self.render_pending_amend(cx))
4332 })
4333 .when(!self.amend_pending, |this| {
4334 this.children(self.render_previous_commit(cx))
4335 })
4336 .into_any_element(),
4337 )
4338 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4339 deferred(
4340 anchored()
4341 .position(*position)
4342 .anchor(Corner::TopLeft)
4343 .child(menu.clone()),
4344 )
4345 .with_priority(1)
4346 }))
4347 }
4348}
4349
4350impl Focusable for GitPanel {
4351 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4352 if self.entries.is_empty() {
4353 self.commit_editor.focus_handle(cx)
4354 } else {
4355 self.focus_handle.clone()
4356 }
4357 }
4358}
4359
4360impl EventEmitter<Event> for GitPanel {}
4361
4362impl EventEmitter<PanelEvent> for GitPanel {}
4363
4364pub(crate) struct GitPanelAddon {
4365 pub(crate) workspace: WeakEntity<Workspace>,
4366}
4367
4368impl editor::Addon for GitPanelAddon {
4369 fn to_any(&self) -> &dyn std::any::Any {
4370 self
4371 }
4372
4373 fn render_buffer_header_controls(
4374 &self,
4375 excerpt_info: &ExcerptInfo,
4376 window: &Window,
4377 cx: &App,
4378 ) -> Option<AnyElement> {
4379 let file = excerpt_info.buffer.file()?;
4380 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4381
4382 git_panel
4383 .read(cx)
4384 .render_buffer_header_controls(&git_panel, &file, window, cx)
4385 }
4386}
4387
4388impl Panel for GitPanel {
4389 fn persistent_name() -> &'static str {
4390 "GitPanel"
4391 }
4392
4393 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4394 GitPanelSettings::get_global(cx).dock
4395 }
4396
4397 fn position_is_valid(&self, position: DockPosition) -> bool {
4398 matches!(position, DockPosition::Left | DockPosition::Right)
4399 }
4400
4401 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4402 settings::update_settings_file::<GitPanelSettings>(
4403 self.fs.clone(),
4404 cx,
4405 move |settings, _| settings.dock = Some(position),
4406 );
4407 }
4408
4409 fn size(&self, _: &Window, cx: &App) -> Pixels {
4410 self.width
4411 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4412 }
4413
4414 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4415 self.width = size;
4416 self.serialize(cx);
4417 cx.notify();
4418 }
4419
4420 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4421 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
4422 }
4423
4424 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4425 Some("Git Panel")
4426 }
4427
4428 fn toggle_action(&self) -> Box<dyn Action> {
4429 Box::new(ToggleFocus)
4430 }
4431
4432 fn activation_priority(&self) -> u32 {
4433 2
4434 }
4435}
4436
4437impl PanelHeader for GitPanel {}
4438
4439struct GitPanelMessageTooltip {
4440 commit_tooltip: Option<Entity<CommitTooltip>>,
4441}
4442
4443impl GitPanelMessageTooltip {
4444 fn new(
4445 git_panel: Entity<GitPanel>,
4446 sha: SharedString,
4447 repository: Entity<Repository>,
4448 window: &mut Window,
4449 cx: &mut App,
4450 ) -> Entity<Self> {
4451 cx.new(|cx| {
4452 cx.spawn_in(window, async move |this, cx| {
4453 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4454 (
4455 git_panel.load_commit_details(sha.to_string(), cx),
4456 git_panel.workspace.clone(),
4457 )
4458 })?;
4459 let details = details.await?;
4460
4461 let commit_details = crate::commit_tooltip::CommitDetails {
4462 sha: details.sha.clone(),
4463 author_name: details.author_name.clone(),
4464 author_email: details.author_email.clone(),
4465 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4466 message: Some(ParsedCommitMessage {
4467 message: details.message.clone(),
4468 ..Default::default()
4469 }),
4470 };
4471
4472 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4473 this.commit_tooltip = Some(cx.new(move |cx| {
4474 CommitTooltip::new(commit_details, repository, workspace, cx)
4475 }));
4476 cx.notify();
4477 })
4478 })
4479 .detach();
4480
4481 Self {
4482 commit_tooltip: None,
4483 }
4484 })
4485 }
4486}
4487
4488impl Render for GitPanelMessageTooltip {
4489 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4490 if let Some(commit_tooltip) = &self.commit_tooltip {
4491 commit_tooltip.clone().into_any_element()
4492 } else {
4493 gpui::Empty.into_any_element()
4494 }
4495 }
4496}
4497
4498#[derive(IntoElement, RegisterComponent)]
4499pub struct PanelRepoFooter {
4500 active_repository: SharedString,
4501 branch: Option<Branch>,
4502 head_commit: Option<CommitDetails>,
4503
4504 // Getting a GitPanel in previews will be difficult.
4505 //
4506 // For now just take an option here, and we won't bind handlers to buttons in previews.
4507 git_panel: Option<Entity<GitPanel>>,
4508}
4509
4510impl PanelRepoFooter {
4511 pub fn new(
4512 active_repository: SharedString,
4513 branch: Option<Branch>,
4514 head_commit: Option<CommitDetails>,
4515 git_panel: Option<Entity<GitPanel>>,
4516 ) -> Self {
4517 Self {
4518 active_repository,
4519 branch,
4520 head_commit,
4521 git_panel,
4522 }
4523 }
4524
4525 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4526 Self {
4527 active_repository,
4528 branch,
4529 head_commit: None,
4530 git_panel: None,
4531 }
4532 }
4533}
4534
4535impl RenderOnce for PanelRepoFooter {
4536 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4537 let project = self
4538 .git_panel
4539 .as_ref()
4540 .map(|panel| panel.read(cx).project.clone());
4541
4542 let repo = self
4543 .git_panel
4544 .as_ref()
4545 .and_then(|panel| panel.read(cx).active_repository.clone());
4546
4547 let single_repo = project
4548 .as_ref()
4549 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4550 .unwrap_or(true);
4551
4552 const MAX_BRANCH_LEN: usize = 16;
4553 const MAX_REPO_LEN: usize = 16;
4554 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4555 const MAX_SHORT_SHA_LEN: usize = 8;
4556
4557 let branch_name = self
4558 .branch
4559 .as_ref()
4560 .map(|branch| branch.name().to_owned())
4561 .or_else(|| {
4562 self.head_commit.as_ref().map(|commit| {
4563 commit
4564 .sha
4565 .chars()
4566 .take(MAX_SHORT_SHA_LEN)
4567 .collect::<String>()
4568 })
4569 })
4570 .unwrap_or_else(|| " (no branch)".to_owned());
4571 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4572
4573 let active_repo_name = self.active_repository.clone();
4574
4575 let branch_actual_len = branch_name.len();
4576 let repo_actual_len = active_repo_name.len();
4577
4578 // ideally, show the whole branch and repo names but
4579 // when we can't, use a budget to allocate space between the two
4580 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4581 <= LABEL_CHARACTER_BUDGET
4582 {
4583 (repo_actual_len, branch_actual_len)
4584 } else {
4585 if branch_actual_len <= MAX_BRANCH_LEN {
4586 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4587 (repo_space, branch_actual_len)
4588 } else if repo_actual_len <= MAX_REPO_LEN {
4589 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4590 (repo_actual_len, branch_space)
4591 } else {
4592 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4593 }
4594 };
4595
4596 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4597 active_repo_name.to_string()
4598 } else {
4599 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4600 };
4601
4602 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4603 branch_name.to_string()
4604 } else {
4605 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4606 };
4607
4608 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4609 .style(ButtonStyle::Transparent)
4610 .size(ButtonSize::None)
4611 .label_size(LabelSize::Small)
4612 .color(Color::Muted);
4613
4614 let repo_selector = PopoverMenu::new("repository-switcher")
4615 .menu({
4616 let project = project.clone();
4617 move |window, cx| {
4618 let project = project.clone()?;
4619 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4620 }
4621 })
4622 .trigger_with_tooltip(
4623 repo_selector_trigger.disabled(single_repo).truncate(true),
4624 Tooltip::text("Switch active repository"),
4625 )
4626 .anchor(Corner::BottomLeft)
4627 .into_any_element();
4628
4629 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4630 .style(ButtonStyle::Transparent)
4631 .size(ButtonSize::None)
4632 .label_size(LabelSize::Small)
4633 .truncate(true)
4634 .tooltip(Tooltip::for_action_title(
4635 "Switch Branch",
4636 &zed_actions::git::Switch,
4637 ))
4638 .on_click(|_, window, cx| {
4639 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4640 });
4641
4642 let branch_selector = PopoverMenu::new("popover-button")
4643 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4644 .trigger_with_tooltip(
4645 branch_selector_button,
4646 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4647 )
4648 .anchor(Corner::BottomLeft)
4649 .offset(gpui::Point {
4650 x: px(0.0),
4651 y: px(-2.0),
4652 });
4653
4654 h_flex()
4655 .w_full()
4656 .px_2()
4657 .h(px(36.))
4658 .items_center()
4659 .justify_between()
4660 .gap_1()
4661 .child(
4662 h_flex()
4663 .flex_1()
4664 .overflow_hidden()
4665 .items_center()
4666 .child(
4667 div().child(
4668 Icon::new(IconName::GitBranchSmall)
4669 .size(IconSize::Small)
4670 .color(if single_repo {
4671 Color::Disabled
4672 } else {
4673 Color::Muted
4674 }),
4675 ),
4676 )
4677 .child(repo_selector)
4678 .when(show_separator, |this| {
4679 this.child(
4680 div()
4681 .text_color(cx.theme().colors().text_muted)
4682 .text_sm()
4683 .child("/"),
4684 )
4685 })
4686 .child(branch_selector),
4687 )
4688 .children(if let Some(git_panel) = self.git_panel {
4689 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4690 } else {
4691 None
4692 })
4693 }
4694}
4695
4696impl Component for PanelRepoFooter {
4697 fn scope() -> ComponentScope {
4698 ComponentScope::VersionControl
4699 }
4700
4701 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4702 let unknown_upstream = None;
4703 let no_remote_upstream = Some(UpstreamTracking::Gone);
4704 let ahead_of_upstream = Some(
4705 UpstreamTrackingStatus {
4706 ahead: 2,
4707 behind: 0,
4708 }
4709 .into(),
4710 );
4711 let behind_upstream = Some(
4712 UpstreamTrackingStatus {
4713 ahead: 0,
4714 behind: 2,
4715 }
4716 .into(),
4717 );
4718 let ahead_and_behind_upstream = Some(
4719 UpstreamTrackingStatus {
4720 ahead: 3,
4721 behind: 1,
4722 }
4723 .into(),
4724 );
4725
4726 let not_ahead_or_behind_upstream = Some(
4727 UpstreamTrackingStatus {
4728 ahead: 0,
4729 behind: 0,
4730 }
4731 .into(),
4732 );
4733
4734 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4735 Branch {
4736 is_head: true,
4737 ref_name: "some-branch".into(),
4738 upstream: upstream.map(|tracking| Upstream {
4739 ref_name: "origin/some-branch".into(),
4740 tracking,
4741 }),
4742 most_recent_commit: Some(CommitSummary {
4743 sha: "abc123".into(),
4744 subject: "Modify stuff".into(),
4745 commit_timestamp: 1710932954,
4746 has_parent: true,
4747 }),
4748 }
4749 }
4750
4751 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4752 Branch {
4753 is_head: true,
4754 ref_name: branch_name.to_string().into(),
4755 upstream: upstream.map(|tracking| Upstream {
4756 ref_name: format!("zed/{}", branch_name).into(),
4757 tracking,
4758 }),
4759 most_recent_commit: Some(CommitSummary {
4760 sha: "abc123".into(),
4761 subject: "Modify stuff".into(),
4762 commit_timestamp: 1710932954,
4763 has_parent: true,
4764 }),
4765 }
4766 }
4767
4768 fn active_repository(id: usize) -> SharedString {
4769 format!("repo-{}", id).into()
4770 }
4771
4772 let example_width = px(340.);
4773 Some(
4774 v_flex()
4775 .gap_6()
4776 .w_full()
4777 .flex_none()
4778 .children(vec![
4779 example_group_with_title(
4780 "Action Button States",
4781 vec![
4782 single_example(
4783 "No Branch",
4784 div()
4785 .w(example_width)
4786 .overflow_hidden()
4787 .child(PanelRepoFooter::new_preview(
4788 active_repository(1).clone(),
4789 None,
4790 ))
4791 .into_any_element(),
4792 ),
4793 single_example(
4794 "Remote status unknown",
4795 div()
4796 .w(example_width)
4797 .overflow_hidden()
4798 .child(PanelRepoFooter::new_preview(
4799 active_repository(2).clone(),
4800 Some(branch(unknown_upstream)),
4801 ))
4802 .into_any_element(),
4803 ),
4804 single_example(
4805 "No Remote Upstream",
4806 div()
4807 .w(example_width)
4808 .overflow_hidden()
4809 .child(PanelRepoFooter::new_preview(
4810 active_repository(3).clone(),
4811 Some(branch(no_remote_upstream)),
4812 ))
4813 .into_any_element(),
4814 ),
4815 single_example(
4816 "Not Ahead or Behind",
4817 div()
4818 .w(example_width)
4819 .overflow_hidden()
4820 .child(PanelRepoFooter::new_preview(
4821 active_repository(4).clone(),
4822 Some(branch(not_ahead_or_behind_upstream)),
4823 ))
4824 .into_any_element(),
4825 ),
4826 single_example(
4827 "Behind remote",
4828 div()
4829 .w(example_width)
4830 .overflow_hidden()
4831 .child(PanelRepoFooter::new_preview(
4832 active_repository(5).clone(),
4833 Some(branch(behind_upstream)),
4834 ))
4835 .into_any_element(),
4836 ),
4837 single_example(
4838 "Ahead of remote",
4839 div()
4840 .w(example_width)
4841 .overflow_hidden()
4842 .child(PanelRepoFooter::new_preview(
4843 active_repository(6).clone(),
4844 Some(branch(ahead_of_upstream)),
4845 ))
4846 .into_any_element(),
4847 ),
4848 single_example(
4849 "Ahead and behind remote",
4850 div()
4851 .w(example_width)
4852 .overflow_hidden()
4853 .child(PanelRepoFooter::new_preview(
4854 active_repository(7).clone(),
4855 Some(branch(ahead_and_behind_upstream)),
4856 ))
4857 .into_any_element(),
4858 ),
4859 ],
4860 )
4861 .grow()
4862 .vertical(),
4863 ])
4864 .children(vec![
4865 example_group_with_title(
4866 "Labels",
4867 vec![
4868 single_example(
4869 "Short Branch & Repo",
4870 div()
4871 .w(example_width)
4872 .overflow_hidden()
4873 .child(PanelRepoFooter::new_preview(
4874 SharedString::from("zed"),
4875 Some(custom("main", behind_upstream)),
4876 ))
4877 .into_any_element(),
4878 ),
4879 single_example(
4880 "Long Branch",
4881 div()
4882 .w(example_width)
4883 .overflow_hidden()
4884 .child(PanelRepoFooter::new_preview(
4885 SharedString::from("zed"),
4886 Some(custom(
4887 "redesign-and-update-git-ui-list-entry-style",
4888 behind_upstream,
4889 )),
4890 ))
4891 .into_any_element(),
4892 ),
4893 single_example(
4894 "Long Repo",
4895 div()
4896 .w(example_width)
4897 .overflow_hidden()
4898 .child(PanelRepoFooter::new_preview(
4899 SharedString::from("zed-industries-community-examples"),
4900 Some(custom("gpui", ahead_of_upstream)),
4901 ))
4902 .into_any_element(),
4903 ),
4904 single_example(
4905 "Long Repo & Branch",
4906 div()
4907 .w(example_width)
4908 .overflow_hidden()
4909 .child(PanelRepoFooter::new_preview(
4910 SharedString::from("zed-industries-community-examples"),
4911 Some(custom(
4912 "redesign-and-update-git-ui-list-entry-style",
4913 behind_upstream,
4914 )),
4915 ))
4916 .into_any_element(),
4917 ),
4918 single_example(
4919 "Uppercase Repo",
4920 div()
4921 .w(example_width)
4922 .overflow_hidden()
4923 .child(PanelRepoFooter::new_preview(
4924 SharedString::from("LICENSES"),
4925 Some(custom("main", ahead_of_upstream)),
4926 ))
4927 .into_any_element(),
4928 ),
4929 single_example(
4930 "Uppercase Branch",
4931 div()
4932 .w(example_width)
4933 .overflow_hidden()
4934 .child(PanelRepoFooter::new_preview(
4935 SharedString::from("zed"),
4936 Some(custom("update-README", behind_upstream)),
4937 ))
4938 .into_any_element(),
4939 ),
4940 ],
4941 )
4942 .grow()
4943 .vertical(),
4944 ])
4945 .into_any_element(),
4946 )
4947 }
4948}
4949
4950#[cfg(test)]
4951mod tests {
4952 use git::status::StatusCode;
4953 use gpui::{TestAppContext, VisualTestContext};
4954 use project::{FakeFs, WorktreeSettings};
4955 use serde_json::json;
4956 use settings::SettingsStore;
4957 use theme::LoadThemes;
4958 use util::path;
4959
4960 use super::*;
4961
4962 fn init_test(cx: &mut gpui::TestAppContext) {
4963 zlog::init_test();
4964
4965 cx.update(|cx| {
4966 let settings_store = SettingsStore::test(cx);
4967 cx.set_global(settings_store);
4968 AgentSettings::register(cx);
4969 WorktreeSettings::register(cx);
4970 workspace::init_settings(cx);
4971 theme::init(LoadThemes::JustBase, cx);
4972 language::init(cx);
4973 editor::init(cx);
4974 Project::init_settings(cx);
4975 crate::init(cx);
4976 });
4977 }
4978
4979 #[gpui::test]
4980 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
4981 init_test(cx);
4982 let fs = FakeFs::new(cx.background_executor.clone());
4983 fs.insert_tree(
4984 "/root",
4985 json!({
4986 "zed": {
4987 ".git": {},
4988 "crates": {
4989 "gpui": {
4990 "gpui.rs": "fn main() {}"
4991 },
4992 "util": {
4993 "util.rs": "fn do_it() {}"
4994 }
4995 }
4996 },
4997 }),
4998 )
4999 .await;
5000
5001 fs.set_status_for_repo(
5002 Path::new(path!("/root/zed/.git")),
5003 &[
5004 (
5005 Path::new("crates/gpui/gpui.rs"),
5006 StatusCode::Modified.worktree(),
5007 ),
5008 (
5009 Path::new("crates/util/util.rs"),
5010 StatusCode::Modified.worktree(),
5011 ),
5012 ],
5013 );
5014
5015 let project =
5016 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5017 let workspace =
5018 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5019 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5020
5021 cx.read(|cx| {
5022 project
5023 .read(cx)
5024 .worktrees(cx)
5025 .nth(0)
5026 .unwrap()
5027 .read(cx)
5028 .as_local()
5029 .unwrap()
5030 .scan_complete()
5031 })
5032 .await;
5033
5034 cx.executor().run_until_parked();
5035
5036 let panel = workspace.update(cx, GitPanel::new).unwrap();
5037
5038 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5039 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5040 });
5041 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5042 handle.await;
5043
5044 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5045 pretty_assertions::assert_eq!(
5046 entries,
5047 [
5048 GitListEntry::Header(GitHeaderEntry {
5049 header: Section::Tracked
5050 }),
5051 GitListEntry::GitStatusEntry(GitStatusEntry {
5052 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5053 repo_path: "crates/gpui/gpui.rs".into(),
5054 status: StatusCode::Modified.worktree(),
5055 staging: StageStatus::Unstaged,
5056 }),
5057 GitListEntry::GitStatusEntry(GitStatusEntry {
5058 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5059 repo_path: "crates/util/util.rs".into(),
5060 status: StatusCode::Modified.worktree(),
5061 staging: StageStatus::Unstaged,
5062 },),
5063 ],
5064 );
5065
5066 // TODO(cole) restore this once repository deduplication is implemented properly.
5067 //cx.update_window_entity(&panel, |panel, window, cx| {
5068 // panel.select_last(&Default::default(), window, cx);
5069 // assert_eq!(panel.selected_entry, Some(2));
5070 // panel.open_diff(&Default::default(), window, cx);
5071 //});
5072 //cx.run_until_parked();
5073
5074 //let worktree_roots = workspace.update(cx, |workspace, cx| {
5075 // workspace
5076 // .worktrees(cx)
5077 // .map(|worktree| worktree.read(cx).abs_path())
5078 // .collect::<Vec<_>>()
5079 //});
5080 //pretty_assertions::assert_eq!(
5081 // worktree_roots,
5082 // vec![
5083 // Path::new(path!("/root/zed/crates/gpui")).into(),
5084 // Path::new(path!("/root/zed/crates/util/util.rs")).into(),
5085 // ]
5086 //);
5087
5088 //project.update(cx, |project, cx| {
5089 // let git_store = project.git_store().read(cx);
5090 // // The repo that comes from the single-file worktree can't be selected through the UI.
5091 // let filtered_entries = filtered_repository_entries(git_store, cx)
5092 // .iter()
5093 // .map(|repo| repo.read(cx).worktree_abs_path.clone())
5094 // .collect::<Vec<_>>();
5095 // assert_eq!(
5096 // filtered_entries,
5097 // [Path::new(path!("/root/zed/crates/gpui")).into()]
5098 // );
5099 // // But we can select it artificially here.
5100 // let repo_from_single_file_worktree = git_store
5101 // .repositories()
5102 // .values()
5103 // .find(|repo| {
5104 // repo.read(cx).worktree_abs_path.as_ref()
5105 // == Path::new(path!("/root/zed/crates/util/util.rs"))
5106 // })
5107 // .unwrap()
5108 // .clone();
5109
5110 // // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
5111 // repo_from_single_file_worktree.update(cx, |repo, cx| repo.set_as_active_repository(cx));
5112 //});
5113
5114 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5115 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5116 });
5117 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5118 handle.await;
5119 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5120 pretty_assertions::assert_eq!(
5121 entries,
5122 [
5123 GitListEntry::Header(GitHeaderEntry {
5124 header: Section::Tracked
5125 }),
5126 GitListEntry::GitStatusEntry(GitStatusEntry {
5127 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5128 repo_path: "crates/gpui/gpui.rs".into(),
5129 status: StatusCode::Modified.worktree(),
5130 staging: StageStatus::Unstaged,
5131 }),
5132 GitListEntry::GitStatusEntry(GitStatusEntry {
5133 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5134 repo_path: "crates/util/util.rs".into(),
5135 status: StatusCode::Modified.worktree(),
5136 staging: StageStatus::Unstaged,
5137 },),
5138 ],
5139 );
5140 }
5141}