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