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