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