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 let options = if force_push {
1710 PushOptions::Force
1711 } else {
1712 PushOptions::SetUpstream
1713 };
1714 let remote = self.get_current_remote(window, cx);
1715
1716 cx.spawn_in(window, move |this, mut cx| async move {
1717 let remote = match remote.await {
1718 Ok(Some(remote)) => remote,
1719 Ok(None) => {
1720 return Ok(());
1721 }
1722 Err(e) => {
1723 log::error!("Failed to get current remote: {}", e);
1724 this.update(&mut cx, |this, cx| this.show_error_toast("push", e, cx))
1725 .ok();
1726 return Ok(());
1727 }
1728 };
1729
1730 let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1731 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1732 })?;
1733
1734 let guard = this
1735 .update(&mut cx, |this, _| this.start_remote_operation())
1736 .ok();
1737
1738 let push = repo.update(&mut cx, |repo, cx| {
1739 repo.push(
1740 branch.name.clone(),
1741 remote.name.clone(),
1742 Some(options),
1743 askpass_delegate,
1744 cx,
1745 )
1746 })?;
1747
1748 let remote_output = push.await?;
1749 drop(guard);
1750
1751 let action = RemoteAction::Push(branch.name, remote);
1752 this.update(&mut cx, |this, cx| match remote_output {
1753 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
1754 Err(e) => {
1755 log::error!("Error while pushing {:?}", e);
1756 this.show_error_toast(action.name(), e, cx)
1757 }
1758 })?;
1759
1760 anyhow::Ok(())
1761 })
1762 .detach_and_log_err(cx);
1763 }
1764
1765 fn askpass_delegate(
1766 &self,
1767 operation: impl Into<SharedString>,
1768 window: &mut Window,
1769 cx: &mut Context<Self>,
1770 ) -> AskPassDelegate {
1771 let this = cx.weak_entity();
1772 let operation = operation.into();
1773 let window = window.window_handle();
1774 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1775 window
1776 .update(cx, |_, window, cx| {
1777 this.update(cx, |this, cx| {
1778 this.workspace.update(cx, |workspace, cx| {
1779 workspace.toggle_modal(window, cx, |window, cx| {
1780 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1781 });
1782 })
1783 })
1784 })
1785 .ok();
1786 })
1787 }
1788
1789 fn can_push_and_pull(&self, cx: &App) -> bool {
1790 crate::can_push_and_pull(&self.project, cx)
1791 }
1792
1793 fn get_current_remote(
1794 &mut self,
1795 window: &mut Window,
1796 cx: &mut Context<Self>,
1797 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1798 let repo = self.active_repository.clone();
1799 let workspace = self.workspace.clone();
1800 let mut cx = window.to_async(cx);
1801
1802 async move {
1803 let Some(repo) = repo else {
1804 return Err(anyhow::anyhow!("No active repository"));
1805 };
1806
1807 let mut current_remotes: Vec<Remote> = repo
1808 .update(&mut cx, |repo, _| {
1809 let Some(current_branch) = repo.current_branch() else {
1810 return Err(anyhow::anyhow!("No active branch"));
1811 };
1812
1813 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1814 })??
1815 .await??;
1816
1817 if current_remotes.len() == 0 {
1818 return Err(anyhow::anyhow!("No active remote"));
1819 } else if current_remotes.len() == 1 {
1820 return Ok(Some(current_remotes.pop().unwrap()));
1821 } else {
1822 let current_remotes: Vec<_> = current_remotes
1823 .into_iter()
1824 .map(|remotes| remotes.name)
1825 .collect();
1826 let selection = cx
1827 .update(|window, cx| {
1828 picker_prompt::prompt(
1829 "Pick which remote to push to",
1830 current_remotes.clone(),
1831 workspace,
1832 window,
1833 cx,
1834 )
1835 })?
1836 .await?;
1837
1838 Ok(selection.map(|selection| Remote {
1839 name: current_remotes[selection].clone(),
1840 }))
1841 }
1842 }
1843 }
1844
1845 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1846 let mut new_co_authors = Vec::new();
1847 let project = self.project.read(cx);
1848
1849 let Some(room) = self
1850 .workspace
1851 .upgrade()
1852 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1853 else {
1854 return Vec::default();
1855 };
1856
1857 let room = room.read(cx);
1858
1859 for (peer_id, collaborator) in project.collaborators() {
1860 if collaborator.is_host {
1861 continue;
1862 }
1863
1864 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1865 continue;
1866 };
1867 if participant.can_write() && participant.user.email.is_some() {
1868 let email = participant.user.email.clone().unwrap();
1869
1870 new_co_authors.push((
1871 participant
1872 .user
1873 .name
1874 .clone()
1875 .unwrap_or_else(|| participant.user.github_login.clone()),
1876 email,
1877 ))
1878 }
1879 }
1880 if !project.is_local() && !project.is_read_only(cx) {
1881 if let Some(user) = room.local_participant_user(cx) {
1882 if let Some(email) = user.email.clone() {
1883 new_co_authors.push((
1884 user.name
1885 .clone()
1886 .unwrap_or_else(|| user.github_login.clone()),
1887 email.clone(),
1888 ))
1889 }
1890 }
1891 }
1892 new_co_authors
1893 }
1894
1895 fn toggle_fill_co_authors(
1896 &mut self,
1897 _: &ToggleFillCoAuthors,
1898 _: &mut Window,
1899 cx: &mut Context<Self>,
1900 ) {
1901 self.add_coauthors = !self.add_coauthors;
1902 cx.notify();
1903 }
1904
1905 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1906 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1907
1908 let existing_text = message.to_ascii_lowercase();
1909 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1910 let mut ends_with_co_authors = false;
1911 let existing_co_authors = existing_text
1912 .lines()
1913 .filter_map(|line| {
1914 let line = line.trim();
1915 if line.starts_with(&lowercase_co_author_prefix) {
1916 ends_with_co_authors = true;
1917 Some(line)
1918 } else {
1919 ends_with_co_authors = false;
1920 None
1921 }
1922 })
1923 .collect::<HashSet<_>>();
1924
1925 let new_co_authors = self
1926 .potential_co_authors(cx)
1927 .into_iter()
1928 .filter(|(_, email)| {
1929 !existing_co_authors
1930 .iter()
1931 .any(|existing| existing.contains(email.as_str()))
1932 })
1933 .collect::<Vec<_>>();
1934
1935 if new_co_authors.is_empty() {
1936 return;
1937 }
1938
1939 if !ends_with_co_authors {
1940 message.push('\n');
1941 }
1942 for (name, email) in new_co_authors {
1943 message.push('\n');
1944 message.push_str(CO_AUTHOR_PREFIX);
1945 message.push_str(&name);
1946 message.push_str(" <");
1947 message.push_str(&email);
1948 message.push('>');
1949 }
1950 message.push('\n');
1951 }
1952
1953 fn schedule_update(
1954 &mut self,
1955 clear_pending: bool,
1956 window: &mut Window,
1957 cx: &mut Context<Self>,
1958 ) {
1959 let handle = cx.entity().downgrade();
1960 self.reopen_commit_buffer(window, cx);
1961 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1962 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1963 if let Some(git_panel) = handle.upgrade() {
1964 git_panel
1965 .update_in(&mut cx, |git_panel, _, cx| {
1966 if clear_pending {
1967 git_panel.clear_pending();
1968 }
1969 git_panel.update_visible_entries(cx);
1970 git_panel.update_editor_placeholder(cx);
1971 })
1972 .ok();
1973 }
1974 });
1975 }
1976
1977 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1978 let Some(active_repo) = self.active_repository.as_ref() else {
1979 return;
1980 };
1981 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1982 let project = self.project.read(cx);
1983 active_repo.open_commit_buffer(
1984 Some(project.languages().clone()),
1985 project.buffer_store().clone(),
1986 cx,
1987 )
1988 });
1989
1990 cx.spawn_in(window, |git_panel, mut cx| async move {
1991 let buffer = load_buffer.await?;
1992 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1993 if git_panel
1994 .commit_editor
1995 .read(cx)
1996 .buffer()
1997 .read(cx)
1998 .as_singleton()
1999 .as_ref()
2000 != Some(&buffer)
2001 {
2002 git_panel.commit_editor = cx.new(|cx| {
2003 commit_message_editor(
2004 buffer,
2005 git_panel.suggest_commit_message().as_deref(),
2006 git_panel.project.clone(),
2007 true,
2008 window,
2009 cx,
2010 )
2011 });
2012 }
2013 })
2014 })
2015 .detach_and_log_err(cx);
2016 }
2017
2018 fn clear_pending(&mut self) {
2019 self.pending.retain(|v| !v.finished)
2020 }
2021
2022 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2023 self.entries.clear();
2024 self.single_staged_entry.take();
2025 self.single_staged_entry.take();
2026 let mut changed_entries = Vec::new();
2027 let mut new_entries = Vec::new();
2028 let mut conflict_entries = Vec::new();
2029 let mut last_staged = None;
2030 let mut staged_count = 0;
2031
2032 let Some(repo) = self.active_repository.as_ref() else {
2033 // Just clear entries if no repository is active.
2034 cx.notify();
2035 return;
2036 };
2037
2038 let repo = repo.read(cx);
2039
2040 for entry in repo.status() {
2041 let is_conflict = repo.has_conflict(&entry.repo_path);
2042 let is_new = entry.status.is_created();
2043 let staging = entry.status.staging();
2044
2045 if self.pending.iter().any(|pending| {
2046 pending.target_status == TargetStatus::Reverted
2047 && !pending.finished
2048 && pending
2049 .entries
2050 .iter()
2051 .any(|pending| pending.repo_path == entry.repo_path)
2052 }) {
2053 continue;
2054 }
2055
2056 // dot_git_abs path always has at least one component, namely .git.
2057 let abs_path = repo
2058 .dot_git_abs_path
2059 .parent()
2060 .unwrap()
2061 .join(&entry.repo_path);
2062 let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2063 let entry = GitStatusEntry {
2064 repo_path: entry.repo_path.clone(),
2065 worktree_path,
2066 abs_path,
2067 status: entry.status,
2068 staging,
2069 };
2070
2071 if staging.has_staged() {
2072 staged_count += 1;
2073 last_staged = Some(entry.clone());
2074 }
2075
2076 if is_conflict {
2077 conflict_entries.push(entry);
2078 } else if is_new {
2079 new_entries.push(entry);
2080 } else {
2081 changed_entries.push(entry);
2082 }
2083 }
2084
2085 let mut pending_staged_count = 0;
2086 let mut last_pending_staged = None;
2087 let mut pending_status_for_last_staged = None;
2088 for pending in self.pending.iter() {
2089 if pending.target_status == TargetStatus::Staged {
2090 pending_staged_count += pending.entries.len();
2091 last_pending_staged = pending.entries.iter().next().cloned();
2092 }
2093 if let Some(last_staged) = &last_staged {
2094 if pending
2095 .entries
2096 .iter()
2097 .any(|entry| entry.repo_path == last_staged.repo_path)
2098 {
2099 pending_status_for_last_staged = Some(pending.target_status);
2100 }
2101 }
2102 }
2103
2104 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2105 match pending_status_for_last_staged {
2106 Some(TargetStatus::Staged) | None => {
2107 self.single_staged_entry = last_staged;
2108 }
2109 _ => {}
2110 }
2111 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2112 self.single_staged_entry = last_pending_staged;
2113 }
2114
2115 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2116 self.single_tracked_entry = changed_entries.first().cloned();
2117 }
2118
2119 if conflict_entries.len() > 0 {
2120 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2121 header: Section::Conflict,
2122 }));
2123 self.entries.extend(
2124 conflict_entries
2125 .into_iter()
2126 .map(GitListEntry::GitStatusEntry),
2127 );
2128 }
2129
2130 if changed_entries.len() > 0 {
2131 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2132 header: Section::Tracked,
2133 }));
2134 self.entries.extend(
2135 changed_entries
2136 .into_iter()
2137 .map(GitListEntry::GitStatusEntry),
2138 );
2139 }
2140 if new_entries.len() > 0 {
2141 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2142 header: Section::New,
2143 }));
2144 self.entries
2145 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2146 }
2147
2148 self.update_counts(repo);
2149
2150 self.select_first_entry_if_none(cx);
2151
2152 cx.notify();
2153 }
2154
2155 fn header_state(&self, header_type: Section) -> ToggleState {
2156 let (staged_count, count) = match header_type {
2157 Section::New => (self.new_staged_count, self.new_count),
2158 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2159 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2160 };
2161 if staged_count == 0 {
2162 ToggleState::Unselected
2163 } else if count == staged_count {
2164 ToggleState::Selected
2165 } else {
2166 ToggleState::Indeterminate
2167 }
2168 }
2169
2170 fn update_counts(&mut self, repo: &Repository) {
2171 self.conflicted_count = 0;
2172 self.conflicted_staged_count = 0;
2173 self.new_count = 0;
2174 self.tracked_count = 0;
2175 self.new_staged_count = 0;
2176 self.tracked_staged_count = 0;
2177 self.entry_count = 0;
2178 for entry in &self.entries {
2179 let Some(status_entry) = entry.status_entry() else {
2180 continue;
2181 };
2182 self.entry_count += 1;
2183 if repo.has_conflict(&status_entry.repo_path) {
2184 self.conflicted_count += 1;
2185 if self.entry_staging(status_entry).has_staged() {
2186 self.conflicted_staged_count += 1;
2187 }
2188 } else if status_entry.status.is_created() {
2189 self.new_count += 1;
2190 if self.entry_staging(status_entry).has_staged() {
2191 self.new_staged_count += 1;
2192 }
2193 } else {
2194 self.tracked_count += 1;
2195 if self.entry_staging(status_entry).has_staged() {
2196 self.tracked_staged_count += 1;
2197 }
2198 }
2199 }
2200 }
2201
2202 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2203 for pending in self.pending.iter().rev() {
2204 if pending
2205 .entries
2206 .iter()
2207 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2208 {
2209 match pending.target_status {
2210 TargetStatus::Staged => return StageStatus::Staged,
2211 TargetStatus::Unstaged => return StageStatus::Unstaged,
2212 TargetStatus::Reverted => continue,
2213 TargetStatus::Unchanged => continue,
2214 }
2215 }
2216 }
2217 entry.staging
2218 }
2219
2220 pub(crate) fn has_staged_changes(&self) -> bool {
2221 self.tracked_staged_count > 0
2222 || self.new_staged_count > 0
2223 || self.conflicted_staged_count > 0
2224 }
2225
2226 pub(crate) fn has_unstaged_changes(&self) -> bool {
2227 self.tracked_count > self.tracked_staged_count
2228 || self.new_count > self.new_staged_count
2229 || self.conflicted_count > self.conflicted_staged_count
2230 }
2231
2232 fn has_conflicts(&self) -> bool {
2233 self.conflicted_count > 0
2234 }
2235
2236 fn has_tracked_changes(&self) -> bool {
2237 self.tracked_count > 0
2238 }
2239
2240 pub fn has_unstaged_conflicts(&self) -> bool {
2241 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2242 }
2243
2244 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2245 let action = action.into();
2246 let Some(workspace) = self.workspace.upgrade() else {
2247 return;
2248 };
2249
2250 let message = e.to_string().trim().to_string();
2251 if message
2252 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2253 .next()
2254 .is_some()
2255 {
2256 return; // Hide the cancelled by user message
2257 } else {
2258 let project = self.project.clone();
2259 workspace.update(cx, |workspace, cx| {
2260 let workspace_weak = cx.weak_entity();
2261 let toast =
2262 StatusToast::new(format!("git {} failed", action.clone()), cx, |this, _cx| {
2263 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2264 .action("View Log", move |window, cx| {
2265 let message = message.clone();
2266 let project = project.clone();
2267 let action = action.clone();
2268 workspace_weak
2269 .update(cx, move |workspace, cx| {
2270 Self::open_output(
2271 project, action, workspace, &message, window, cx,
2272 )
2273 })
2274 .ok();
2275 })
2276 });
2277 workspace.toggle_status_toast(toast, cx)
2278 });
2279 }
2280 }
2281
2282 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2283 let Some(workspace) = self.workspace.upgrade() else {
2284 return;
2285 };
2286
2287 workspace.update(cx, |workspace, cx| {
2288 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2289 let workspace_weak = cx.weak_entity();
2290 let operation = action.name();
2291
2292 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2293 use remote_output::SuccessStyle::*;
2294 let project = self.project.clone();
2295 match style {
2296 Toast { .. } => this,
2297 ToastWithLog { output } => this
2298 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2299 .action("View Log", move |window, cx| {
2300 let output = output.clone();
2301 let project = project.clone();
2302 let output =
2303 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2304 workspace_weak
2305 .update(cx, move |workspace, cx| {
2306 Self::open_output(
2307 project, operation, workspace, &output, window, cx,
2308 )
2309 })
2310 .ok();
2311 }),
2312 PushPrLink { link } => this
2313 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2314 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2315 }
2316 });
2317 workspace.toggle_status_toast(status_toast, cx)
2318 });
2319 }
2320
2321 fn open_output(
2322 project: Entity<Project>,
2323 operation: impl Into<SharedString>,
2324 workspace: &mut Workspace,
2325 output: &str,
2326 window: &mut Window,
2327 cx: &mut Context<Workspace>,
2328 ) {
2329 let operation = operation.into();
2330 let buffer = cx.new(|cx| Buffer::local(output, cx));
2331 let editor = cx.new(|cx| {
2332 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2333 editor.buffer().update(cx, |buffer, cx| {
2334 buffer.set_title(format!("Output from git {operation}"), cx);
2335 });
2336 editor.set_read_only(true);
2337 editor
2338 });
2339
2340 workspace.add_item_to_center(Box::new(editor), window, cx);
2341 }
2342
2343 pub fn render_spinner(&self) -> Option<impl IntoElement> {
2344 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2345 Icon::new(IconName::ArrowCircle)
2346 .size(IconSize::XSmall)
2347 .color(Color::Info)
2348 .with_animation(
2349 "arrow-circle",
2350 Animation::new(Duration::from_secs(2)).repeat(),
2351 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2352 )
2353 .into_any_element()
2354 })
2355 }
2356
2357 pub fn can_commit(&self) -> bool {
2358 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2359 }
2360
2361 pub fn can_stage_all(&self) -> bool {
2362 self.has_unstaged_changes()
2363 }
2364
2365 pub fn can_unstage_all(&self) -> bool {
2366 self.has_staged_changes()
2367 }
2368
2369 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2370 let focus_handle = self.focus_handle.clone();
2371 PopoverMenu::new(id.into())
2372 .trigger(
2373 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
2374 .icon_size(IconSize::Small)
2375 .icon_color(Color::Muted),
2376 )
2377 .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
2378 .anchor(Corner::TopRight)
2379 }
2380
2381 pub(crate) fn render_generate_commit_message_button(
2382 &self,
2383 cx: &Context<Self>,
2384 ) -> Option<AnyElement> {
2385 current_language_model(cx).is_some().then(|| {
2386 if self.generate_commit_message_task.is_some() {
2387 return h_flex()
2388 .gap_1()
2389 .child(
2390 Icon::new(IconName::ArrowCircle)
2391 .size(IconSize::XSmall)
2392 .color(Color::Info)
2393 .with_animation(
2394 "arrow-circle",
2395 Animation::new(Duration::from_secs(2)).repeat(),
2396 |icon, delta| {
2397 icon.transform(Transformation::rotate(percentage(delta)))
2398 },
2399 ),
2400 )
2401 .child(
2402 Label::new("Generating Commit...")
2403 .size(LabelSize::Small)
2404 .color(Color::Muted),
2405 )
2406 .into_any_element();
2407 }
2408
2409 let can_commit = self.can_commit();
2410 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2411 IconButton::new("generate-commit-message", IconName::AiEdit)
2412 .shape(ui::IconButtonShape::Square)
2413 .icon_color(Color::Muted)
2414 .tooltip(move |window, cx| {
2415 if can_commit {
2416 Tooltip::for_action_in(
2417 "Generate Commit Message",
2418 &git::GenerateCommitMessage,
2419 &editor_focus_handle,
2420 window,
2421 cx,
2422 )
2423 } else {
2424 Tooltip::simple("No changes to commit", cx)
2425 }
2426 })
2427 .disabled(!can_commit)
2428 .on_click(cx.listener(move |this, _event, _window, cx| {
2429 this.generate_commit_message(cx);
2430 }))
2431 .into_any_element()
2432 })
2433 }
2434
2435 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2436 let potential_co_authors = self.potential_co_authors(cx);
2437 if potential_co_authors.is_empty() {
2438 None
2439 } else {
2440 Some(
2441 IconButton::new("co-authors", IconName::Person)
2442 .shape(ui::IconButtonShape::Square)
2443 .icon_color(Color::Disabled)
2444 .selected_icon_color(Color::Selected)
2445 .toggle_state(self.add_coauthors)
2446 .tooltip(move |_, cx| {
2447 let title = format!(
2448 "Add co-authored-by:{}{}",
2449 if potential_co_authors.len() == 1 {
2450 ""
2451 } else {
2452 "\n"
2453 },
2454 potential_co_authors
2455 .iter()
2456 .map(|(name, email)| format!(" {} <{}>", name, email))
2457 .join("\n")
2458 );
2459 Tooltip::simple(title, cx)
2460 })
2461 .on_click(cx.listener(|this, _, _, cx| {
2462 this.add_coauthors = !this.add_coauthors;
2463 cx.notify();
2464 }))
2465 .into_any_element(),
2466 )
2467 }
2468 }
2469
2470 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2471 if self.has_unstaged_conflicts() {
2472 (false, "You must resolve conflicts before committing")
2473 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2474 (false, "No changes to commit")
2475 } else if self.pending_commit.is_some() {
2476 (false, "Commit in progress")
2477 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2478 (false, "No commit message")
2479 } else if !self.has_write_access(cx) {
2480 (false, "You do not have write access to this project")
2481 } else {
2482 (true, self.commit_button_title())
2483 }
2484 }
2485
2486 pub fn commit_button_title(&self) -> &'static str {
2487 if self.has_staged_changes() {
2488 "Commit"
2489 } else {
2490 "Commit Tracked"
2491 }
2492 }
2493
2494 fn expand_commit_editor(
2495 &mut self,
2496 _: &git::ExpandCommitEditor,
2497 window: &mut Window,
2498 cx: &mut Context<Self>,
2499 ) {
2500 let workspace = self.workspace.clone();
2501 window.defer(cx, move |window, cx| {
2502 workspace
2503 .update(cx, |workspace, cx| {
2504 CommitModal::toggle(workspace, window, cx)
2505 })
2506 .ok();
2507 })
2508 }
2509
2510 fn render_panel_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2511 let text;
2512 let action;
2513 let tooltip;
2514 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
2515 text = "Unstage All";
2516 action = git::UnstageAll.boxed_clone();
2517 tooltip = "git reset";
2518 } else {
2519 text = "Stage All";
2520 action = git::StageAll.boxed_clone();
2521 tooltip = "git add --all ."
2522 }
2523
2524 let change_string = match self.entry_count {
2525 0 => "No Changes".to_string(),
2526 1 => "1 Change".to_string(),
2527 _ => format!("{} Changes", self.entry_count),
2528 };
2529
2530 self.panel_header_container(window, cx)
2531 .px_2()
2532 .child(
2533 panel_button(change_string)
2534 .color(Color::Muted)
2535 .tooltip(Tooltip::for_action_title_in(
2536 "Open diff",
2537 &Diff,
2538 &self.focus_handle,
2539 ))
2540 .on_click(|_, _, cx| {
2541 cx.defer(|cx| {
2542 cx.dispatch_action(&Diff);
2543 })
2544 }),
2545 )
2546 .child(div().flex_grow()) // spacer
2547 .child(self.render_overflow_menu("overflow_menu"))
2548 .child(
2549 panel_filled_button(text)
2550 .tooltip(Tooltip::for_action_title_in(
2551 tooltip,
2552 action.as_ref(),
2553 &self.focus_handle,
2554 ))
2555 .disabled(self.entry_count == 0)
2556 .on_click(move |_, _, cx| {
2557 let action = action.boxed_clone();
2558 cx.defer(move |cx| {
2559 cx.dispatch_action(action.as_ref());
2560 })
2561 }),
2562 )
2563 }
2564
2565 pub fn render_footer(
2566 &self,
2567 window: &mut Window,
2568 cx: &mut Context<Self>,
2569 ) -> Option<impl IntoElement> {
2570 let active_repository = self.active_repository.clone()?;
2571 let (can_commit, tooltip) = self.configure_commit_button(cx);
2572 let project = self.project.clone().read(cx);
2573 let panel_editor_style = panel_editor_style(true, window, cx);
2574
2575 let enable_coauthors = self.render_co_authors(cx);
2576 let title = self.commit_button_title();
2577
2578 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2579 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2580 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2581
2582 let branch = active_repository.read(cx).current_branch().cloned();
2583
2584 let footer_size = px(32.);
2585 let gap = px(8.0);
2586 let max_height = window.line_height() * 5. + gap + footer_size;
2587
2588 let git_panel = cx.entity().clone();
2589 let display_name = SharedString::from(Arc::from(
2590 active_repository
2591 .read(cx)
2592 .display_name(project, cx)
2593 .trim_end_matches("/"),
2594 ));
2595
2596 let footer = v_flex()
2597 .child(PanelRepoFooter::new(
2598 "footer-button",
2599 display_name,
2600 branch,
2601 Some(git_panel),
2602 ))
2603 .child(
2604 panel_editor_container(window, cx)
2605 .id("commit-editor-container")
2606 .relative()
2607 .h(max_height)
2608 .w_full()
2609 .border_t_1()
2610 .border_color(cx.theme().colors().border_variant)
2611 .bg(cx.theme().colors().editor_background)
2612 .cursor_text()
2613 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2614 window.focus(&this.commit_editor.focus_handle(cx));
2615 }))
2616 .child(
2617 h_flex()
2618 .id("commit-footer")
2619 .absolute()
2620 .bottom_0()
2621 .left_0()
2622 .w_full()
2623 .px_2()
2624 .h(footer_size)
2625 .flex_none()
2626 .justify_between()
2627 .child(
2628 self.render_generate_commit_message_button(cx)
2629 .unwrap_or_else(|| div().into_any_element()),
2630 )
2631 .child(
2632 h_flex().gap_0p5().children(enable_coauthors).child(
2633 panel_filled_button(title)
2634 .tooltip(move |window, cx| {
2635 if can_commit {
2636 Tooltip::for_action_in(
2637 tooltip,
2638 &Commit,
2639 &commit_tooltip_focus_handle,
2640 window,
2641 cx,
2642 )
2643 } else {
2644 Tooltip::simple(tooltip, cx)
2645 }
2646 })
2647 .disabled(!can_commit || self.modal_open)
2648 .on_click({
2649 cx.listener(move |this, _: &ClickEvent, window, cx| {
2650 this.commit_changes(window, cx)
2651 })
2652 }),
2653 ),
2654 ),
2655 )
2656 .child(
2657 div()
2658 .pr_2p5()
2659 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2660 )
2661 .child(
2662 h_flex()
2663 .absolute()
2664 .top_2()
2665 .right_2()
2666 .opacity(0.5)
2667 .hover(|this| this.opacity(1.0))
2668 .child(
2669 panel_icon_button("expand-commit-editor", IconName::Maximize)
2670 .icon_size(IconSize::Small)
2671 .size(ui::ButtonSize::Default)
2672 .tooltip(move |window, cx| {
2673 Tooltip::for_action_in(
2674 "Open Commit Modal",
2675 &git::ExpandCommitEditor,
2676 &expand_tooltip_focus_handle,
2677 window,
2678 cx,
2679 )
2680 })
2681 .on_click(cx.listener({
2682 move |_, _, window, cx| {
2683 window.dispatch_action(
2684 git::ExpandCommitEditor.boxed_clone(),
2685 cx,
2686 )
2687 }
2688 })),
2689 ),
2690 ),
2691 );
2692
2693 Some(footer)
2694 }
2695
2696 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2697 let active_repository = self.active_repository.as_ref()?;
2698 let branch = active_repository.read(cx).current_branch()?;
2699 let commit = branch.most_recent_commit.as_ref()?.clone();
2700
2701 let this = cx.entity();
2702 Some(
2703 h_flex()
2704 .items_center()
2705 .py_2()
2706 .px(px(8.))
2707 .border_color(cx.theme().colors().border)
2708 .gap_1p5()
2709 .child(
2710 div()
2711 .flex_grow()
2712 .overflow_hidden()
2713 .items_center()
2714 .max_w(relative(0.85))
2715 .h_full()
2716 .child(
2717 Label::new(commit.subject.clone())
2718 .size(LabelSize::Small)
2719 .truncate(),
2720 )
2721 .id("commit-msg-hover")
2722 .hoverable_tooltip(move |window, cx| {
2723 GitPanelMessageTooltip::new(
2724 this.clone(),
2725 commit.sha.clone(),
2726 window,
2727 cx,
2728 )
2729 .into()
2730 }),
2731 )
2732 .child(div().flex_1())
2733 .when(commit.has_parent, |this| {
2734 let has_unstaged = self.has_unstaged_changes();
2735 this.child(
2736 panel_icon_button("undo", IconName::Undo)
2737 .icon_size(IconSize::Small)
2738 .icon_color(Color::Muted)
2739 .tooltip(move |window, cx| {
2740 Tooltip::with_meta(
2741 "Uncommit",
2742 Some(&git::Uncommit),
2743 if has_unstaged {
2744 "git reset HEAD^ --soft"
2745 } else {
2746 "git reset HEAD^"
2747 },
2748 window,
2749 cx,
2750 )
2751 })
2752 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2753 )
2754 }),
2755 )
2756 }
2757
2758 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2759 h_flex()
2760 .h_full()
2761 .flex_grow()
2762 .justify_center()
2763 .items_center()
2764 .child(
2765 v_flex()
2766 .gap_3()
2767 .child(if self.active_repository.is_some() {
2768 "No changes to commit"
2769 } else {
2770 "No Git repositories"
2771 })
2772 .text_ui_sm(cx)
2773 .mx_auto()
2774 .text_color(Color::Placeholder.color(cx)),
2775 )
2776 }
2777
2778 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2779 let scroll_bar_style = self.show_scrollbar(cx);
2780 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2781
2782 if !self.should_show_scrollbar(cx)
2783 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2784 {
2785 return None;
2786 }
2787
2788 Some(
2789 div()
2790 .id("git-panel-vertical-scroll")
2791 .occlude()
2792 .flex_none()
2793 .h_full()
2794 .cursor_default()
2795 .when(show_container, |this| this.pl_1().px_1p5())
2796 .when(!show_container, |this| {
2797 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2798 })
2799 .on_mouse_move(cx.listener(|_, _, _, cx| {
2800 cx.notify();
2801 cx.stop_propagation()
2802 }))
2803 .on_hover(|_, _, cx| {
2804 cx.stop_propagation();
2805 })
2806 .on_any_mouse_down(|_, _, cx| {
2807 cx.stop_propagation();
2808 })
2809 .on_mouse_up(
2810 MouseButton::Left,
2811 cx.listener(|this, _, window, cx| {
2812 if !this.scrollbar_state.is_dragging()
2813 && !this.focus_handle.contains_focused(window, cx)
2814 {
2815 this.hide_scrollbar(window, cx);
2816 cx.notify();
2817 }
2818
2819 cx.stop_propagation();
2820 }),
2821 )
2822 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2823 cx.notify();
2824 }))
2825 .children(Scrollbar::vertical(
2826 // percentage as f32..end_offset as f32,
2827 self.scrollbar_state.clone(),
2828 )),
2829 )
2830 }
2831
2832 fn render_buffer_header_controls(
2833 &self,
2834 entity: &Entity<Self>,
2835 file: &Arc<dyn File>,
2836 _: &Window,
2837 cx: &App,
2838 ) -> Option<AnyElement> {
2839 let repo = self.active_repository.as_ref()?.read(cx);
2840 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2841 let ix = self.entry_by_path(&repo_path)?;
2842 let entry = self.entries.get(ix)?;
2843
2844 let entry_staging = self.entry_staging(entry.status_entry()?);
2845
2846 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
2847 .disabled(!self.has_write_access(cx))
2848 .fill()
2849 .elevation(ElevationIndex::Surface)
2850 .on_click({
2851 let entry = entry.clone();
2852 let git_panel = entity.downgrade();
2853 move |_, window, cx| {
2854 git_panel
2855 .update(cx, |this, cx| {
2856 this.toggle_staged_for_entry(&entry, window, cx);
2857 cx.stop_propagation();
2858 })
2859 .ok();
2860 }
2861 });
2862 Some(
2863 h_flex()
2864 .id("start-slot")
2865 .text_lg()
2866 .child(checkbox)
2867 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2868 // prevent the list item active state triggering when toggling checkbox
2869 cx.stop_propagation();
2870 })
2871 .into_any_element(),
2872 )
2873 }
2874
2875 fn render_entries(
2876 &self,
2877 has_write_access: bool,
2878 _: &Window,
2879 cx: &mut Context<Self>,
2880 ) -> impl IntoElement {
2881 let entry_count = self.entries.len();
2882
2883 h_flex()
2884 .size_full()
2885 .flex_grow()
2886 .overflow_hidden()
2887 .child(
2888 uniform_list(cx.entity().clone(), "entries", entry_count, {
2889 move |this, range, window, cx| {
2890 let mut items = Vec::with_capacity(range.end - range.start);
2891
2892 for ix in range {
2893 match &this.entries.get(ix) {
2894 Some(GitListEntry::GitStatusEntry(entry)) => {
2895 items.push(this.render_entry(
2896 ix,
2897 entry,
2898 has_write_access,
2899 window,
2900 cx,
2901 ));
2902 }
2903 Some(GitListEntry::Header(header)) => {
2904 items.push(this.render_list_header(
2905 ix,
2906 header,
2907 has_write_access,
2908 window,
2909 cx,
2910 ));
2911 }
2912 None => {}
2913 }
2914 }
2915
2916 items
2917 }
2918 })
2919 .size_full()
2920 .with_sizing_behavior(ListSizingBehavior::Auto)
2921 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2922 .track_scroll(self.scroll_handle.clone()),
2923 )
2924 .on_mouse_down(
2925 MouseButton::Right,
2926 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2927 this.deploy_panel_context_menu(event.position, window, cx)
2928 }),
2929 )
2930 .children(self.render_scrollbar(cx))
2931 }
2932
2933 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2934 Label::new(label.into()).color(color).single_line()
2935 }
2936
2937 fn list_item_height(&self) -> Rems {
2938 rems(1.75)
2939 }
2940
2941 fn render_list_header(
2942 &self,
2943 ix: usize,
2944 header: &GitHeaderEntry,
2945 _: bool,
2946 _: &Window,
2947 _: &Context<Self>,
2948 ) -> AnyElement {
2949 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2950
2951 h_flex()
2952 .id(id)
2953 .h(self.list_item_height())
2954 .w_full()
2955 .items_end()
2956 .px(rems(0.75)) // ~12px
2957 .pb(rems(0.3125)) // ~ 5px
2958 .child(
2959 Label::new(header.title())
2960 .color(Color::Muted)
2961 .size(LabelSize::Small)
2962 .line_height_style(LineHeightStyle::UiLabel)
2963 .single_line(),
2964 )
2965 .into_any_element()
2966 }
2967
2968 fn load_commit_details(
2969 &self,
2970 sha: &str,
2971 cx: &mut Context<Self>,
2972 ) -> Task<anyhow::Result<CommitDetails>> {
2973 let Some(repo) = self.active_repository.clone() else {
2974 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2975 };
2976 repo.update(cx, |repo, cx| {
2977 let show = repo.show(sha);
2978 cx.spawn(|_, _| async move { show.await? })
2979 })
2980 }
2981
2982 fn deploy_entry_context_menu(
2983 &mut self,
2984 position: Point<Pixels>,
2985 ix: usize,
2986 window: &mut Window,
2987 cx: &mut Context<Self>,
2988 ) {
2989 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2990 return;
2991 };
2992 let stage_title = if entry.status.staging().is_fully_staged() {
2993 "Unstage File"
2994 } else {
2995 "Stage File"
2996 };
2997 let restore_title = if entry.status.is_created() {
2998 "Trash File"
2999 } else {
3000 "Restore File"
3001 };
3002 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
3003 context_menu
3004 .context(self.focus_handle.clone())
3005 .action(stage_title, ToggleStaged.boxed_clone())
3006 .action(restore_title, git::RestoreFile.boxed_clone())
3007 .separator()
3008 .action("Open Diff", Confirm.boxed_clone())
3009 .action("Open File", SecondaryConfirm.boxed_clone())
3010 });
3011 self.selected_entry = Some(ix);
3012 self.set_context_menu(context_menu, position, window, cx);
3013 }
3014
3015 fn deploy_panel_context_menu(
3016 &mut self,
3017 position: Point<Pixels>,
3018 window: &mut Window,
3019 cx: &mut Context<Self>,
3020 ) {
3021 let context_menu = git_panel_context_menu(self.focus_handle.clone(), window, cx);
3022 self.set_context_menu(context_menu, position, window, cx);
3023 }
3024
3025 fn set_context_menu(
3026 &mut self,
3027 context_menu: Entity<ContextMenu>,
3028 position: Point<Pixels>,
3029 window: &Window,
3030 cx: &mut Context<Self>,
3031 ) {
3032 let subscription = cx.subscribe_in(
3033 &context_menu,
3034 window,
3035 |this, _, _: &DismissEvent, window, cx| {
3036 if this.context_menu.as_ref().is_some_and(|context_menu| {
3037 context_menu.0.focus_handle(cx).contains_focused(window, cx)
3038 }) {
3039 cx.focus_self(window);
3040 }
3041 this.context_menu.take();
3042 cx.notify();
3043 },
3044 );
3045 self.context_menu = Some((context_menu, position, subscription));
3046 cx.notify();
3047 }
3048
3049 fn render_entry(
3050 &self,
3051 ix: usize,
3052 entry: &GitStatusEntry,
3053 has_write_access: bool,
3054 window: &Window,
3055 cx: &Context<Self>,
3056 ) -> AnyElement {
3057 let display_name = entry
3058 .worktree_path
3059 .file_name()
3060 .map(|name| name.to_string_lossy().into_owned())
3061 .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
3062
3063 let worktree_path = entry.worktree_path.clone();
3064 let selected = self.selected_entry == Some(ix);
3065 let marked = self.marked_entries.contains(&ix);
3066 let status_style = GitPanelSettings::get_global(cx).status_style;
3067 let status = entry.status;
3068 let modifiers = self.current_modifiers;
3069 let shift_held = modifiers.shift;
3070
3071 let has_conflict = status.is_conflicted();
3072 let is_modified = status.is_modified();
3073 let is_deleted = status.is_deleted();
3074
3075 let label_color = if status_style == StatusStyle::LabelColor {
3076 if has_conflict {
3077 Color::Conflict
3078 } else if is_modified {
3079 Color::Modified
3080 } else if is_deleted {
3081 // We don't want a bunch of red labels in the list
3082 Color::Disabled
3083 } else {
3084 Color::Created
3085 }
3086 } else {
3087 Color::Default
3088 };
3089
3090 let path_color = if status.is_deleted() {
3091 Color::Disabled
3092 } else {
3093 Color::Muted
3094 };
3095
3096 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3097 let checkbox_wrapper_id: ElementId =
3098 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3099 let checkbox_id: ElementId =
3100 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3101
3102 let entry_staging = self.entry_staging(entry);
3103 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3104
3105 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3106 is_staged = ToggleState::Selected;
3107 }
3108
3109 let handle = cx.weak_entity();
3110
3111 let selected_bg_alpha = 0.08;
3112 let marked_bg_alpha = 0.12;
3113 let state_opacity_step = 0.04;
3114
3115 let base_bg = match (selected, marked) {
3116 (true, true) => cx
3117 .theme()
3118 .status()
3119 .info
3120 .alpha(selected_bg_alpha + marked_bg_alpha),
3121 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3122 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3123 _ => cx.theme().colors().ghost_element_background,
3124 };
3125
3126 let hover_bg = if selected {
3127 cx.theme()
3128 .status()
3129 .info
3130 .alpha(selected_bg_alpha + state_opacity_step)
3131 } else {
3132 cx.theme().colors().ghost_element_hover
3133 };
3134
3135 let active_bg = if selected {
3136 cx.theme()
3137 .status()
3138 .info
3139 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3140 } else {
3141 cx.theme().colors().ghost_element_active
3142 };
3143
3144 h_flex()
3145 .id(id)
3146 .h(self.list_item_height())
3147 .w_full()
3148 .items_center()
3149 .border_1()
3150 .when(selected && self.focus_handle.is_focused(window), |el| {
3151 el.border_color(cx.theme().colors().border_focused)
3152 })
3153 .px(rems(0.75)) // ~12px
3154 .overflow_hidden()
3155 .flex_none()
3156 .gap_1p5()
3157 .bg(base_bg)
3158 .hover(|this| this.bg(hover_bg))
3159 .active(|this| this.bg(active_bg))
3160 .on_click({
3161 cx.listener(move |this, event: &ClickEvent, window, cx| {
3162 this.selected_entry = Some(ix);
3163 cx.notify();
3164 if event.modifiers().secondary() {
3165 this.open_file(&Default::default(), window, cx)
3166 } else {
3167 this.open_diff(&Default::default(), window, cx);
3168 this.focus_handle.focus(window);
3169 }
3170 })
3171 })
3172 .on_mouse_down(
3173 MouseButton::Right,
3174 move |event: &MouseDownEvent, window, cx| {
3175 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3176 if event.button != MouseButton::Right {
3177 return;
3178 }
3179
3180 let Some(this) = handle.upgrade() else {
3181 return;
3182 };
3183 this.update(cx, |this, cx| {
3184 this.deploy_entry_context_menu(event.position, ix, window, cx);
3185 });
3186 cx.stop_propagation();
3187 },
3188 )
3189 // .on_secondary_mouse_down(cx.listener(
3190 // move |this, event: &MouseDownEvent, window, cx| {
3191 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3192 // cx.stop_propagation();
3193 // },
3194 // ))
3195 .child(
3196 div()
3197 .id(checkbox_wrapper_id)
3198 .flex_none()
3199 .occlude()
3200 .cursor_pointer()
3201 .ml_neg_0p5()
3202 .child(
3203 Checkbox::new(checkbox_id, is_staged)
3204 .disabled(!has_write_access)
3205 .fill()
3206 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
3207 .elevation(ElevationIndex::Surface)
3208 .on_click({
3209 let entry = entry.clone();
3210 cx.listener(move |this, _, window, cx| {
3211 if !has_write_access {
3212 return;
3213 }
3214 this.toggle_staged_for_entry(
3215 &GitListEntry::GitStatusEntry(entry.clone()),
3216 window,
3217 cx,
3218 );
3219 cx.stop_propagation();
3220 })
3221 })
3222 .tooltip(move |window, cx| {
3223 let is_staged = entry_staging.is_fully_staged();
3224
3225 let action = if is_staged { "Unstage" } else { "Stage" };
3226 let tooltip_name = if shift_held {
3227 format!("{} section", action)
3228 } else {
3229 action.to_string()
3230 };
3231
3232 let meta = if shift_held {
3233 format!(
3234 "Release shift to {} single entry",
3235 action.to_lowercase()
3236 )
3237 } else {
3238 format!("Shift click to {} section", action.to_lowercase())
3239 };
3240
3241 Tooltip::with_meta(
3242 tooltip_name,
3243 Some(&ToggleStaged),
3244 meta,
3245 window,
3246 cx,
3247 )
3248 }),
3249 ),
3250 )
3251 .child(git_status_icon(status))
3252 .child(
3253 h_flex()
3254 .items_center()
3255 .overflow_hidden()
3256 .when_some(worktree_path.parent(), |this, parent| {
3257 let parent_str = parent.to_string_lossy();
3258 if !parent_str.is_empty() {
3259 this.child(
3260 self.entry_label(format!("{}/", parent_str), path_color)
3261 .when(status.is_deleted(), |this| this.strikethrough()),
3262 )
3263 } else {
3264 this
3265 }
3266 })
3267 .child(
3268 self.entry_label(display_name.clone(), label_color)
3269 .when(status.is_deleted(), |this| this.strikethrough()),
3270 ),
3271 )
3272 .into_any_element()
3273 }
3274
3275 fn has_write_access(&self, cx: &App) -> bool {
3276 !self.project.read(cx).is_read_only(cx)
3277 }
3278}
3279
3280fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3281 let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3282 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3283 provider.is_authenticated(cx).then(|| model)
3284}
3285
3286impl Render for GitPanel {
3287 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3288 let project = self.project.read(cx);
3289 let has_entries = self.entries.len() > 0;
3290 let room = self
3291 .workspace
3292 .upgrade()
3293 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3294
3295 let has_write_access = self.has_write_access(cx);
3296
3297 let has_co_authors = room.map_or(false, |room| {
3298 room.read(cx)
3299 .remote_participants()
3300 .values()
3301 .any(|remote_participant| remote_participant.can_write())
3302 });
3303
3304 v_flex()
3305 .id("git_panel")
3306 .key_context(self.dispatch_context(window, cx))
3307 .track_focus(&self.focus_handle)
3308 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3309 .when(has_write_access && !project.is_read_only(cx), |this| {
3310 this.on_action(cx.listener(Self::toggle_staged_for_selected))
3311 .on_action(cx.listener(GitPanel::commit))
3312 .on_action(cx.listener(Self::stage_all))
3313 .on_action(cx.listener(Self::unstage_all))
3314 .on_action(cx.listener(Self::stage_selected))
3315 .on_action(cx.listener(Self::unstage_selected))
3316 .on_action(cx.listener(Self::restore_tracked_files))
3317 .on_action(cx.listener(Self::revert_selected))
3318 .on_action(cx.listener(Self::clean_all))
3319 .on_action(cx.listener(Self::generate_commit_message_action))
3320 })
3321 .on_action(cx.listener(Self::select_first))
3322 .on_action(cx.listener(Self::select_next))
3323 .on_action(cx.listener(Self::select_previous))
3324 .on_action(cx.listener(Self::select_last))
3325 .on_action(cx.listener(Self::close_panel))
3326 .on_action(cx.listener(Self::open_diff))
3327 .on_action(cx.listener(Self::open_file))
3328 .on_action(cx.listener(Self::focus_changes_list))
3329 .on_action(cx.listener(Self::focus_editor))
3330 .on_action(cx.listener(Self::expand_commit_editor))
3331 .when(has_write_access && has_co_authors, |git_panel| {
3332 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3333 })
3334 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3335 .on_hover(cx.listener(|this, hovered, window, cx| {
3336 if *hovered {
3337 this.show_scrollbar = true;
3338 this.hide_scrollbar_task.take();
3339 cx.notify();
3340 } else if !this.focus_handle.contains_focused(window, cx) {
3341 this.hide_scrollbar(window, cx);
3342 }
3343 }))
3344 .size_full()
3345 .overflow_hidden()
3346 .bg(ElevationIndex::Surface.bg(cx))
3347 .child(
3348 v_flex()
3349 .size_full()
3350 .child(self.render_panel_header(window, cx))
3351 .map(|this| {
3352 if has_entries {
3353 this.child(self.render_entries(has_write_access, window, cx))
3354 } else {
3355 this.child(self.render_empty_state(cx).into_any_element())
3356 }
3357 })
3358 .children(self.render_footer(window, cx))
3359 .children(self.render_previous_commit(cx))
3360 .into_any_element(),
3361 )
3362 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3363 deferred(
3364 anchored()
3365 .position(*position)
3366 .anchor(gpui::Corner::TopLeft)
3367 .child(menu.clone()),
3368 )
3369 .with_priority(1)
3370 }))
3371 }
3372}
3373
3374impl Focusable for GitPanel {
3375 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3376 self.focus_handle.clone()
3377 }
3378}
3379
3380impl EventEmitter<Event> for GitPanel {}
3381
3382impl EventEmitter<PanelEvent> for GitPanel {}
3383
3384pub(crate) struct GitPanelAddon {
3385 pub(crate) workspace: WeakEntity<Workspace>,
3386}
3387
3388impl editor::Addon for GitPanelAddon {
3389 fn to_any(&self) -> &dyn std::any::Any {
3390 self
3391 }
3392
3393 fn render_buffer_header_controls(
3394 &self,
3395 excerpt_info: &ExcerptInfo,
3396 window: &Window,
3397 cx: &App,
3398 ) -> Option<AnyElement> {
3399 let file = excerpt_info.buffer.file()?;
3400 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3401
3402 git_panel
3403 .read(cx)
3404 .render_buffer_header_controls(&git_panel, &file, window, cx)
3405 }
3406}
3407
3408impl Panel for GitPanel {
3409 fn persistent_name() -> &'static str {
3410 "GitPanel"
3411 }
3412
3413 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3414 GitPanelSettings::get_global(cx).dock
3415 }
3416
3417 fn position_is_valid(&self, position: DockPosition) -> bool {
3418 matches!(position, DockPosition::Left | DockPosition::Right)
3419 }
3420
3421 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3422 settings::update_settings_file::<GitPanelSettings>(
3423 self.fs.clone(),
3424 cx,
3425 move |settings, _| settings.dock = Some(position),
3426 );
3427 }
3428
3429 fn size(&self, _: &Window, cx: &App) -> Pixels {
3430 self.width
3431 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3432 }
3433
3434 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3435 self.width = size;
3436 self.serialize(cx);
3437 cx.notify();
3438 }
3439
3440 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3441 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3442 }
3443
3444 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3445 Some("Git Panel")
3446 }
3447
3448 fn toggle_action(&self) -> Box<dyn Action> {
3449 Box::new(ToggleFocus)
3450 }
3451
3452 fn activation_priority(&self) -> u32 {
3453 2
3454 }
3455}
3456
3457impl PanelHeader for GitPanel {}
3458
3459struct GitPanelMessageTooltip {
3460 commit_tooltip: Option<Entity<CommitTooltip>>,
3461}
3462
3463impl GitPanelMessageTooltip {
3464 fn new(
3465 git_panel: Entity<GitPanel>,
3466 sha: SharedString,
3467 window: &mut Window,
3468 cx: &mut App,
3469 ) -> Entity<Self> {
3470 cx.new(|cx| {
3471 cx.spawn_in(window, |this, mut cx| async move {
3472 let details = git_panel
3473 .update(&mut cx, |git_panel, cx| {
3474 git_panel.load_commit_details(&sha, cx)
3475 })?
3476 .await?;
3477
3478 let commit_details = editor::commit_tooltip::CommitDetails {
3479 sha: details.sha.clone(),
3480 committer_name: details.committer_name.clone(),
3481 committer_email: details.committer_email.clone(),
3482 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3483 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3484 message: details.message.clone(),
3485 ..Default::default()
3486 }),
3487 };
3488
3489 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3490 this.commit_tooltip =
3491 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3492 cx.notify();
3493 })
3494 })
3495 .detach();
3496
3497 Self {
3498 commit_tooltip: None,
3499 }
3500 })
3501 }
3502}
3503
3504impl Render for GitPanelMessageTooltip {
3505 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3506 if let Some(commit_tooltip) = &self.commit_tooltip {
3507 commit_tooltip.clone().into_any_element()
3508 } else {
3509 gpui::Empty.into_any_element()
3510 }
3511 }
3512}
3513
3514#[derive(IntoElement, IntoComponent)]
3515#[component(scope = "Version Control")]
3516pub struct PanelRepoFooter {
3517 id: SharedString,
3518 active_repository: SharedString,
3519 branch: Option<Branch>,
3520 // Getting a GitPanel in previews will be difficult.
3521 //
3522 // For now just take an option here, and we won't bind handlers to buttons in previews.
3523 git_panel: Option<Entity<GitPanel>>,
3524}
3525
3526impl PanelRepoFooter {
3527 pub fn new(
3528 id: impl Into<SharedString>,
3529 active_repository: SharedString,
3530 branch: Option<Branch>,
3531 git_panel: Option<Entity<GitPanel>>,
3532 ) -> Self {
3533 Self {
3534 id: id.into(),
3535 active_repository,
3536 branch,
3537 git_panel,
3538 }
3539 }
3540
3541 pub fn new_preview(
3542 id: impl Into<SharedString>,
3543 active_repository: SharedString,
3544 branch: Option<Branch>,
3545 ) -> Self {
3546 Self {
3547 id: id.into(),
3548 active_repository,
3549 branch,
3550 git_panel: None,
3551 }
3552 }
3553}
3554
3555impl RenderOnce for PanelRepoFooter {
3556 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3557 let active_repo = self.active_repository.clone();
3558 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3559 .style(ButtonStyle::Transparent)
3560 .size(ButtonSize::None)
3561 .label_size(LabelSize::Small)
3562 .color(Color::Muted);
3563
3564 let project = self
3565 .git_panel
3566 .as_ref()
3567 .map(|panel| panel.read(cx).project.clone());
3568
3569 let repo = self
3570 .git_panel
3571 .as_ref()
3572 .and_then(|panel| panel.read(cx).active_repository.clone());
3573
3574 let single_repo = project
3575 .as_ref()
3576 .map(|project| {
3577 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3578 })
3579 .unwrap_or(true);
3580
3581 let repo_selector = PopoverMenu::new("repository-switcher")
3582 .menu({
3583 let project = project.clone();
3584 move |window, cx| {
3585 let project = project.clone()?;
3586 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3587 }
3588 })
3589 .trigger_with_tooltip(
3590 repo_selector_trigger.disabled(single_repo).truncate(true),
3591 Tooltip::text("Switch active repository"),
3592 )
3593 .attach(gpui::Corner::BottomLeft)
3594 .into_any_element();
3595
3596 let branch = self.branch.clone();
3597 let branch_name = branch
3598 .as_ref()
3599 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3600
3601 let branch_selector_button = Button::new("branch-selector", branch_name)
3602 .style(ButtonStyle::Transparent)
3603 .size(ButtonSize::None)
3604 .label_size(LabelSize::Small)
3605 .truncate(true)
3606 .tooltip(Tooltip::for_action_title(
3607 "Switch Branch",
3608 &zed_actions::git::Branch,
3609 ))
3610 .on_click(|_, window, cx| {
3611 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3612 });
3613
3614 let branch_selector = PopoverMenu::new("popover-button")
3615 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3616 .trigger_with_tooltip(
3617 branch_selector_button,
3618 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3619 )
3620 .anchor(Corner::TopLeft)
3621 .offset(gpui::Point {
3622 x: px(0.0),
3623 y: px(-2.0),
3624 });
3625
3626 let spinner = self
3627 .git_panel
3628 .as_ref()
3629 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3630
3631 h_flex()
3632 .w_full()
3633 .px_2()
3634 .h(px(36.))
3635 .items_center()
3636 .justify_between()
3637 .gap_1()
3638 .child(
3639 h_flex()
3640 .flex_1()
3641 .overflow_hidden()
3642 .items_center()
3643 .child(
3644 div().child(
3645 Icon::new(IconName::GitBranchSmall)
3646 .size(IconSize::Small)
3647 .color(if single_repo {
3648 Color::Disabled
3649 } else {
3650 Color::Muted
3651 }),
3652 ),
3653 )
3654 .child(repo_selector)
3655 .when_some(branch.clone(), |this, _| {
3656 this.child(
3657 div()
3658 .text_color(cx.theme().colors().text_muted)
3659 .text_sm()
3660 .child("/"),
3661 )
3662 })
3663 .child(branch_selector),
3664 )
3665 .child(
3666 h_flex()
3667 .gap_1()
3668 .flex_shrink_0()
3669 .children(spinner)
3670 .when_some(branch, |this, branch| {
3671 let mut focus_handle = None;
3672 if let Some(git_panel) = self.git_panel.as_ref() {
3673 if !git_panel.read(cx).can_push_and_pull(cx) {
3674 return this;
3675 }
3676 focus_handle = Some(git_panel.focus_handle(cx));
3677 }
3678
3679 this.children(render_remote_button(
3680 self.id.clone(),
3681 &branch,
3682 focus_handle,
3683 true,
3684 ))
3685 }),
3686 )
3687 }
3688}
3689
3690impl ComponentPreview for PanelRepoFooter {
3691 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3692 let unknown_upstream = None;
3693 let no_remote_upstream = Some(UpstreamTracking::Gone);
3694 let ahead_of_upstream = Some(
3695 UpstreamTrackingStatus {
3696 ahead: 2,
3697 behind: 0,
3698 }
3699 .into(),
3700 );
3701 let behind_upstream = Some(
3702 UpstreamTrackingStatus {
3703 ahead: 0,
3704 behind: 2,
3705 }
3706 .into(),
3707 );
3708 let ahead_and_behind_upstream = Some(
3709 UpstreamTrackingStatus {
3710 ahead: 3,
3711 behind: 1,
3712 }
3713 .into(),
3714 );
3715
3716 let not_ahead_or_behind_upstream = Some(
3717 UpstreamTrackingStatus {
3718 ahead: 0,
3719 behind: 0,
3720 }
3721 .into(),
3722 );
3723
3724 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3725 Branch {
3726 is_head: true,
3727 name: "some-branch".into(),
3728 upstream: upstream.map(|tracking| Upstream {
3729 ref_name: "origin/some-branch".into(),
3730 tracking,
3731 }),
3732 most_recent_commit: Some(CommitSummary {
3733 sha: "abc123".into(),
3734 subject: "Modify stuff".into(),
3735 commit_timestamp: 1710932954,
3736 has_parent: true,
3737 }),
3738 }
3739 }
3740
3741 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3742 Branch {
3743 is_head: true,
3744 name: branch_name.to_string().into(),
3745 upstream: upstream.map(|tracking| Upstream {
3746 ref_name: format!("zed/{}", branch_name).into(),
3747 tracking,
3748 }),
3749 most_recent_commit: Some(CommitSummary {
3750 sha: "abc123".into(),
3751 subject: "Modify stuff".into(),
3752 commit_timestamp: 1710932954,
3753 has_parent: true,
3754 }),
3755 }
3756 }
3757
3758 fn active_repository(id: usize) -> SharedString {
3759 format!("repo-{}", id).into()
3760 }
3761
3762 let example_width = px(340.);
3763
3764 v_flex()
3765 .gap_6()
3766 .w_full()
3767 .flex_none()
3768 .children(vec![example_group_with_title(
3769 "Action Button States",
3770 vec![
3771 single_example(
3772 "No Branch",
3773 div()
3774 .w(example_width)
3775 .overflow_hidden()
3776 .child(PanelRepoFooter::new_preview(
3777 "no-branch",
3778 active_repository(1).clone(),
3779 None,
3780 ))
3781 .into_any_element(),
3782 )
3783 .grow(),
3784 single_example(
3785 "Remote status unknown",
3786 div()
3787 .w(example_width)
3788 .overflow_hidden()
3789 .child(PanelRepoFooter::new_preview(
3790 "unknown-upstream",
3791 active_repository(2).clone(),
3792 Some(branch(unknown_upstream)),
3793 ))
3794 .into_any_element(),
3795 )
3796 .grow(),
3797 single_example(
3798 "No Remote Upstream",
3799 div()
3800 .w(example_width)
3801 .overflow_hidden()
3802 .child(PanelRepoFooter::new_preview(
3803 "no-remote-upstream",
3804 active_repository(3).clone(),
3805 Some(branch(no_remote_upstream)),
3806 ))
3807 .into_any_element(),
3808 )
3809 .grow(),
3810 single_example(
3811 "Not Ahead or Behind",
3812 div()
3813 .w(example_width)
3814 .overflow_hidden()
3815 .child(PanelRepoFooter::new_preview(
3816 "not-ahead-or-behind",
3817 active_repository(4).clone(),
3818 Some(branch(not_ahead_or_behind_upstream)),
3819 ))
3820 .into_any_element(),
3821 )
3822 .grow(),
3823 single_example(
3824 "Behind remote",
3825 div()
3826 .w(example_width)
3827 .overflow_hidden()
3828 .child(PanelRepoFooter::new_preview(
3829 "behind-remote",
3830 active_repository(5).clone(),
3831 Some(branch(behind_upstream)),
3832 ))
3833 .into_any_element(),
3834 )
3835 .grow(),
3836 single_example(
3837 "Ahead of remote",
3838 div()
3839 .w(example_width)
3840 .overflow_hidden()
3841 .child(PanelRepoFooter::new_preview(
3842 "ahead-of-remote",
3843 active_repository(6).clone(),
3844 Some(branch(ahead_of_upstream)),
3845 ))
3846 .into_any_element(),
3847 )
3848 .grow(),
3849 single_example(
3850 "Ahead and behind remote",
3851 div()
3852 .w(example_width)
3853 .overflow_hidden()
3854 .child(PanelRepoFooter::new_preview(
3855 "ahead-and-behind",
3856 active_repository(7).clone(),
3857 Some(branch(ahead_and_behind_upstream)),
3858 ))
3859 .into_any_element(),
3860 )
3861 .grow(),
3862 ],
3863 )
3864 .grow()
3865 .vertical()])
3866 .children(vec![example_group_with_title(
3867 "Labels",
3868 vec![
3869 single_example(
3870 "Short Branch & Repo",
3871 div()
3872 .w(example_width)
3873 .overflow_hidden()
3874 .child(PanelRepoFooter::new_preview(
3875 "short-branch",
3876 SharedString::from("zed"),
3877 Some(custom("main", behind_upstream)),
3878 ))
3879 .into_any_element(),
3880 )
3881 .grow(),
3882 single_example(
3883 "Long Branch",
3884 div()
3885 .w(example_width)
3886 .overflow_hidden()
3887 .child(PanelRepoFooter::new_preview(
3888 "long-branch",
3889 SharedString::from("zed"),
3890 Some(custom(
3891 "redesign-and-update-git-ui-list-entry-style",
3892 behind_upstream,
3893 )),
3894 ))
3895 .into_any_element(),
3896 )
3897 .grow(),
3898 single_example(
3899 "Long Repo",
3900 div()
3901 .w(example_width)
3902 .overflow_hidden()
3903 .child(PanelRepoFooter::new_preview(
3904 "long-repo",
3905 SharedString::from("zed-industries-community-examples"),
3906 Some(custom("gpui", ahead_of_upstream)),
3907 ))
3908 .into_any_element(),
3909 )
3910 .grow(),
3911 single_example(
3912 "Long Repo & Branch",
3913 div()
3914 .w(example_width)
3915 .overflow_hidden()
3916 .child(PanelRepoFooter::new_preview(
3917 "long-repo-and-branch",
3918 SharedString::from("zed-industries-community-examples"),
3919 Some(custom(
3920 "redesign-and-update-git-ui-list-entry-style",
3921 behind_upstream,
3922 )),
3923 ))
3924 .into_any_element(),
3925 )
3926 .grow(),
3927 single_example(
3928 "Uppercase Repo",
3929 div()
3930 .w(example_width)
3931 .overflow_hidden()
3932 .child(PanelRepoFooter::new_preview(
3933 "uppercase-repo",
3934 SharedString::from("LICENSES"),
3935 Some(custom("main", ahead_of_upstream)),
3936 ))
3937 .into_any_element(),
3938 )
3939 .grow(),
3940 single_example(
3941 "Uppercase Branch",
3942 div()
3943 .w(example_width)
3944 .overflow_hidden()
3945 .child(PanelRepoFooter::new_preview(
3946 "uppercase-branch",
3947 SharedString::from("zed"),
3948 Some(custom("update-README", behind_upstream)),
3949 ))
3950 .into_any_element(),
3951 )
3952 .grow(),
3953 ],
3954 )
3955 .grow()
3956 .vertical()])
3957 .into_any_element()
3958 }
3959}
3960
3961#[cfg(test)]
3962mod tests {
3963 use git::status::StatusCode;
3964 use gpui::TestAppContext;
3965 use project::{FakeFs, WorktreeSettings};
3966 use serde_json::json;
3967 use settings::SettingsStore;
3968 use theme::LoadThemes;
3969 use util::path;
3970
3971 use super::*;
3972
3973 fn init_test(cx: &mut gpui::TestAppContext) {
3974 if std::env::var("RUST_LOG").is_ok() {
3975 env_logger::try_init().ok();
3976 }
3977
3978 cx.update(|cx| {
3979 let settings_store = SettingsStore::test(cx);
3980 cx.set_global(settings_store);
3981 WorktreeSettings::register(cx);
3982 workspace::init_settings(cx);
3983 theme::init(LoadThemes::JustBase, cx);
3984 language::init(cx);
3985 editor::init(cx);
3986 Project::init_settings(cx);
3987 crate::init(cx);
3988 });
3989 }
3990
3991 #[gpui::test]
3992 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3993 init_test(cx);
3994 let fs = FakeFs::new(cx.background_executor.clone());
3995 fs.insert_tree(
3996 "/root",
3997 json!({
3998 "zed": {
3999 ".git": {},
4000 "crates": {
4001 "gpui": {
4002 "gpui.rs": "fn main() {}"
4003 },
4004 "util": {
4005 "util.rs": "fn do_it() {}"
4006 }
4007 }
4008 },
4009 }),
4010 )
4011 .await;
4012
4013 fs.set_status_for_repo_via_git_operation(
4014 Path::new(path!("/root/zed/.git")),
4015 &[
4016 (
4017 Path::new("crates/gpui/gpui.rs"),
4018 StatusCode::Modified.worktree(),
4019 ),
4020 (
4021 Path::new("crates/util/util.rs"),
4022 StatusCode::Modified.worktree(),
4023 ),
4024 ],
4025 );
4026
4027 let project =
4028 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
4029 let (workspace, cx) =
4030 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4031
4032 cx.read(|cx| {
4033 project
4034 .read(cx)
4035 .worktrees(cx)
4036 .nth(0)
4037 .unwrap()
4038 .read(cx)
4039 .as_local()
4040 .unwrap()
4041 .scan_complete()
4042 })
4043 .await;
4044
4045 cx.executor().run_until_parked();
4046
4047 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
4048 let panel = cx.new_window_entity(|window, cx| {
4049 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
4050 });
4051
4052 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4053 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4054 });
4055 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4056 handle.await;
4057
4058 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4059 pretty_assertions::assert_eq!(
4060 entries,
4061 [
4062 GitListEntry::Header(GitHeaderEntry {
4063 header: Section::Tracked
4064 }),
4065 GitListEntry::GitStatusEntry(GitStatusEntry {
4066 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4067 repo_path: "crates/gpui/gpui.rs".into(),
4068 worktree_path: Path::new("gpui.rs").into(),
4069 status: StatusCode::Modified.worktree(),
4070 staging: StageStatus::Unstaged,
4071 }),
4072 GitListEntry::GitStatusEntry(GitStatusEntry {
4073 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4074 repo_path: "crates/util/util.rs".into(),
4075 worktree_path: Path::new("../util/util.rs").into(),
4076 status: StatusCode::Modified.worktree(),
4077 staging: StageStatus::Unstaged,
4078 },),
4079 ],
4080 );
4081
4082 cx.update_window_entity(&panel, |panel, window, cx| {
4083 panel.select_last(&Default::default(), window, cx);
4084 assert_eq!(panel.selected_entry, Some(2));
4085 panel.open_diff(&Default::default(), window, cx);
4086 });
4087 cx.run_until_parked();
4088
4089 let worktree_roots = workspace.update(cx, |workspace, cx| {
4090 workspace
4091 .worktrees(cx)
4092 .map(|worktree| worktree.read(cx).abs_path())
4093 .collect::<Vec<_>>()
4094 });
4095 pretty_assertions::assert_eq!(
4096 worktree_roots,
4097 vec![
4098 Path::new(path!("/root/zed/crates/gpui")).into(),
4099 Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4100 ]
4101 );
4102
4103 let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4104 let git_store = project.git_store().read(cx);
4105 // The repo that comes from the single-file worktree can't be selected through the UI.
4106 let filtered_entries = filtered_repository_entries(git_store, cx)
4107 .iter()
4108 .map(|repo| repo.read(cx).worktree_abs_path.clone())
4109 .collect::<Vec<_>>();
4110 assert_eq!(
4111 filtered_entries,
4112 [Path::new(path!("/root/zed/crates/gpui")).into()]
4113 );
4114 // But we can select it artificially here.
4115 git_store
4116 .all_repositories()
4117 .into_iter()
4118 .find(|repo| {
4119 &*repo.read(cx).worktree_abs_path
4120 == Path::new(path!("/root/zed/crates/util/util.rs"))
4121 })
4122 .unwrap()
4123 });
4124
4125 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4126 repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4127 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4128 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4129 });
4130 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4131 handle.await;
4132 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4133 pretty_assertions::assert_eq!(
4134 entries,
4135 [
4136 GitListEntry::Header(GitHeaderEntry {
4137 header: Section::Tracked
4138 }),
4139 GitListEntry::GitStatusEntry(GitStatusEntry {
4140 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4141 repo_path: "crates/gpui/gpui.rs".into(),
4142 worktree_path: Path::new("../../gpui/gpui.rs").into(),
4143 status: StatusCode::Modified.worktree(),
4144 staging: StageStatus::Unstaged,
4145 }),
4146 GitListEntry::GitStatusEntry(GitStatusEntry {
4147 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4148 repo_path: "crates/util/util.rs".into(),
4149 worktree_path: Path::new("util.rs").into(),
4150 status: StatusCode::Modified.worktree(),
4151 staging: StageStatus::Unstaged,
4152 },),
4153 ],
4154 );
4155 }
4156}