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