1use crate::askpass_modal::AskPassModal;
2use crate::commit_modal::CommitModal;
3use crate::git_panel_settings::StatusStyle;
4use crate::project_diff::Diff;
5use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
6use crate::repository_selector::filtered_repository_entries;
7use crate::{branch_picker, render_remote_button};
8use crate::{
9 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
10};
11use crate::{picker_prompt, project_diff, ProjectDiff};
12use anyhow::Result;
13use askpass::AskPassDelegate;
14use db::kvp::KEY_VALUE_STORE;
15use editor::commit_tooltip::CommitTooltip;
16
17use editor::{
18 scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
19 ShowScrollbar,
20};
21use futures::StreamExt as _;
22use git::repository::{
23 Branch, CommitDetails, CommitSummary, DiffType, PushOptions, Remote, RemoteCommandOutput,
24 ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,
25};
26use git::status::StageStatus;
27use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
28use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
29use gpui::{
30 actions, anchored, deferred, percentage, uniform_list, Action, Animation, AnimationExt as _,
31 ClickEvent, Corner, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,
32 ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers, ModifiersChangedEvent,
33 MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Stateful, Subscription, Task,
34 Transformation, UniformListScrollHandle, WeakEntity,
35};
36use itertools::Itertools;
37use language::{Buffer, File};
38use language_model::{
39 LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
40};
41use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
42use multi_buffer::ExcerptInfo;
43use panel::{
44 panel_editor_container, panel_editor_style, panel_filled_button, panel_icon_button, PanelHeader,
45};
46use project::{
47 git::{GitEvent, Repository},
48 Fs, Project, ProjectPath,
49};
50use serde::{Deserialize, Serialize};
51use settings::Settings as _;
52use std::cell::RefCell;
53use std::future::Future;
54use std::path::{Path, PathBuf};
55use std::rc::Rc;
56use std::{collections::HashSet, sync::Arc, time::Duration, usize};
57use strum::{IntoEnumIterator, VariantNames};
58use time::OffsetDateTime;
59use ui::{
60 prelude::*, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState,
61 Tooltip,
62};
63use util::{maybe, post_inc, ResultExt, TryFutureExt};
64use workspace::{AppState, OpenOptions, OpenVisible};
65
66use workspace::{
67 dock::{DockPosition, Panel, PanelEvent},
68 notifications::{DetachAndPromptErr, NotificationId},
69 Toast, Workspace,
70};
71
72actions!(
73 git_panel,
74 [
75 Close,
76 ToggleFocus,
77 OpenMenu,
78 FocusEditor,
79 FocusChanges,
80 ToggleFillCoAuthors,
81 GenerateCommitMessage
82 ]
83);
84
85fn prompt<T>(
86 msg: &str,
87 detail: Option<&str>,
88 window: &mut Window,
89 cx: &mut App,
90) -> Task<anyhow::Result<T>>
91where
92 T: IntoEnumIterator + VariantNames + 'static,
93{
94 let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
95 cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
96}
97
98#[derive(strum::EnumIter, strum::VariantNames)]
99#[strum(serialize_all = "title_case")]
100enum TrashCancel {
101 Trash,
102 Cancel,
103}
104
105fn git_panel_context_menu(
106 focus_handle: Option<FocusHandle>,
107 window: &mut Window,
108 cx: &mut App,
109) -> Entity<ContextMenu> {
110 ContextMenu::build(window, cx, |context_menu, _, _| {
111 context_menu
112 .when_some(focus_handle, |el, focus_handle| el.context(focus_handle))
113 .action("Stage All", StageAll.boxed_clone())
114 .action("Unstage All", UnstageAll.boxed_clone())
115 .separator()
116 .action("Open Diff", project_diff::Diff.boxed_clone())
117 .separator()
118 .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
119 .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
120 })
121}
122
123const GIT_PANEL_KEY: &str = "GitPanel";
124
125const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
126
127pub fn init(cx: &mut App) {
128 cx.observe_new(
129 |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
130 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
131 workspace.toggle_panel_focus::<GitPanel>(window, cx);
132 });
133 workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
134 CommitModal::toggle(workspace, window, cx)
135 });
136 },
137 )
138 .detach();
139}
140
141#[derive(Debug, Clone)]
142pub enum Event {
143 Focus,
144}
145
146#[derive(Serialize, Deserialize)]
147struct SerializedGitPanel {
148 width: Option<Pixels>,
149}
150
151#[derive(Debug, PartialEq, Eq, Clone, Copy)]
152enum Section {
153 Conflict,
154 Tracked,
155 New,
156}
157
158#[derive(Debug, PartialEq, Eq, Clone)]
159struct GitHeaderEntry {
160 header: Section,
161}
162
163impl GitHeaderEntry {
164 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
165 let this = &self.header;
166 let status = status_entry.status;
167 match this {
168 Section::Conflict => repo.has_conflict(&status_entry.repo_path),
169 Section::Tracked => !status.is_created(),
170 Section::New => status.is_created(),
171 }
172 }
173 pub fn title(&self) -> &'static str {
174 match self.header {
175 Section::Conflict => "Conflicts",
176 Section::Tracked => "Tracked",
177 Section::New => "Untracked",
178 }
179 }
180}
181
182#[derive(Debug, PartialEq, Eq, Clone)]
183enum GitListEntry {
184 GitStatusEntry(GitStatusEntry),
185 Header(GitHeaderEntry),
186}
187
188impl GitListEntry {
189 fn status_entry(&self) -> Option<&GitStatusEntry> {
190 match self {
191 GitListEntry::GitStatusEntry(entry) => Some(entry),
192 _ => None,
193 }
194 }
195}
196
197#[derive(Debug, PartialEq, Eq, Clone)]
198pub struct GitStatusEntry {
199 pub(crate) repo_path: RepoPath,
200 pub(crate) worktree_path: Arc<Path>,
201 pub(crate) abs_path: PathBuf,
202 pub(crate) status: FileStatus,
203 pub(crate) staging: StageStatus,
204}
205
206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207enum TargetStatus {
208 Staged,
209 Unstaged,
210 Reverted,
211 Unchanged,
212}
213
214struct PendingOperation {
215 finished: bool,
216 target_status: TargetStatus,
217 entries: Vec<GitStatusEntry>,
218 op_id: usize,
219}
220
221type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
222
223pub struct GitPanel {
224 remote_operation_id: u32,
225 pending_remote_operations: RemoteOperations,
226 pub(crate) active_repository: Option<Entity<Repository>>,
227 pub(crate) commit_editor: Entity<Editor>,
228 conflicted_count: usize,
229 conflicted_staged_count: usize,
230 current_modifiers: Modifiers,
231 add_coauthors: bool,
232 generate_commit_message_task: Option<Task<Option<()>>>,
233 entries: Vec<GitListEntry>,
234 single_staged_entry: Option<GitStatusEntry>,
235 single_tracked_entry: Option<GitStatusEntry>,
236 focus_handle: FocusHandle,
237 fs: Arc<dyn Fs>,
238 hide_scrollbar_task: Option<Task<()>>,
239 new_count: usize,
240 entry_count: usize,
241 new_staged_count: usize,
242 pending: Vec<PendingOperation>,
243 pending_commit: Option<Task<()>>,
244 pending_serialization: Task<Option<()>>,
245 pub(crate) project: Entity<Project>,
246 scroll_handle: UniformListScrollHandle,
247 scrollbar_state: ScrollbarState,
248 selected_entry: Option<usize>,
249 marked_entries: Vec<usize>,
250 show_scrollbar: bool,
251 tracked_count: usize,
252 tracked_staged_count: usize,
253 update_visible_entries_task: Task<()>,
254 width: Option<Pixels>,
255 workspace: WeakEntity<Workspace>,
256 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
257 modal_open: bool,
258}
259
260struct RemoteOperationGuard {
261 id: u32,
262 pending_remote_operations: RemoteOperations,
263}
264
265impl Drop for RemoteOperationGuard {
266 fn drop(&mut self) {
267 self.pending_remote_operations.borrow_mut().remove(&self.id);
268 }
269}
270
271pub(crate) fn commit_message_editor(
272 commit_message_buffer: Entity<Buffer>,
273 placeholder: Option<&str>,
274 project: Entity<Project>,
275 in_panel: bool,
276 window: &mut Window,
277 cx: &mut Context<'_, Editor>,
278) -> Editor {
279 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
280 let max_lines = if in_panel { 6 } else { 18 };
281 let mut commit_editor = Editor::new(
282 EditorMode::AutoHeight { max_lines },
283 buffer,
284 None,
285 false,
286 window,
287 cx,
288 );
289 commit_editor.set_collaboration_hub(Box::new(project));
290 commit_editor.set_use_autoclose(false);
291 commit_editor.set_show_gutter(false, cx);
292 commit_editor.set_show_wrap_guides(false, cx);
293 commit_editor.set_show_indent_guides(false, cx);
294 let placeholder = placeholder.unwrap_or("Enter commit message");
295 commit_editor.set_placeholder_text(placeholder, cx);
296 commit_editor
297}
298
299impl GitPanel {
300 pub fn new(
301 workspace: Entity<Workspace>,
302 project: Entity<Project>,
303 app_state: Arc<AppState>,
304 window: &mut Window,
305 cx: &mut Context<Self>,
306 ) -> Self {
307 let fs = app_state.fs.clone();
308 let git_store = project.read(cx).git_store().clone();
309 let active_repository = project.read(cx).active_repository(cx);
310 let workspace = workspace.downgrade();
311
312 let focus_handle = cx.focus_handle();
313 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
314 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
315 this.hide_scrollbar(window, cx);
316 })
317 .detach();
318
319 // just to let us render a placeholder editor.
320 // Once the active git repo is set, this buffer will be replaced.
321 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
322 let commit_editor = cx.new(|cx| {
323 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
324 });
325
326 commit_editor.update(cx, |editor, cx| {
327 editor.clear(window, cx);
328 });
329
330 let scroll_handle = UniformListScrollHandle::new();
331
332 cx.subscribe_in(
333 &git_store,
334 window,
335 move |this, git_store, event, window, cx| match event {
336 GitEvent::FileSystemUpdated => {
337 this.schedule_update(false, window, cx);
338 }
339 GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
340 this.active_repository = git_store.read(cx).active_repository();
341 this.schedule_update(true, window, cx);
342 }
343 GitEvent::IndexWriteError(error) => {
344 this.workspace
345 .update(cx, |workspace, cx| {
346 workspace.show_error(error, cx);
347 })
348 .ok();
349 }
350 },
351 )
352 .detach();
353
354 let scrollbar_state =
355 ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
356
357 let mut git_panel = Self {
358 pending_remote_operations: Default::default(),
359 remote_operation_id: 0,
360 active_repository,
361 commit_editor,
362 conflicted_count: 0,
363 conflicted_staged_count: 0,
364 current_modifiers: window.modifiers(),
365 add_coauthors: true,
366 generate_commit_message_task: None,
367 entries: Vec::new(),
368 focus_handle: cx.focus_handle(),
369 fs,
370 hide_scrollbar_task: None,
371 new_count: 0,
372 new_staged_count: 0,
373 pending: Vec::new(),
374 pending_commit: None,
375 pending_serialization: Task::ready(None),
376 single_staged_entry: None,
377 single_tracked_entry: None,
378 project,
379 scroll_handle,
380 scrollbar_state,
381 selected_entry: None,
382 marked_entries: Vec::new(),
383 show_scrollbar: false,
384 tracked_count: 0,
385 tracked_staged_count: 0,
386 update_visible_entries_task: Task::ready(()),
387 width: None,
388 context_menu: None,
389 workspace,
390 modal_open: false,
391 entry_count: 0,
392 };
393 git_panel.schedule_update(false, window, cx);
394 git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
395 git_panel
396 }
397
398 pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
399 fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
400 where
401 F: Fn(usize) -> std::cmp::Ordering,
402 {
403 while low < high {
404 let mid = low + (high - low) / 2;
405 match is_target(mid) {
406 std::cmp::Ordering::Equal => return Some(mid),
407 std::cmp::Ordering::Less => low = mid + 1,
408 std::cmp::Ordering::Greater => high = mid,
409 }
410 }
411 None
412 }
413 if self.conflicted_count > 0 {
414 let conflicted_start = 1;
415 if let Some(ix) = binary_search(
416 conflicted_start,
417 conflicted_start + self.conflicted_count,
418 |ix| {
419 self.entries[ix]
420 .status_entry()
421 .unwrap()
422 .repo_path
423 .cmp(&path)
424 },
425 ) {
426 return Some(ix);
427 }
428 }
429 if self.tracked_count > 0 {
430 let tracked_start = if self.conflicted_count > 0 {
431 1 + self.conflicted_count
432 } else {
433 0
434 } + 1;
435 if let Some(ix) =
436 binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
437 self.entries[ix]
438 .status_entry()
439 .unwrap()
440 .repo_path
441 .cmp(&path)
442 })
443 {
444 return Some(ix);
445 }
446 }
447 if self.new_count > 0 {
448 let untracked_start = if self.conflicted_count > 0 {
449 1 + self.conflicted_count
450 } else {
451 0
452 } + if self.tracked_count > 0 {
453 1 + self.tracked_count
454 } else {
455 0
456 } + 1;
457 if let Some(ix) =
458 binary_search(untracked_start, untracked_start + self.new_count, |ix| {
459 self.entries[ix]
460 .status_entry()
461 .unwrap()
462 .repo_path
463 .cmp(&path)
464 })
465 {
466 return Some(ix);
467 }
468 }
469 None
470 }
471
472 pub fn select_entry_by_path(
473 &mut self,
474 path: ProjectPath,
475 _: &mut Window,
476 cx: &mut Context<Self>,
477 ) {
478 let Some(git_repo) = self.active_repository.as_ref() else {
479 return;
480 };
481 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
482 return;
483 };
484 let Some(ix) = self.entry_by_path(&repo_path) else {
485 return;
486 };
487 self.selected_entry = Some(ix);
488 cx.notify();
489 }
490
491 fn start_remote_operation(&mut self) -> RemoteOperationGuard {
492 let id = post_inc(&mut self.remote_operation_id);
493 self.pending_remote_operations.borrow_mut().insert(id);
494
495 RemoteOperationGuard {
496 id,
497 pending_remote_operations: self.pending_remote_operations.clone(),
498 }
499 }
500
501 fn serialize(&mut self, cx: &mut Context<Self>) {
502 let width = self.width;
503 self.pending_serialization = cx.background_spawn(
504 async move {
505 KEY_VALUE_STORE
506 .write_kvp(
507 GIT_PANEL_KEY.into(),
508 serde_json::to_string(&SerializedGitPanel { width })?,
509 )
510 .await?;
511 anyhow::Ok(())
512 }
513 .log_err(),
514 );
515 }
516
517 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
518 self.modal_open = open;
519 cx.notify();
520 }
521
522 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
523 let mut dispatch_context = KeyContext::new_with_defaults();
524 dispatch_context.add("GitPanel");
525
526 if self.is_focused(window, cx) {
527 dispatch_context.add("menu");
528 dispatch_context.add("ChangesList");
529 }
530
531 if self.commit_editor.read(cx).is_focused(window) {
532 dispatch_context.add("CommitEditor");
533 }
534
535 dispatch_context
536 }
537
538 fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
539 window
540 .focused(cx)
541 .map_or(false, |focused| self.focus_handle == focused)
542 }
543
544 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
545 cx.emit(PanelEvent::Close);
546 }
547
548 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
549 if !self.focus_handle.contains_focused(window, cx) {
550 cx.emit(Event::Focus);
551 }
552 }
553
554 fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
555 GitPanelSettings::get_global(cx)
556 .scrollbar
557 .show
558 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
559 }
560
561 fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
562 let show = self.show_scrollbar(cx);
563 match show {
564 ShowScrollbar::Auto => true,
565 ShowScrollbar::System => true,
566 ShowScrollbar::Always => true,
567 ShowScrollbar::Never => false,
568 }
569 }
570
571 fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
572 let show = self.show_scrollbar(cx);
573 match show {
574 ShowScrollbar::Auto => true,
575 ShowScrollbar::System => cx
576 .try_global::<ScrollbarAutoHide>()
577 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
578 ShowScrollbar::Always => false,
579 ShowScrollbar::Never => true,
580 }
581 }
582
583 fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
584 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
585 if !self.should_autohide_scrollbar(cx) {
586 return;
587 }
588 self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
589 cx.background_executor()
590 .timer(SCROLLBAR_SHOW_INTERVAL)
591 .await;
592 panel
593 .update(&mut cx, |panel, cx| {
594 panel.show_scrollbar = false;
595 cx.notify();
596 })
597 .log_err();
598 }))
599 }
600
601 fn handle_modifiers_changed(
602 &mut self,
603 event: &ModifiersChangedEvent,
604 _: &mut Window,
605 cx: &mut Context<Self>,
606 ) {
607 self.current_modifiers = event.modifiers;
608 cx.notify();
609 }
610
611 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
612 if let Some(selected_entry) = self.selected_entry {
613 self.scroll_handle
614 .scroll_to_item(selected_entry, ScrollStrategy::Center);
615 }
616
617 cx.notify();
618 }
619
620 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
621 if !self.entries.is_empty() {
622 self.selected_entry = Some(1);
623 self.scroll_to_selected_entry(cx);
624 }
625 }
626
627 fn select_previous(
628 &mut self,
629 _: &SelectPrevious,
630 _window: &mut Window,
631 cx: &mut Context<Self>,
632 ) {
633 let item_count = self.entries.len();
634 if item_count == 0 {
635 return;
636 }
637
638 if let Some(selected_entry) = self.selected_entry {
639 let new_selected_entry = if selected_entry > 0 {
640 selected_entry - 1
641 } else {
642 selected_entry
643 };
644
645 if matches!(
646 self.entries.get(new_selected_entry),
647 Some(GitListEntry::Header(..))
648 ) {
649 if new_selected_entry > 0 {
650 self.selected_entry = Some(new_selected_entry - 1)
651 }
652 } else {
653 self.selected_entry = Some(new_selected_entry);
654 }
655
656 self.scroll_to_selected_entry(cx);
657 }
658
659 cx.notify();
660 }
661
662 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
663 let item_count = self.entries.len();
664 if item_count == 0 {
665 return;
666 }
667
668 if let Some(selected_entry) = self.selected_entry {
669 let new_selected_entry = if selected_entry < item_count - 1 {
670 selected_entry + 1
671 } else {
672 selected_entry
673 };
674 if matches!(
675 self.entries.get(new_selected_entry),
676 Some(GitListEntry::Header(..))
677 ) {
678 self.selected_entry = Some(new_selected_entry + 1);
679 } else {
680 self.selected_entry = Some(new_selected_entry);
681 }
682
683 self.scroll_to_selected_entry(cx);
684 }
685
686 cx.notify();
687 }
688
689 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
690 if self.entries.last().is_some() {
691 self.selected_entry = Some(self.entries.len() - 1);
692 self.scroll_to_selected_entry(cx);
693 }
694 }
695
696 pub(crate) fn editor_focus_handle(&self, cx: &mut Context<Self>) -> FocusHandle {
697 self.commit_editor.focus_handle(cx).clone()
698 }
699
700 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
701 self.commit_editor.update(cx, |editor, cx| {
702 window.focus(&editor.focus_handle(cx));
703 });
704 cx.notify();
705 }
706
707 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
708 let have_entries = self
709 .active_repository
710 .as_ref()
711 .map_or(false, |active_repository| {
712 active_repository.read(cx).entry_count() > 0
713 });
714 if have_entries && self.selected_entry.is_none() {
715 self.selected_entry = Some(1);
716 self.scroll_to_selected_entry(cx);
717 cx.notify();
718 }
719 }
720
721 fn focus_changes_list(
722 &mut self,
723 _: &FocusChanges,
724 window: &mut Window,
725 cx: &mut Context<Self>,
726 ) {
727 self.select_first_entry_if_none(cx);
728
729 cx.focus_self(window);
730 cx.notify();
731 }
732
733 fn get_selected_entry(&self) -> Option<&GitListEntry> {
734 self.selected_entry.and_then(|i| self.entries.get(i))
735 }
736
737 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
738 maybe!({
739 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
740 let workspace = self.workspace.upgrade()?;
741 let git_repo = self.active_repository.as_ref()?;
742
743 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
744 if let Some(project_path) = project_diff.read(cx).active_path(cx) {
745 if Some(&entry.repo_path)
746 == git_repo
747 .read(cx)
748 .project_path_to_repo_path(&project_path)
749 .as_ref()
750 {
751 project_diff.focus_handle(cx).focus(window);
752 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 pub(crate) fn render_generate_commit_message_button(
2312 &self,
2313 cx: &Context<Self>,
2314 ) -> Option<AnyElement> {
2315 current_language_model(cx).is_some().then(|| {
2316 if self.generate_commit_message_task.is_some() {
2317 return h_flex()
2318 .gap_1()
2319 .child(
2320 Icon::new(IconName::ArrowCircle)
2321 .size(IconSize::XSmall)
2322 .color(Color::Info)
2323 .with_animation(
2324 "arrow-circle",
2325 Animation::new(Duration::from_secs(2)).repeat(),
2326 |icon, delta| {
2327 icon.transform(Transformation::rotate(percentage(delta)))
2328 },
2329 ),
2330 )
2331 .child(
2332 Label::new("Generating Commit...")
2333 .size(LabelSize::Small)
2334 .color(Color::Muted),
2335 )
2336 .into_any_element();
2337 }
2338
2339 let can_commit = self.can_commit();
2340 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2341 IconButton::new("generate-commit-message", IconName::AiEdit)
2342 .shape(ui::IconButtonShape::Square)
2343 .icon_color(Color::Muted)
2344 .tooltip(move |window, cx| {
2345 if can_commit {
2346 Tooltip::for_action_in(
2347 "Generate Commit Message",
2348 &git::GenerateCommitMessage,
2349 &editor_focus_handle,
2350 window,
2351 cx,
2352 )
2353 } else {
2354 Tooltip::simple(
2355 "You must have either staged changes or tracked files to generate a commit message",
2356 cx,
2357 )
2358 }
2359 })
2360 .disabled(!can_commit)
2361 .on_click(cx.listener(move |this, _event, _window, cx| {
2362 this.generate_commit_message(cx);
2363 }))
2364 .into_any_element()
2365 })
2366 }
2367
2368 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2369 let potential_co_authors = self.potential_co_authors(cx);
2370 if potential_co_authors.is_empty() {
2371 None
2372 } else {
2373 Some(
2374 IconButton::new("co-authors", IconName::Person)
2375 .shape(ui::IconButtonShape::Square)
2376 .icon_color(Color::Disabled)
2377 .selected_icon_color(Color::Selected)
2378 .toggle_state(self.add_coauthors)
2379 .tooltip(move |_, cx| {
2380 let title = format!(
2381 "Add co-authored-by:{}{}",
2382 if potential_co_authors.len() == 1 {
2383 ""
2384 } else {
2385 "\n"
2386 },
2387 potential_co_authors
2388 .iter()
2389 .map(|(name, email)| format!(" {} <{}>", name, email))
2390 .join("\n")
2391 );
2392 Tooltip::simple(title, cx)
2393 })
2394 .on_click(cx.listener(|this, _, _, cx| {
2395 this.add_coauthors = !this.add_coauthors;
2396 cx.notify();
2397 }))
2398 .into_any_element(),
2399 )
2400 }
2401 }
2402
2403 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2404 if self.has_unstaged_conflicts() {
2405 (false, "You must resolve conflicts before committing")
2406 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2407 (
2408 false,
2409 "You must have either staged changes or tracked files to commit",
2410 )
2411 } else if self.pending_commit.is_some() {
2412 (false, "Commit in progress")
2413 } else if self.custom_or_suggested_commit_message(cx).is_none() {
2414 (false, "No commit message")
2415 } else if !self.has_write_access(cx) {
2416 (false, "You do not have write access to this project")
2417 } else {
2418 (true, self.commit_button_title())
2419 }
2420 }
2421
2422 pub fn commit_button_title(&self) -> &'static str {
2423 if self.has_staged_changes() {
2424 "Commit"
2425 } else {
2426 "Commit Tracked"
2427 }
2428 }
2429
2430 fn expand_commit_editor(
2431 &mut self,
2432 _: &git::ExpandCommitEditor,
2433 window: &mut Window,
2434 cx: &mut Context<Self>,
2435 ) {
2436 let workspace = self.workspace.clone();
2437 window.defer(cx, move |window, cx| {
2438 workspace
2439 .update(cx, |workspace, cx| {
2440 CommitModal::toggle(workspace, window, cx)
2441 })
2442 .ok();
2443 })
2444 }
2445
2446 fn render_panel_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2447 let text;
2448 let action;
2449 let tooltip;
2450 if self.total_staged_count() == self.entry_count {
2451 text = "Unstage All";
2452 action = git::UnstageAll.boxed_clone();
2453 tooltip = "git reset";
2454 } else {
2455 text = "Stage All";
2456 action = git::StageAll.boxed_clone();
2457 tooltip = "git add --all ."
2458 }
2459
2460 self.panel_header_container(window, cx)
2461 .child(
2462 Button::new("diff", "Open Diff")
2463 .tooltip(Tooltip::for_action_title_in(
2464 "Open diff",
2465 &Diff,
2466 &self.focus_handle,
2467 ))
2468 .on_click(|_, _, cx| {
2469 cx.defer(|cx| {
2470 cx.dispatch_action(&Diff);
2471 })
2472 }),
2473 )
2474 .child(div().flex_grow()) // spacer
2475 .child(
2476 Button::new("stage-unstage-all", text)
2477 .tooltip(Tooltip::for_action_title_in(
2478 tooltip,
2479 action.as_ref(),
2480 &self.focus_handle,
2481 ))
2482 .on_click(move |_, _, cx| {
2483 let action = action.boxed_clone();
2484 cx.defer(move |cx| {
2485 cx.dispatch_action(action.as_ref());
2486 })
2487 }),
2488 )
2489 }
2490
2491 pub fn render_footer(
2492 &self,
2493 window: &mut Window,
2494 cx: &mut Context<Self>,
2495 ) -> Option<impl IntoElement> {
2496 let active_repository = self.active_repository.clone()?;
2497 let (can_commit, tooltip) = self.configure_commit_button(cx);
2498 let project = self.project.clone().read(cx);
2499 let panel_editor_style = panel_editor_style(true, window, cx);
2500
2501 let enable_coauthors = self.render_co_authors(cx);
2502 let title = self.commit_button_title();
2503
2504 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2505 let commit_tooltip_focus_handle = editor_focus_handle.clone();
2506 let expand_tooltip_focus_handle = editor_focus_handle.clone();
2507
2508 let branch = active_repository.read(cx).current_branch().cloned();
2509
2510 let footer_size = px(32.);
2511 let gap = px(8.0);
2512 let max_height = window.line_height() * 5. + gap + footer_size;
2513
2514 let git_panel = cx.entity().clone();
2515 let display_name = SharedString::from(Arc::from(
2516 active_repository
2517 .read(cx)
2518 .display_name(project, cx)
2519 .trim_end_matches("/"),
2520 ));
2521
2522 let footer = v_flex()
2523 .child(PanelRepoFooter::new(
2524 "footer-button",
2525 display_name,
2526 branch,
2527 Some(git_panel),
2528 ))
2529 .child(
2530 panel_editor_container(window, cx)
2531 .id("commit-editor-container")
2532 .relative()
2533 .h(max_height)
2534 .w_full()
2535 .border_t_1()
2536 .border_color(cx.theme().colors().border_variant)
2537 .bg(cx.theme().colors().editor_background)
2538 .cursor_text()
2539 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2540 window.focus(&this.commit_editor.focus_handle(cx));
2541 }))
2542 .child(
2543 h_flex()
2544 .id("commit-footer")
2545 .absolute()
2546 .bottom_0()
2547 .left_0()
2548 .w_full()
2549 .px_2()
2550 .h(footer_size)
2551 .flex_none()
2552 .justify_between()
2553 .child(
2554 self.render_generate_commit_message_button(cx)
2555 .unwrap_or_else(|| div().into_any_element()),
2556 )
2557 .child(
2558 h_flex().gap_0p5().children(enable_coauthors).child(
2559 panel_filled_button(title)
2560 .tooltip(move |window, cx| {
2561 if can_commit {
2562 Tooltip::for_action_in(
2563 tooltip,
2564 &Commit,
2565 &commit_tooltip_focus_handle,
2566 window,
2567 cx,
2568 )
2569 } else {
2570 Tooltip::simple(tooltip, cx)
2571 }
2572 })
2573 .disabled(!can_commit || self.modal_open)
2574 .on_click({
2575 cx.listener(move |this, _: &ClickEvent, window, cx| {
2576 this.commit_changes(window, cx)
2577 })
2578 }),
2579 ),
2580 ),
2581 )
2582 .child(
2583 div()
2584 .pr_2p5()
2585 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2586 )
2587 .child(
2588 h_flex()
2589 .absolute()
2590 .top_2()
2591 .right_2()
2592 .opacity(0.5)
2593 .hover(|this| this.opacity(1.0))
2594 .child(
2595 panel_icon_button("expand-commit-editor", IconName::Maximize)
2596 .icon_size(IconSize::Small)
2597 .size(ui::ButtonSize::Default)
2598 .tooltip(move |window, cx| {
2599 Tooltip::for_action_in(
2600 "Open Commit Modal",
2601 &git::ExpandCommitEditor,
2602 &expand_tooltip_focus_handle,
2603 window,
2604 cx,
2605 )
2606 })
2607 .on_click(cx.listener({
2608 move |_, _, window, cx| {
2609 window.dispatch_action(
2610 git::ExpandCommitEditor.boxed_clone(),
2611 cx,
2612 )
2613 }
2614 })),
2615 ),
2616 ),
2617 );
2618
2619 Some(footer)
2620 }
2621
2622 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2623 let active_repository = self.active_repository.as_ref()?;
2624 let branch = active_repository.read(cx).current_branch()?;
2625 let commit = branch.most_recent_commit.as_ref()?.clone();
2626
2627 let this = cx.entity();
2628 Some(
2629 h_flex()
2630 .items_center()
2631 .py_2()
2632 .px(px(8.))
2633 // .bg(cx.theme().colors().background)
2634 // .border_t_1()
2635 .border_color(cx.theme().colors().border)
2636 .gap_1p5()
2637 .child(
2638 div()
2639 .flex_grow()
2640 .overflow_hidden()
2641 .max_w(relative(0.6))
2642 .h_full()
2643 .child(
2644 Label::new(commit.subject.clone())
2645 .size(LabelSize::Small)
2646 .truncate(),
2647 )
2648 .id("commit-msg-hover")
2649 .hoverable_tooltip(move |window, cx| {
2650 GitPanelMessageTooltip::new(
2651 this.clone(),
2652 commit.sha.clone(),
2653 window,
2654 cx,
2655 )
2656 .into()
2657 }),
2658 )
2659 .child(div().flex_1())
2660 .when(commit.has_parent, |this| {
2661 let has_unstaged = self.has_unstaged_changes();
2662 this.child(
2663 panel_icon_button("undo", IconName::Undo)
2664 .icon_size(IconSize::Small)
2665 .icon_color(Color::Muted)
2666 .tooltip(move |window, cx| {
2667 Tooltip::with_meta(
2668 "Uncommit",
2669 Some(&git::Uncommit),
2670 if has_unstaged {
2671 "git reset HEAD^ --soft"
2672 } else {
2673 "git reset HEAD^"
2674 },
2675 window,
2676 cx,
2677 )
2678 })
2679 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2680 )
2681 }),
2682 )
2683 }
2684
2685 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2686 h_flex()
2687 .h_full()
2688 .flex_grow()
2689 .justify_center()
2690 .items_center()
2691 .child(
2692 v_flex()
2693 .gap_3()
2694 .child(if self.active_repository.is_some() {
2695 "No changes to commit"
2696 } else {
2697 "No Git repositories"
2698 })
2699 .text_ui_sm(cx)
2700 .mx_auto()
2701 .text_color(Color::Placeholder.color(cx)),
2702 )
2703 }
2704
2705 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2706 let scroll_bar_style = self.show_scrollbar(cx);
2707 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2708
2709 if !self.should_show_scrollbar(cx)
2710 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2711 {
2712 return None;
2713 }
2714
2715 Some(
2716 div()
2717 .id("git-panel-vertical-scroll")
2718 .occlude()
2719 .flex_none()
2720 .h_full()
2721 .cursor_default()
2722 .when(show_container, |this| this.pl_1().px_1p5())
2723 .when(!show_container, |this| {
2724 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2725 })
2726 .on_mouse_move(cx.listener(|_, _, _, cx| {
2727 cx.notify();
2728 cx.stop_propagation()
2729 }))
2730 .on_hover(|_, _, cx| {
2731 cx.stop_propagation();
2732 })
2733 .on_any_mouse_down(|_, _, cx| {
2734 cx.stop_propagation();
2735 })
2736 .on_mouse_up(
2737 MouseButton::Left,
2738 cx.listener(|this, _, window, cx| {
2739 if !this.scrollbar_state.is_dragging()
2740 && !this.focus_handle.contains_focused(window, cx)
2741 {
2742 this.hide_scrollbar(window, cx);
2743 cx.notify();
2744 }
2745
2746 cx.stop_propagation();
2747 }),
2748 )
2749 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2750 cx.notify();
2751 }))
2752 .children(Scrollbar::vertical(
2753 // percentage as f32..end_offset as f32,
2754 self.scrollbar_state.clone(),
2755 )),
2756 )
2757 }
2758
2759 fn render_buffer_header_controls(
2760 &self,
2761 entity: &Entity<Self>,
2762 file: &Arc<dyn File>,
2763 _: &Window,
2764 cx: &App,
2765 ) -> Option<AnyElement> {
2766 let repo = self.active_repository.as_ref()?.read(cx);
2767 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2768 let ix = self.entry_by_path(&repo_path)?;
2769 let entry = self.entries.get(ix)?;
2770
2771 let entry_staging = self.entry_staging(entry.status_entry()?);
2772
2773 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
2774 .disabled(!self.has_write_access(cx))
2775 .fill()
2776 .elevation(ElevationIndex::Surface)
2777 .on_click({
2778 let entry = entry.clone();
2779 let git_panel = entity.downgrade();
2780 move |_, window, cx| {
2781 git_panel
2782 .update(cx, |this, cx| {
2783 this.toggle_staged_for_entry(&entry, window, cx);
2784 cx.stop_propagation();
2785 })
2786 .ok();
2787 }
2788 });
2789 Some(
2790 h_flex()
2791 .id("start-slot")
2792 .text_lg()
2793 .child(checkbox)
2794 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2795 // prevent the list item active state triggering when toggling checkbox
2796 cx.stop_propagation();
2797 })
2798 .into_any_element(),
2799 )
2800 }
2801
2802 fn render_entries(
2803 &self,
2804 has_write_access: bool,
2805 _: &Window,
2806 cx: &mut Context<Self>,
2807 ) -> impl IntoElement {
2808 let entry_count = self.entries.len();
2809
2810 h_flex()
2811 .size_full()
2812 .flex_grow()
2813 .overflow_hidden()
2814 .child(
2815 uniform_list(cx.entity().clone(), "entries", entry_count, {
2816 move |this, range, window, cx| {
2817 let mut items = Vec::with_capacity(range.end - range.start);
2818
2819 for ix in range {
2820 match &this.entries.get(ix) {
2821 Some(GitListEntry::GitStatusEntry(entry)) => {
2822 items.push(this.render_entry(
2823 ix,
2824 entry,
2825 has_write_access,
2826 window,
2827 cx,
2828 ));
2829 }
2830 Some(GitListEntry::Header(header)) => {
2831 items.push(this.render_list_header(
2832 ix,
2833 header,
2834 has_write_access,
2835 window,
2836 cx,
2837 ));
2838 }
2839 None => {}
2840 }
2841 }
2842
2843 items
2844 }
2845 })
2846 .size_full()
2847 .with_sizing_behavior(ListSizingBehavior::Auto)
2848 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2849 .track_scroll(self.scroll_handle.clone()),
2850 )
2851 .on_mouse_down(
2852 MouseButton::Right,
2853 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2854 this.deploy_panel_context_menu(event.position, window, cx)
2855 }),
2856 )
2857 .children(self.render_scrollbar(cx))
2858 }
2859
2860 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2861 Label::new(label.into()).color(color).single_line()
2862 }
2863
2864 fn list_item_height(&self) -> Rems {
2865 rems(1.75)
2866 }
2867
2868 fn render_list_header(
2869 &self,
2870 ix: usize,
2871 header: &GitHeaderEntry,
2872 _: bool,
2873 _: &Window,
2874 _: &Context<Self>,
2875 ) -> AnyElement {
2876 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2877
2878 h_flex()
2879 .id(id)
2880 .h(self.list_item_height())
2881 .w_full()
2882 .items_end()
2883 .px(rems(0.75)) // ~12px
2884 .pb(rems(0.3125)) // ~ 5px
2885 .child(
2886 Label::new(header.title())
2887 .color(Color::Muted)
2888 .size(LabelSize::Small)
2889 .line_height_style(LineHeightStyle::UiLabel)
2890 .single_line(),
2891 )
2892 .into_any_element()
2893 }
2894
2895 fn load_commit_details(
2896 &self,
2897 sha: &str,
2898 cx: &mut Context<Self>,
2899 ) -> Task<anyhow::Result<CommitDetails>> {
2900 let Some(repo) = self.active_repository.clone() else {
2901 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2902 };
2903 repo.update(cx, |repo, cx| {
2904 let show = repo.show(sha);
2905 cx.spawn(|_, _| async move { show.await? })
2906 })
2907 }
2908
2909 fn deploy_entry_context_menu(
2910 &mut self,
2911 position: Point<Pixels>,
2912 ix: usize,
2913 window: &mut Window,
2914 cx: &mut Context<Self>,
2915 ) {
2916 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2917 return;
2918 };
2919 let stage_title = if entry.status.staging().is_fully_staged() {
2920 "Unstage File"
2921 } else {
2922 "Stage File"
2923 };
2924 let restore_title = if entry.status.is_created() {
2925 "Trash File"
2926 } else {
2927 "Restore File"
2928 };
2929 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2930 context_menu
2931 .context(self.focus_handle.clone())
2932 .action(stage_title, ToggleStaged.boxed_clone())
2933 .action(restore_title, git::RestoreFile.boxed_clone())
2934 .separator()
2935 .action("Open Diff", Confirm.boxed_clone())
2936 .action("Open File", SecondaryConfirm.boxed_clone())
2937 });
2938 self.selected_entry = Some(ix);
2939 self.set_context_menu(context_menu, position, window, cx);
2940 }
2941
2942 fn deploy_panel_context_menu(
2943 &mut self,
2944 position: Point<Pixels>,
2945 window: &mut Window,
2946 cx: &mut Context<Self>,
2947 ) {
2948 let context_menu = git_panel_context_menu(Some(self.focus_handle.clone()), window, cx);
2949 self.set_context_menu(context_menu, position, window, cx);
2950 }
2951
2952 fn set_context_menu(
2953 &mut self,
2954 context_menu: Entity<ContextMenu>,
2955 position: Point<Pixels>,
2956 window: &Window,
2957 cx: &mut Context<Self>,
2958 ) {
2959 let subscription = cx.subscribe_in(
2960 &context_menu,
2961 window,
2962 |this, _, _: &DismissEvent, window, cx| {
2963 if this.context_menu.as_ref().is_some_and(|context_menu| {
2964 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2965 }) {
2966 cx.focus_self(window);
2967 }
2968 this.context_menu.take();
2969 cx.notify();
2970 },
2971 );
2972 self.context_menu = Some((context_menu, position, subscription));
2973 cx.notify();
2974 }
2975
2976 fn render_entry(
2977 &self,
2978 ix: usize,
2979 entry: &GitStatusEntry,
2980 has_write_access: bool,
2981 window: &Window,
2982 cx: &Context<Self>,
2983 ) -> AnyElement {
2984 let display_name = entry
2985 .worktree_path
2986 .file_name()
2987 .map(|name| name.to_string_lossy().into_owned())
2988 .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2989
2990 let worktree_path = entry.worktree_path.clone();
2991 let selected = self.selected_entry == Some(ix);
2992 let marked = self.marked_entries.contains(&ix);
2993 let status_style = GitPanelSettings::get_global(cx).status_style;
2994 let status = entry.status;
2995 let has_conflict = status.is_conflicted();
2996 let is_modified = status.is_modified();
2997 let is_deleted = status.is_deleted();
2998
2999 let label_color = if status_style == StatusStyle::LabelColor {
3000 if has_conflict {
3001 Color::Conflict
3002 } else if is_modified {
3003 Color::Modified
3004 } else if is_deleted {
3005 // We don't want a bunch of red labels in the list
3006 Color::Disabled
3007 } else {
3008 Color::Created
3009 }
3010 } else {
3011 Color::Default
3012 };
3013
3014 let path_color = if status.is_deleted() {
3015 Color::Disabled
3016 } else {
3017 Color::Muted
3018 };
3019
3020 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3021 let checkbox_wrapper_id: ElementId =
3022 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3023 let checkbox_id: ElementId =
3024 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3025
3026 let entry_staging = self.entry_staging(entry);
3027 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3028
3029 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3030 is_staged = ToggleState::Selected;
3031 }
3032
3033 let handle = cx.weak_entity();
3034
3035 let selected_bg_alpha = 0.08;
3036 let marked_bg_alpha = 0.12;
3037 let state_opacity_step = 0.04;
3038
3039 let base_bg = match (selected, marked) {
3040 (true, true) => cx
3041 .theme()
3042 .status()
3043 .info
3044 .alpha(selected_bg_alpha + marked_bg_alpha),
3045 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3046 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3047 _ => cx.theme().colors().ghost_element_background,
3048 };
3049
3050 let hover_bg = if selected {
3051 cx.theme()
3052 .status()
3053 .info
3054 .alpha(selected_bg_alpha + state_opacity_step)
3055 } else {
3056 cx.theme().colors().ghost_element_hover
3057 };
3058
3059 let active_bg = if selected {
3060 cx.theme()
3061 .status()
3062 .info
3063 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3064 } else {
3065 cx.theme().colors().ghost_element_active
3066 };
3067
3068 h_flex()
3069 .id(id)
3070 .h(self.list_item_height())
3071 .w_full()
3072 .items_center()
3073 .border_1()
3074 .when(selected && self.focus_handle.is_focused(window), |el| {
3075 el.border_color(cx.theme().colors().border_focused)
3076 })
3077 .px(rems(0.75)) // ~12px
3078 .overflow_hidden()
3079 .flex_none()
3080 .gap(DynamicSpacing::Base04.rems(cx))
3081 .bg(base_bg)
3082 .hover(|this| this.bg(hover_bg))
3083 .active(|this| this.bg(active_bg))
3084 .on_click({
3085 cx.listener(move |this, event: &ClickEvent, window, cx| {
3086 this.selected_entry = Some(ix);
3087 cx.notify();
3088 if event.modifiers().secondary() {
3089 this.open_file(&Default::default(), window, cx)
3090 } else {
3091 this.open_diff(&Default::default(), window, cx);
3092 this.focus_handle.focus(window);
3093 }
3094 })
3095 })
3096 .on_mouse_down(
3097 MouseButton::Right,
3098 move |event: &MouseDownEvent, window, cx| {
3099 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3100 if event.button != MouseButton::Right {
3101 return;
3102 }
3103
3104 let Some(this) = handle.upgrade() else {
3105 return;
3106 };
3107 this.update(cx, |this, cx| {
3108 this.deploy_entry_context_menu(event.position, ix, window, cx);
3109 });
3110 cx.stop_propagation();
3111 },
3112 )
3113 // .on_secondary_mouse_down(cx.listener(
3114 // move |this, event: &MouseDownEvent, window, cx| {
3115 // this.deploy_entry_context_menu(event.position, ix, window, cx);
3116 // cx.stop_propagation();
3117 // },
3118 // ))
3119 .child(
3120 div()
3121 .id(checkbox_wrapper_id)
3122 .flex_none()
3123 .occlude()
3124 .cursor_pointer()
3125 .child(
3126 Checkbox::new(checkbox_id, is_staged)
3127 .disabled(!has_write_access)
3128 .fill()
3129 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
3130 .elevation(ElevationIndex::Surface)
3131 .on_click({
3132 let entry = entry.clone();
3133 cx.listener(move |this, _, window, cx| {
3134 if !has_write_access {
3135 return;
3136 }
3137 this.toggle_staged_for_entry(
3138 &GitListEntry::GitStatusEntry(entry.clone()),
3139 window,
3140 cx,
3141 );
3142 cx.stop_propagation();
3143 })
3144 })
3145 .tooltip(move |window, cx| {
3146 let tooltip_name = if entry_staging.is_fully_staged() {
3147 "Unstage"
3148 } else {
3149 "Stage"
3150 };
3151
3152 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
3153 }),
3154 ),
3155 )
3156 .child(git_status_icon(status, cx))
3157 .child(
3158 h_flex()
3159 .items_center()
3160 .overflow_hidden()
3161 .when_some(worktree_path.parent(), |this, parent| {
3162 let parent_str = parent.to_string_lossy();
3163 if !parent_str.is_empty() {
3164 this.child(
3165 self.entry_label(format!("{}/", parent_str), path_color)
3166 .when(status.is_deleted(), |this| this.strikethrough()),
3167 )
3168 } else {
3169 this
3170 }
3171 })
3172 .child(
3173 self.entry_label(display_name.clone(), label_color)
3174 .when(status.is_deleted(), |this| this.strikethrough()),
3175 ),
3176 )
3177 .into_any_element()
3178 }
3179
3180 fn has_write_access(&self, cx: &App) -> bool {
3181 !self.project.read(cx).is_read_only(cx)
3182 }
3183}
3184
3185fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3186 let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3187 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3188 provider.is_authenticated(cx).then(|| model)
3189}
3190
3191impl Render for GitPanel {
3192 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3193 let project = self.project.read(cx);
3194 let has_entries = self.entries.len() > 0;
3195 let room = self
3196 .workspace
3197 .upgrade()
3198 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3199
3200 let has_write_access = self.has_write_access(cx);
3201
3202 let has_co_authors = room.map_or(false, |room| {
3203 room.read(cx)
3204 .remote_participants()
3205 .values()
3206 .any(|remote_participant| remote_participant.can_write())
3207 });
3208
3209 v_flex()
3210 .id("git_panel")
3211 .key_context(self.dispatch_context(window, cx))
3212 .track_focus(&self.focus_handle)
3213 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3214 .when(has_write_access && !project.is_read_only(cx), |this| {
3215 this.on_action(cx.listener(Self::toggle_staged_for_selected))
3216 .on_action(cx.listener(GitPanel::commit))
3217 .on_action(cx.listener(Self::stage_all))
3218 .on_action(cx.listener(Self::unstage_all))
3219 .on_action(cx.listener(Self::stage_selected))
3220 .on_action(cx.listener(Self::unstage_selected))
3221 .on_action(cx.listener(Self::restore_tracked_files))
3222 .on_action(cx.listener(Self::revert_selected))
3223 .on_action(cx.listener(Self::clean_all))
3224 .on_action(cx.listener(Self::generate_commit_message_action))
3225 })
3226 .on_action(cx.listener(Self::select_first))
3227 .on_action(cx.listener(Self::select_next))
3228 .on_action(cx.listener(Self::select_previous))
3229 .on_action(cx.listener(Self::select_last))
3230 .on_action(cx.listener(Self::close_panel))
3231 .on_action(cx.listener(Self::open_diff))
3232 .on_action(cx.listener(Self::open_file))
3233 .on_action(cx.listener(Self::focus_changes_list))
3234 .on_action(cx.listener(Self::focus_editor))
3235 .on_action(cx.listener(Self::expand_commit_editor))
3236 .when(has_write_access && has_co_authors, |git_panel| {
3237 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3238 })
3239 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3240 .on_hover(cx.listener(|this, hovered, window, cx| {
3241 if *hovered {
3242 this.show_scrollbar = true;
3243 this.hide_scrollbar_task.take();
3244 cx.notify();
3245 } else if !this.focus_handle.contains_focused(window, cx) {
3246 this.hide_scrollbar(window, cx);
3247 }
3248 }))
3249 .size_full()
3250 .overflow_hidden()
3251 .bg(ElevationIndex::Surface.bg(cx))
3252 .child(
3253 v_flex()
3254 .size_full()
3255 .child(self.render_panel_header(window, cx))
3256 .map(|this| {
3257 if has_entries {
3258 this.child(self.render_entries(has_write_access, window, cx))
3259 } else {
3260 this.child(self.render_empty_state(cx).into_any_element())
3261 }
3262 })
3263 .children(self.render_footer(window, cx))
3264 .children(self.render_previous_commit(cx))
3265 .into_any_element(),
3266 )
3267 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3268 deferred(
3269 anchored()
3270 .position(*position)
3271 .anchor(gpui::Corner::TopLeft)
3272 .child(menu.clone()),
3273 )
3274 .with_priority(1)
3275 }))
3276 }
3277}
3278
3279impl Focusable for GitPanel {
3280 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3281 self.focus_handle.clone()
3282 }
3283}
3284
3285impl EventEmitter<Event> for GitPanel {}
3286
3287impl EventEmitter<PanelEvent> for GitPanel {}
3288
3289pub(crate) struct GitPanelAddon {
3290 pub(crate) workspace: WeakEntity<Workspace>,
3291}
3292
3293impl editor::Addon for GitPanelAddon {
3294 fn to_any(&self) -> &dyn std::any::Any {
3295 self
3296 }
3297
3298 fn render_buffer_header_controls(
3299 &self,
3300 excerpt_info: &ExcerptInfo,
3301 window: &Window,
3302 cx: &App,
3303 ) -> Option<AnyElement> {
3304 let file = excerpt_info.buffer.file()?;
3305 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3306
3307 git_panel
3308 .read(cx)
3309 .render_buffer_header_controls(&git_panel, &file, window, cx)
3310 }
3311}
3312
3313impl Panel for GitPanel {
3314 fn persistent_name() -> &'static str {
3315 "GitPanel"
3316 }
3317
3318 fn position(&self, _: &Window, cx: &App) -> DockPosition {
3319 GitPanelSettings::get_global(cx).dock
3320 }
3321
3322 fn position_is_valid(&self, position: DockPosition) -> bool {
3323 matches!(position, DockPosition::Left | DockPosition::Right)
3324 }
3325
3326 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3327 settings::update_settings_file::<GitPanelSettings>(
3328 self.fs.clone(),
3329 cx,
3330 move |settings, _| settings.dock = Some(position),
3331 );
3332 }
3333
3334 fn size(&self, _: &Window, cx: &App) -> Pixels {
3335 self.width
3336 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3337 }
3338
3339 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3340 self.width = size;
3341 self.serialize(cx);
3342 cx.notify();
3343 }
3344
3345 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3346 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3347 }
3348
3349 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3350 Some("Git Panel")
3351 }
3352
3353 fn toggle_action(&self) -> Box<dyn Action> {
3354 Box::new(ToggleFocus)
3355 }
3356
3357 fn activation_priority(&self) -> u32 {
3358 2
3359 }
3360}
3361
3362impl PanelHeader for GitPanel {}
3363
3364struct GitPanelMessageTooltip {
3365 commit_tooltip: Option<Entity<CommitTooltip>>,
3366}
3367
3368impl GitPanelMessageTooltip {
3369 fn new(
3370 git_panel: Entity<GitPanel>,
3371 sha: SharedString,
3372 window: &mut Window,
3373 cx: &mut App,
3374 ) -> Entity<Self> {
3375 cx.new(|cx| {
3376 cx.spawn_in(window, |this, mut cx| async move {
3377 let details = git_panel
3378 .update(&mut cx, |git_panel, cx| {
3379 git_panel.load_commit_details(&sha, cx)
3380 })?
3381 .await?;
3382
3383 let commit_details = editor::commit_tooltip::CommitDetails {
3384 sha: details.sha.clone(),
3385 committer_name: details.committer_name.clone(),
3386 committer_email: details.committer_email.clone(),
3387 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3388 message: Some(editor::commit_tooltip::ParsedCommitMessage {
3389 message: details.message.clone(),
3390 ..Default::default()
3391 }),
3392 };
3393
3394 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3395 this.commit_tooltip =
3396 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3397 cx.notify();
3398 })
3399 })
3400 .detach();
3401
3402 Self {
3403 commit_tooltip: None,
3404 }
3405 })
3406 }
3407}
3408
3409impl Render for GitPanelMessageTooltip {
3410 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3411 if let Some(commit_tooltip) = &self.commit_tooltip {
3412 commit_tooltip.clone().into_any_element()
3413 } else {
3414 gpui::Empty.into_any_element()
3415 }
3416 }
3417}
3418
3419#[derive(IntoElement, IntoComponent)]
3420#[component(scope = "Version Control")]
3421pub struct PanelRepoFooter {
3422 id: SharedString,
3423 active_repository: SharedString,
3424 branch: Option<Branch>,
3425 // Getting a GitPanel in previews will be difficult.
3426 //
3427 // For now just take an option here, and we won't bind handlers to buttons in previews.
3428 git_panel: Option<Entity<GitPanel>>,
3429}
3430
3431impl PanelRepoFooter {
3432 pub fn new(
3433 id: impl Into<SharedString>,
3434 active_repository: SharedString,
3435 branch: Option<Branch>,
3436 git_panel: Option<Entity<GitPanel>>,
3437 ) -> Self {
3438 Self {
3439 id: id.into(),
3440 active_repository,
3441 branch,
3442 git_panel,
3443 }
3444 }
3445
3446 pub fn new_preview(
3447 id: impl Into<SharedString>,
3448 active_repository: SharedString,
3449 branch: Option<Branch>,
3450 ) -> Self {
3451 Self {
3452 id: id.into(),
3453 active_repository,
3454 branch,
3455 git_panel: None,
3456 }
3457 }
3458
3459 fn render_overflow_menu(&self, id: impl Into<ElementId>, cx: &App) -> impl IntoElement {
3460 let focus_handle = self
3461 .git_panel
3462 .as_ref()
3463 .map(|git_panel| git_panel.focus_handle(cx));
3464 PopoverMenu::new(id.into())
3465 .trigger(
3466 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3467 .icon_size(IconSize::Small)
3468 .icon_color(Color::Muted),
3469 )
3470 .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
3471 .anchor(Corner::TopRight)
3472 }
3473}
3474
3475impl RenderOnce for PanelRepoFooter {
3476 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3477 let active_repo = self.active_repository.clone();
3478 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3479 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3480 .style(ButtonStyle::Transparent)
3481 .size(ButtonSize::None)
3482 .label_size(LabelSize::Small)
3483 .color(Color::Muted);
3484
3485 let project = self
3486 .git_panel
3487 .as_ref()
3488 .map(|panel| panel.read(cx).project.clone());
3489
3490 let repo = self
3491 .git_panel
3492 .as_ref()
3493 .and_then(|panel| panel.read(cx).active_repository.clone());
3494
3495 let single_repo = project
3496 .as_ref()
3497 .map(|project| {
3498 filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3499 })
3500 .unwrap_or(true);
3501
3502 let repo_selector = PopoverMenu::new("repository-switcher")
3503 .menu({
3504 let project = project.clone();
3505 move |window, cx| {
3506 let project = project.clone()?;
3507 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3508 }
3509 })
3510 .trigger_with_tooltip(
3511 repo_selector_trigger.disabled(single_repo).truncate(true),
3512 Tooltip::text("Switch active repository"),
3513 )
3514 .attach(gpui::Corner::BottomLeft)
3515 .into_any_element();
3516
3517 let branch = self.branch.clone();
3518 let branch_name = branch
3519 .as_ref()
3520 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3521
3522 let branch_selector_button = Button::new("branch-selector", branch_name)
3523 .style(ButtonStyle::Transparent)
3524 .size(ButtonSize::None)
3525 .label_size(LabelSize::Small)
3526 .truncate(true)
3527 .tooltip(Tooltip::for_action_title(
3528 "Switch Branch",
3529 &zed_actions::git::Branch,
3530 ))
3531 .on_click(|_, window, cx| {
3532 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3533 });
3534
3535 let branch_selector = PopoverMenu::new("popover-button")
3536 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3537 .trigger_with_tooltip(
3538 branch_selector_button,
3539 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3540 )
3541 .anchor(Corner::TopLeft)
3542 .offset(gpui::Point {
3543 x: px(0.0),
3544 y: px(-2.0),
3545 });
3546
3547 let spinner = self
3548 .git_panel
3549 .as_ref()
3550 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3551
3552 h_flex()
3553 .w_full()
3554 .px_2()
3555 .h(px(36.))
3556 .items_center()
3557 .justify_between()
3558 .child(
3559 h_flex()
3560 .flex_1()
3561 .overflow_hidden()
3562 .items_center()
3563 .child(
3564 div().child(
3565 Icon::new(IconName::GitBranchSmall)
3566 .size(IconSize::Small)
3567 .color(Color::Muted),
3568 ),
3569 )
3570 .child(repo_selector)
3571 .when_some(branch.clone(), |this, _| {
3572 this.child(
3573 div()
3574 .text_color(cx.theme().colors().text_muted)
3575 .text_sm()
3576 .child("/"),
3577 )
3578 })
3579 .child(branch_selector),
3580 )
3581 .child(
3582 h_flex()
3583 .gap_1()
3584 .flex_shrink_0()
3585 .children(spinner)
3586 .child(self.render_overflow_menu(overflow_menu_id, cx))
3587 .when_some(branch, |this, branch| {
3588 let mut focus_handle = None;
3589 if let Some(git_panel) = self.git_panel.as_ref() {
3590 if !git_panel.read(cx).can_push_and_pull(cx) {
3591 return this;
3592 }
3593 focus_handle = Some(git_panel.focus_handle(cx));
3594 }
3595
3596 this.children(render_remote_button(
3597 self.id.clone(),
3598 &branch,
3599 focus_handle,
3600 true,
3601 ))
3602 }),
3603 )
3604 }
3605}
3606
3607impl ComponentPreview for PanelRepoFooter {
3608 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3609 let unknown_upstream = None;
3610 let no_remote_upstream = Some(UpstreamTracking::Gone);
3611 let ahead_of_upstream = Some(
3612 UpstreamTrackingStatus {
3613 ahead: 2,
3614 behind: 0,
3615 }
3616 .into(),
3617 );
3618 let behind_upstream = Some(
3619 UpstreamTrackingStatus {
3620 ahead: 0,
3621 behind: 2,
3622 }
3623 .into(),
3624 );
3625 let ahead_and_behind_upstream = Some(
3626 UpstreamTrackingStatus {
3627 ahead: 3,
3628 behind: 1,
3629 }
3630 .into(),
3631 );
3632
3633 let not_ahead_or_behind_upstream = Some(
3634 UpstreamTrackingStatus {
3635 ahead: 0,
3636 behind: 0,
3637 }
3638 .into(),
3639 );
3640
3641 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3642 Branch {
3643 is_head: true,
3644 name: "some-branch".into(),
3645 upstream: upstream.map(|tracking| Upstream {
3646 ref_name: "origin/some-branch".into(),
3647 tracking,
3648 }),
3649 most_recent_commit: Some(CommitSummary {
3650 sha: "abc123".into(),
3651 subject: "Modify stuff".into(),
3652 commit_timestamp: 1710932954,
3653 has_parent: true,
3654 }),
3655 }
3656 }
3657
3658 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3659 Branch {
3660 is_head: true,
3661 name: branch_name.to_string().into(),
3662 upstream: upstream.map(|tracking| Upstream {
3663 ref_name: format!("zed/{}", branch_name).into(),
3664 tracking,
3665 }),
3666 most_recent_commit: Some(CommitSummary {
3667 sha: "abc123".into(),
3668 subject: "Modify stuff".into(),
3669 commit_timestamp: 1710932954,
3670 has_parent: true,
3671 }),
3672 }
3673 }
3674
3675 fn active_repository(id: usize) -> SharedString {
3676 format!("repo-{}", id).into()
3677 }
3678
3679 let example_width = px(340.);
3680
3681 v_flex()
3682 .gap_6()
3683 .w_full()
3684 .flex_none()
3685 .children(vec![example_group_with_title(
3686 "Action Button States",
3687 vec![
3688 single_example(
3689 "No Branch",
3690 div()
3691 .w(example_width)
3692 .overflow_hidden()
3693 .child(PanelRepoFooter::new_preview(
3694 "no-branch",
3695 active_repository(1).clone(),
3696 None,
3697 ))
3698 .into_any_element(),
3699 )
3700 .grow(),
3701 single_example(
3702 "Remote status unknown",
3703 div()
3704 .w(example_width)
3705 .overflow_hidden()
3706 .child(PanelRepoFooter::new_preview(
3707 "unknown-upstream",
3708 active_repository(2).clone(),
3709 Some(branch(unknown_upstream)),
3710 ))
3711 .into_any_element(),
3712 )
3713 .grow(),
3714 single_example(
3715 "No Remote Upstream",
3716 div()
3717 .w(example_width)
3718 .overflow_hidden()
3719 .child(PanelRepoFooter::new_preview(
3720 "no-remote-upstream",
3721 active_repository(3).clone(),
3722 Some(branch(no_remote_upstream)),
3723 ))
3724 .into_any_element(),
3725 )
3726 .grow(),
3727 single_example(
3728 "Not Ahead or Behind",
3729 div()
3730 .w(example_width)
3731 .overflow_hidden()
3732 .child(PanelRepoFooter::new_preview(
3733 "not-ahead-or-behind",
3734 active_repository(4).clone(),
3735 Some(branch(not_ahead_or_behind_upstream)),
3736 ))
3737 .into_any_element(),
3738 )
3739 .grow(),
3740 single_example(
3741 "Behind remote",
3742 div()
3743 .w(example_width)
3744 .overflow_hidden()
3745 .child(PanelRepoFooter::new_preview(
3746 "behind-remote",
3747 active_repository(5).clone(),
3748 Some(branch(behind_upstream)),
3749 ))
3750 .into_any_element(),
3751 )
3752 .grow(),
3753 single_example(
3754 "Ahead of remote",
3755 div()
3756 .w(example_width)
3757 .overflow_hidden()
3758 .child(PanelRepoFooter::new_preview(
3759 "ahead-of-remote",
3760 active_repository(6).clone(),
3761 Some(branch(ahead_of_upstream)),
3762 ))
3763 .into_any_element(),
3764 )
3765 .grow(),
3766 single_example(
3767 "Ahead and behind remote",
3768 div()
3769 .w(example_width)
3770 .overflow_hidden()
3771 .child(PanelRepoFooter::new_preview(
3772 "ahead-and-behind",
3773 active_repository(7).clone(),
3774 Some(branch(ahead_and_behind_upstream)),
3775 ))
3776 .into_any_element(),
3777 )
3778 .grow(),
3779 ],
3780 )
3781 .grow()
3782 .vertical()])
3783 .children(vec![example_group_with_title(
3784 "Labels",
3785 vec![
3786 single_example(
3787 "Short Branch & Repo",
3788 div()
3789 .w(example_width)
3790 .overflow_hidden()
3791 .child(PanelRepoFooter::new_preview(
3792 "short-branch",
3793 SharedString::from("zed"),
3794 Some(custom("main", behind_upstream)),
3795 ))
3796 .into_any_element(),
3797 )
3798 .grow(),
3799 single_example(
3800 "Long Branch",
3801 div()
3802 .w(example_width)
3803 .overflow_hidden()
3804 .child(PanelRepoFooter::new_preview(
3805 "long-branch",
3806 SharedString::from("zed"),
3807 Some(custom(
3808 "redesign-and-update-git-ui-list-entry-style",
3809 behind_upstream,
3810 )),
3811 ))
3812 .into_any_element(),
3813 )
3814 .grow(),
3815 single_example(
3816 "Long Repo",
3817 div()
3818 .w(example_width)
3819 .overflow_hidden()
3820 .child(PanelRepoFooter::new_preview(
3821 "long-repo",
3822 SharedString::from("zed-industries-community-examples"),
3823 Some(custom("gpui", ahead_of_upstream)),
3824 ))
3825 .into_any_element(),
3826 )
3827 .grow(),
3828 single_example(
3829 "Long Repo & Branch",
3830 div()
3831 .w(example_width)
3832 .overflow_hidden()
3833 .child(PanelRepoFooter::new_preview(
3834 "long-repo-and-branch",
3835 SharedString::from("zed-industries-community-examples"),
3836 Some(custom(
3837 "redesign-and-update-git-ui-list-entry-style",
3838 behind_upstream,
3839 )),
3840 ))
3841 .into_any_element(),
3842 )
3843 .grow(),
3844 single_example(
3845 "Uppercase Repo",
3846 div()
3847 .w(example_width)
3848 .overflow_hidden()
3849 .child(PanelRepoFooter::new_preview(
3850 "uppercase-repo",
3851 SharedString::from("LICENSES"),
3852 Some(custom("main", ahead_of_upstream)),
3853 ))
3854 .into_any_element(),
3855 )
3856 .grow(),
3857 single_example(
3858 "Uppercase Branch",
3859 div()
3860 .w(example_width)
3861 .overflow_hidden()
3862 .child(PanelRepoFooter::new_preview(
3863 "uppercase-branch",
3864 SharedString::from("zed"),
3865 Some(custom("update-README", behind_upstream)),
3866 ))
3867 .into_any_element(),
3868 )
3869 .grow(),
3870 ],
3871 )
3872 .grow()
3873 .vertical()])
3874 .into_any_element()
3875 }
3876}
3877
3878#[cfg(test)]
3879mod tests {
3880 use git::status::StatusCode;
3881 use gpui::TestAppContext;
3882 use project::{FakeFs, WorktreeSettings};
3883 use serde_json::json;
3884 use settings::SettingsStore;
3885 use theme::LoadThemes;
3886 use util::path;
3887
3888 use super::*;
3889
3890 fn init_test(cx: &mut gpui::TestAppContext) {
3891 if std::env::var("RUST_LOG").is_ok() {
3892 env_logger::try_init().ok();
3893 }
3894
3895 cx.update(|cx| {
3896 let settings_store = SettingsStore::test(cx);
3897 cx.set_global(settings_store);
3898 WorktreeSettings::register(cx);
3899 workspace::init_settings(cx);
3900 theme::init(LoadThemes::JustBase, cx);
3901 language::init(cx);
3902 editor::init(cx);
3903 Project::init_settings(cx);
3904 crate::init(cx);
3905 });
3906 }
3907
3908 #[gpui::test]
3909 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3910 init_test(cx);
3911 let fs = FakeFs::new(cx.background_executor.clone());
3912 fs.insert_tree(
3913 "/root",
3914 json!({
3915 "zed": {
3916 ".git": {},
3917 "crates": {
3918 "gpui": {
3919 "gpui.rs": "fn main() {}"
3920 },
3921 "util": {
3922 "util.rs": "fn do_it() {}"
3923 }
3924 }
3925 },
3926 }),
3927 )
3928 .await;
3929
3930 fs.set_status_for_repo_via_git_operation(
3931 Path::new(path!("/root/zed/.git")),
3932 &[
3933 (
3934 Path::new("crates/gpui/gpui.rs"),
3935 StatusCode::Modified.worktree(),
3936 ),
3937 (
3938 Path::new("crates/util/util.rs"),
3939 StatusCode::Modified.worktree(),
3940 ),
3941 ],
3942 );
3943
3944 let project =
3945 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
3946 let (workspace, cx) =
3947 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3948
3949 cx.read(|cx| {
3950 project
3951 .read(cx)
3952 .worktrees(cx)
3953 .nth(0)
3954 .unwrap()
3955 .read(cx)
3956 .as_local()
3957 .unwrap()
3958 .scan_complete()
3959 })
3960 .await;
3961
3962 cx.executor().run_until_parked();
3963
3964 let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
3965 let panel = cx.new_window_entity(|window, cx| {
3966 GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
3967 });
3968
3969 let handle = cx.update_window_entity(&panel, |panel, _, _| {
3970 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3971 });
3972 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3973 handle.await;
3974
3975 let entries = panel.update(cx, |panel, _| panel.entries.clone());
3976 pretty_assertions::assert_eq!(
3977 entries,
3978 [
3979 GitListEntry::Header(GitHeaderEntry {
3980 header: Section::Tracked
3981 }),
3982 GitListEntry::GitStatusEntry(GitStatusEntry {
3983 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3984 repo_path: "crates/gpui/gpui.rs".into(),
3985 worktree_path: Path::new("gpui.rs").into(),
3986 status: StatusCode::Modified.worktree(),
3987 staging: StageStatus::Unstaged,
3988 }),
3989 GitListEntry::GitStatusEntry(GitStatusEntry {
3990 abs_path: path!("/root/zed/crates/util/util.rs").into(),
3991 repo_path: "crates/util/util.rs".into(),
3992 worktree_path: Path::new("../util/util.rs").into(),
3993 status: StatusCode::Modified.worktree(),
3994 staging: StageStatus::Unstaged,
3995 },),
3996 ],
3997 );
3998
3999 cx.update_window_entity(&panel, |panel, window, cx| {
4000 panel.select_last(&Default::default(), window, cx);
4001 assert_eq!(panel.selected_entry, Some(2));
4002 panel.open_diff(&Default::default(), window, cx);
4003 });
4004 cx.run_until_parked();
4005
4006 let worktree_roots = workspace.update(cx, |workspace, cx| {
4007 workspace
4008 .worktrees(cx)
4009 .map(|worktree| worktree.read(cx).abs_path())
4010 .collect::<Vec<_>>()
4011 });
4012 pretty_assertions::assert_eq!(
4013 worktree_roots,
4014 vec![
4015 Path::new(path!("/root/zed/crates/gpui")).into(),
4016 Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4017 ]
4018 );
4019
4020 let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4021 let git_store = project.git_store().read(cx);
4022 // The repo that comes from the single-file worktree can't be selected through the UI.
4023 let filtered_entries = filtered_repository_entries(git_store, cx)
4024 .iter()
4025 .map(|repo| repo.read(cx).worktree_abs_path.clone())
4026 .collect::<Vec<_>>();
4027 assert_eq!(
4028 filtered_entries,
4029 [Path::new(path!("/root/zed/crates/gpui")).into()]
4030 );
4031 // But we can select it artificially here.
4032 git_store
4033 .all_repositories()
4034 .into_iter()
4035 .find(|repo| {
4036 &*repo.read(cx).worktree_abs_path
4037 == Path::new(path!("/root/zed/crates/util/util.rs"))
4038 })
4039 .unwrap()
4040 });
4041
4042 // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4043 repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4044 let handle = cx.update_window_entity(&panel, |panel, _, _| {
4045 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4046 });
4047 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4048 handle.await;
4049 let entries = panel.update(cx, |panel, _| panel.entries.clone());
4050 pretty_assertions::assert_eq!(
4051 entries,
4052 [
4053 GitListEntry::Header(GitHeaderEntry {
4054 header: Section::Tracked
4055 }),
4056 GitListEntry::GitStatusEntry(GitStatusEntry {
4057 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4058 repo_path: "crates/gpui/gpui.rs".into(),
4059 worktree_path: Path::new("../../gpui/gpui.rs").into(),
4060 status: StatusCode::Modified.worktree(),
4061 staging: StageStatus::Unstaged,
4062 }),
4063 GitListEntry::GitStatusEntry(GitStatusEntry {
4064 abs_path: path!("/root/zed/crates/util/util.rs").into(),
4065 repo_path: "crates/util/util.rs".into(),
4066 worktree_path: Path::new("util.rs").into(),
4067 status: StatusCode::Modified.worktree(),
4068 staging: StageStatus::Unstaged,
4069 },),
4070 ],
4071 );
4072 }
4073}