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