1use crate::askpass_modal::AskPassModal;
2use crate::commit_modal::CommitModal;
3use crate::commit_tooltip::CommitTooltip;
4use crate::commit_view::CommitView;
5use crate::git_panel_settings::StatusStyle;
6use crate::project_diff::{self, Diff, ProjectDiff};
7use crate::remote_output::{self, RemoteAction, SuccessMessage};
8use crate::{branch_picker, picker_prompt, render_remote_button};
9use crate::{
10 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
11};
12use agent_settings::AgentSettings;
13use anyhow::Context as _;
14use askpass::AskPassDelegate;
15use client::DisableAiSettings;
16use db::kvp::KEY_VALUE_STORE;
17use editor::{
18 Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar,
19 scroll::ScrollbarAutoHide,
20};
21use futures::StreamExt as _;
22use git::blame::ParsedCommitMessage;
23use git::repository::{
24 Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,
25 PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,
26 UpstreamTrackingStatus, get_git_committer,
27};
28use git::status::StageStatus;
29use git::{Amend, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};
30use git::{
31 ExpandCommitEditor, RestoreTrackedFiles, StageAll, StashAll, StashPop, TrashUntrackedFiles,
32 UnstageAll,
33};
34use gpui::{
35 Action, Animation, AnimationExt as _, AsyncApp, AsyncWindowContext, Axis, ClickEvent, Corner,
36 DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,
37 ListHorizontalSizingBehavior, ListSizingBehavior, MouseButton, MouseDownEvent, Point,
38 PromptLevel, ScrollStrategy, Subscription, Task, Transformation, UniformListScrollHandle,
39 WeakEntity, actions, anchored, deferred, percentage, uniform_list,
40};
41use itertools::Itertools;
42use language::{Buffer, File};
43use language_model::{
44 ConfiguredModel, LanguageModel, LanguageModelRegistry, LanguageModelRequest,
45 LanguageModelRequestMessage, Role,
46};
47use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
48use multi_buffer::ExcerptInfo;
49use notifications::status_toast::{StatusToast, ToastIcon};
50use panel::{
51 PanelHeader, panel_button, panel_editor_container, panel_editor_style, panel_filled_button,
52 panel_icon_button,
53};
54use project::git_store::{RepositoryEvent, RepositoryId};
55use project::{
56 Fs, Project, ProjectPath,
57 git_store::{GitStoreEvent, Repository},
58};
59use serde::{Deserialize, Serialize};
60use settings::{Settings, SettingsStore};
61use std::future::Future;
62use std::ops::Range;
63use std::path::{Path, PathBuf};
64use std::{collections::HashSet, sync::Arc, time::Duration, usize};
65use strum::{IntoEnumIterator, VariantNames};
66use time::OffsetDateTime;
67use ui::{
68 Checkbox, ContextMenu, ElevationIndex, IconPosition, Label, LabelSize, PopoverMenu, Scrollbar,
69 ScrollbarState, SplitButton, Tooltip, prelude::*,
70};
71use util::{ResultExt, TryFutureExt, maybe};
72use workspace::SERIALIZATION_THROTTLE_TIME;
73
74use workspace::{
75 Workspace,
76 dock::{DockPosition, Panel, PanelEvent},
77 notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId},
78};
79use zed_llm_client::CompletionIntent;
80
81actions!(
82 git_panel,
83 [
84 /// Closes the git panel.
85 Close,
86 /// Toggles focus on the git panel.
87 ToggleFocus,
88 /// Opens the git panel menu.
89 OpenMenu,
90 /// Focuses on the commit message editor.
91 FocusEditor,
92 /// Focuses on the changes list.
93 FocusChanges,
94 /// Toggles automatic co-author suggestions.
95 ToggleFillCoAuthors,
96 ]
97);
98
99fn prompt<T>(
100 msg: &str,
101 detail: Option<&str>,
102 window: &mut Window,
103 cx: &mut App,
104) -> Task<anyhow::Result<T>>
105where
106 T: IntoEnumIterator + VariantNames + 'static,
107{
108 let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
109 cx.spawn(async move |_| Ok(T::iter().nth(rx.await?).unwrap()))
110}
111
112#[derive(strum::EnumIter, strum::VariantNames)]
113#[strum(serialize_all = "title_case")]
114enum TrashCancel {
115 Trash,
116 Cancel,
117}
118
119struct GitMenuState {
120 has_tracked_changes: bool,
121 has_staged_changes: bool,
122 has_unstaged_changes: bool,
123 has_new_changes: bool,
124}
125
126fn git_panel_context_menu(
127 focus_handle: FocusHandle,
128 state: GitMenuState,
129 window: &mut Window,
130 cx: &mut App,
131) -> Entity<ContextMenu> {
132 ContextMenu::build(window, cx, move |context_menu, _, _| {
133 context_menu
134 .context(focus_handle)
135 .action_disabled_when(
136 !state.has_unstaged_changes,
137 "Stage All",
138 StageAll.boxed_clone(),
139 )
140 .action_disabled_when(
141 !state.has_staged_changes,
142 "Unstage All",
143 UnstageAll.boxed_clone(),
144 )
145 .separator()
146 .action_disabled_when(
147 !(state.has_new_changes || state.has_tracked_changes),
148 "Stash All",
149 StashAll.boxed_clone(),
150 )
151 .action("Stash Pop", StashPop.boxed_clone())
152 .separator()
153 .action("Open Diff", project_diff::Diff.boxed_clone())
154 .separator()
155 .action_disabled_when(
156 !state.has_tracked_changes,
157 "Discard Tracked Changes",
158 RestoreTrackedFiles.boxed_clone(),
159 )
160 .action_disabled_when(
161 !state.has_new_changes,
162 "Trash Untracked Files",
163 TrashUntrackedFiles.boxed_clone(),
164 )
165 })
166}
167
168const GIT_PANEL_KEY: &str = "GitPanel";
169
170const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
171
172pub fn register(workspace: &mut Workspace) {
173 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
174 workspace.toggle_panel_focus::<GitPanel>(window, cx);
175 });
176 workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
177 CommitModal::toggle(workspace, None, window, cx)
178 });
179}
180
181#[derive(Debug, Clone)]
182pub enum Event {
183 Focus,
184}
185
186#[derive(Serialize, Deserialize)]
187struct SerializedGitPanel {
188 width: Option<Pixels>,
189 #[serde(default)]
190 amend_pending: bool,
191 #[serde(default)]
192 signoff_enabled: bool,
193}
194
195#[derive(Debug, PartialEq, Eq, Clone, Copy)]
196enum Section {
197 Conflict,
198 Tracked,
199 New,
200}
201
202#[derive(Debug, PartialEq, Eq, Clone)]
203struct GitHeaderEntry {
204 header: Section,
205}
206
207impl GitHeaderEntry {
208 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
209 let this = &self.header;
210 let status = status_entry.status;
211 match this {
212 Section::Conflict => {
213 repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path)
214 }
215 Section::Tracked => !status.is_created(),
216 Section::New => status.is_created(),
217 }
218 }
219 pub fn title(&self) -> &'static str {
220 match self.header {
221 Section::Conflict => "Conflicts",
222 Section::Tracked => "Tracked",
223 Section::New => "Untracked",
224 }
225 }
226}
227
228#[derive(Debug, PartialEq, Eq, Clone)]
229enum GitListEntry {
230 Status(GitStatusEntry),
231 Header(GitHeaderEntry),
232}
233
234impl GitListEntry {
235 fn status_entry(&self) -> Option<&GitStatusEntry> {
236 match self {
237 GitListEntry::Status(entry) => Some(entry),
238 _ => None,
239 }
240 }
241}
242
243#[derive(Debug, PartialEq, Eq, Clone)]
244pub struct GitStatusEntry {
245 pub(crate) repo_path: RepoPath,
246 pub(crate) abs_path: PathBuf,
247 pub(crate) status: FileStatus,
248 pub(crate) staging: StageStatus,
249}
250
251impl GitStatusEntry {
252 fn display_name(&self) -> String {
253 self.repo_path
254 .file_name()
255 .map(|name| name.to_string_lossy().into_owned())
256 .unwrap_or_else(|| self.repo_path.to_string_lossy().into_owned())
257 }
258
259 fn parent_dir(&self) -> Option<String> {
260 self.repo_path
261 .parent()
262 .map(|parent| parent.to_string_lossy().into_owned())
263 }
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267enum TargetStatus {
268 Staged,
269 Unstaged,
270 Reverted,
271 Unchanged,
272}
273
274struct PendingOperation {
275 finished: bool,
276 target_status: TargetStatus,
277 entries: Vec<GitStatusEntry>,
278 op_id: usize,
279}
280
281// computed state related to how to render scrollbars
282// one per axis
283// on render we just read this off the panel
284// we update it when
285// - settings change
286// - on focus in, on focus out, on hover, etc.
287#[derive(Debug)]
288struct ScrollbarProperties {
289 axis: Axis,
290 show_scrollbar: bool,
291 show_track: bool,
292 auto_hide: bool,
293 hide_task: Option<Task<()>>,
294 state: ScrollbarState,
295}
296
297impl ScrollbarProperties {
298 // Shows the scrollbar and cancels any pending hide task
299 fn show(&mut self, cx: &mut Context<GitPanel>) {
300 if !self.auto_hide {
301 return;
302 }
303 self.show_scrollbar = true;
304 self.hide_task.take();
305 cx.notify();
306 }
307
308 fn hide(&mut self, window: &mut Window, cx: &mut Context<GitPanel>) {
309 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
310
311 if !self.auto_hide {
312 return;
313 }
314
315 let axis = self.axis;
316 self.hide_task = Some(cx.spawn_in(window, async move |panel, cx| {
317 cx.background_executor()
318 .timer(SCROLLBAR_SHOW_INTERVAL)
319 .await;
320
321 if let Some(panel) = panel.upgrade() {
322 panel
323 .update(cx, |panel, cx| {
324 match axis {
325 Axis::Vertical => panel.vertical_scrollbar.show_scrollbar = false,
326 Axis::Horizontal => panel.horizontal_scrollbar.show_scrollbar = false,
327 }
328 cx.notify();
329 })
330 .log_err();
331 }
332 }));
333 }
334}
335
336pub struct GitPanel {
337 pub(crate) active_repository: Option<Entity<Repository>>,
338 pub(crate) commit_editor: Entity<Editor>,
339 conflicted_count: usize,
340 conflicted_staged_count: usize,
341 add_coauthors: bool,
342 generate_commit_message_task: Option<Task<Option<()>>>,
343 entries: Vec<GitListEntry>,
344 single_staged_entry: Option<GitStatusEntry>,
345 single_tracked_entry: Option<GitStatusEntry>,
346 focus_handle: FocusHandle,
347 fs: Arc<dyn Fs>,
348 horizontal_scrollbar: ScrollbarProperties,
349 vertical_scrollbar: ScrollbarProperties,
350 new_count: usize,
351 entry_count: usize,
352 new_staged_count: usize,
353 pending: Vec<PendingOperation>,
354 pending_commit: Option<Task<()>>,
355 amend_pending: bool,
356 signoff_enabled: bool,
357 pending_serialization: Task<()>,
358 pub(crate) project: Entity<Project>,
359 scroll_handle: UniformListScrollHandle,
360 max_width_item_index: Option<usize>,
361 selected_entry: Option<usize>,
362 marked_entries: Vec<usize>,
363 tracked_count: usize,
364 tracked_staged_count: usize,
365 update_visible_entries_task: Task<()>,
366 width: Option<Pixels>,
367 workspace: WeakEntity<Workspace>,
368 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
369 modal_open: bool,
370 show_placeholders: bool,
371 local_committer: Option<GitCommitter>,
372 local_committer_task: Option<Task<()>>,
373 bulk_staging: Option<BulkStaging>,
374 _settings_subscription: Subscription,
375}
376
377#[derive(Clone, Debug, PartialEq, Eq)]
378struct BulkStaging {
379 repo_id: RepositoryId,
380 anchor: RepoPath,
381}
382
383const MAX_PANEL_EDITOR_LINES: usize = 6;
384
385pub(crate) fn commit_message_editor(
386 commit_message_buffer: Entity<Buffer>,
387 placeholder: Option<SharedString>,
388 project: Entity<Project>,
389 in_panel: bool,
390 window: &mut Window,
391 cx: &mut Context<Editor>,
392) -> Editor {
393 project.update(cx, |this, cx| {
394 this.mark_buffer_as_non_searchable(commit_message_buffer.read(cx).remote_id(), cx);
395 });
396 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
397 let max_lines = if in_panel { MAX_PANEL_EDITOR_LINES } else { 18 };
398 let mut commit_editor = Editor::new(
399 EditorMode::AutoHeight {
400 min_lines: 1,
401 max_lines: Some(max_lines),
402 },
403 buffer,
404 None,
405 window,
406 cx,
407 );
408 commit_editor.set_collaboration_hub(Box::new(project));
409 commit_editor.set_use_autoclose(false);
410 commit_editor.set_show_gutter(false, cx);
411 commit_editor.set_use_modal_editing(true);
412 commit_editor.set_show_wrap_guides(false, cx);
413 commit_editor.set_show_indent_guides(false, cx);
414 let placeholder = placeholder.unwrap_or("Enter commit message".into());
415 commit_editor.set_placeholder_text(placeholder, cx);
416 commit_editor
417}
418
419impl GitPanel {
420 fn new(
421 workspace: &mut Workspace,
422 window: &mut Window,
423 cx: &mut Context<Workspace>,
424 ) -> Entity<Self> {
425 let project = workspace.project().clone();
426 let app_state = workspace.app_state().clone();
427 let fs = app_state.fs.clone();
428 let git_store = project.read(cx).git_store().clone();
429 let active_repository = project.read(cx).active_repository(cx);
430
431 let git_panel = cx.new(|cx| {
432 let focus_handle = cx.focus_handle();
433 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
434 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
435 this.hide_scrollbars(window, cx);
436 })
437 .detach();
438
439 let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
440 cx.observe_global::<SettingsStore>(move |this, cx| {
441 let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
442 if is_sort_by_path != was_sort_by_path {
443 this.update_visible_entries(cx);
444 }
445 was_sort_by_path = is_sort_by_path
446 })
447 .detach();
448
449 // just to let us render a placeholder editor.
450 // Once the active git repo is set, this buffer will be replaced.
451 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
452 let commit_editor = cx.new(|cx| {
453 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
454 });
455
456 commit_editor.update(cx, |editor, cx| {
457 editor.clear(window, cx);
458 });
459
460 let scroll_handle = UniformListScrollHandle::new();
461
462 let vertical_scrollbar = ScrollbarProperties {
463 axis: Axis::Vertical,
464 state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
465 show_scrollbar: false,
466 show_track: false,
467 auto_hide: false,
468 hide_task: None,
469 };
470
471 let horizontal_scrollbar = ScrollbarProperties {
472 axis: Axis::Horizontal,
473 state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),
474 show_scrollbar: false,
475 show_track: false,
476 auto_hide: false,
477 hide_task: None,
478 };
479
480 let mut assistant_enabled = AgentSettings::get_global(cx).enabled;
481 let mut was_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
482 let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {
483 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
484 if assistant_enabled != AgentSettings::get_global(cx).enabled
485 || was_ai_disabled != is_ai_disabled
486 {
487 assistant_enabled = AgentSettings::get_global(cx).enabled;
488 was_ai_disabled = is_ai_disabled;
489 cx.notify();
490 }
491 });
492
493 cx.subscribe_in(
494 &git_store,
495 window,
496 move |this, _git_store, event, window, cx| match event {
497 GitStoreEvent::ActiveRepositoryChanged(_) => {
498 this.active_repository = this.project.read(cx).active_repository(cx);
499 this.schedule_update(true, window, cx);
500 }
501 GitStoreEvent::RepositoryUpdated(
502 _,
503 RepositoryEvent::Updated { full_scan, .. },
504 true,
505 ) => {
506 this.schedule_update(*full_scan, window, cx);
507 }
508
509 GitStoreEvent::RepositoryAdded(_) | GitStoreEvent::RepositoryRemoved(_) => {
510 this.schedule_update(false, window, cx);
511 }
512 GitStoreEvent::IndexWriteError(error) => {
513 this.workspace
514 .update(cx, |workspace, cx| {
515 workspace.show_error(error, cx);
516 })
517 .ok();
518 }
519 GitStoreEvent::RepositoryUpdated(_, _, _) => {}
520 GitStoreEvent::JobsUpdated | GitStoreEvent::ConflictsUpdated => {}
521 },
522 )
523 .detach();
524
525 let mut this = Self {
526 active_repository,
527 commit_editor,
528 conflicted_count: 0,
529 conflicted_staged_count: 0,
530 add_coauthors: true,
531 generate_commit_message_task: None,
532 entries: Vec::new(),
533 focus_handle: cx.focus_handle(),
534 fs,
535 new_count: 0,
536 new_staged_count: 0,
537 pending: Vec::new(),
538 pending_commit: None,
539 amend_pending: false,
540 signoff_enabled: false,
541 pending_serialization: Task::ready(()),
542 single_staged_entry: None,
543 single_tracked_entry: None,
544 project,
545 scroll_handle,
546 max_width_item_index: None,
547 selected_entry: None,
548 marked_entries: Vec::new(),
549 tracked_count: 0,
550 tracked_staged_count: 0,
551 update_visible_entries_task: Task::ready(()),
552 width: None,
553 show_placeholders: false,
554 local_committer: None,
555 local_committer_task: None,
556 context_menu: None,
557 workspace: workspace.weak_handle(),
558 modal_open: false,
559 entry_count: 0,
560 horizontal_scrollbar,
561 vertical_scrollbar,
562 bulk_staging: None,
563 _settings_subscription,
564 };
565
566 this.schedule_update(false, window, cx);
567 this
568 });
569
570 git_panel
571 }
572
573 fn hide_scrollbars(&mut self, window: &mut Window, cx: &mut Context<Self>) {
574 self.horizontal_scrollbar.hide(window, cx);
575 self.vertical_scrollbar.hide(window, cx);
576 }
577
578 fn update_scrollbar_properties(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
579 // TODO: This PR should have defined Editor's `scrollbar.axis`
580 // as an Option<ScrollbarAxis>, not a ScrollbarAxes as it would allow you to
581 // `.unwrap_or(EditorSettings::get_global(cx).scrollbar.show)`.
582 //
583 // Once this is fixed we can extend the GitPanelSettings with a `scrollbar.axis`
584 // so we can show each axis based on the settings.
585 //
586 // We should fix this. PR: https://github.com/zed-industries/zed/pull/19495
587
588 let show_setting = GitPanelSettings::get_global(cx)
589 .scrollbar
590 .show
591 .unwrap_or(EditorSettings::get_global(cx).scrollbar.show);
592
593 let scroll_handle = self.scroll_handle.0.borrow();
594
595 let autohide = |show: ShowScrollbar, cx: &mut Context<Self>| match show {
596 ShowScrollbar::Auto => true,
597 ShowScrollbar::System => cx
598 .try_global::<ScrollbarAutoHide>()
599 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
600 ShowScrollbar::Always => false,
601 ShowScrollbar::Never => false,
602 };
603
604 let longest_item_width = scroll_handle.last_item_size.and_then(|size| {
605 (size.contents.width > size.item.width).then_some(size.contents.width)
606 });
607
608 // is there an item long enough that we should show a horizontal scrollbar?
609 let item_wider_than_container = if let Some(longest_item_width) = longest_item_width {
610 longest_item_width > px(scroll_handle.base_handle.bounds().size.width.0)
611 } else {
612 true
613 };
614
615 let show_horizontal = match (show_setting, item_wider_than_container) {
616 (_, false) => false,
617 (ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always, true) => true,
618 (ShowScrollbar::Never, true) => false,
619 };
620
621 let show_vertical = match show_setting {
622 ShowScrollbar::Auto | ShowScrollbar::System | ShowScrollbar::Always => true,
623 ShowScrollbar::Never => false,
624 };
625
626 let show_horizontal_track =
627 show_horizontal && matches!(show_setting, ShowScrollbar::Always);
628
629 // TODO: we probably should hide the scroll track when the list doesn't need to scroll
630 let show_vertical_track = show_vertical && matches!(show_setting, ShowScrollbar::Always);
631
632 self.vertical_scrollbar = ScrollbarProperties {
633 axis: self.vertical_scrollbar.axis,
634 state: self.vertical_scrollbar.state.clone(),
635 show_scrollbar: show_vertical,
636 show_track: show_vertical_track,
637 auto_hide: autohide(show_setting, cx),
638 hide_task: None,
639 };
640
641 self.horizontal_scrollbar = ScrollbarProperties {
642 axis: self.horizontal_scrollbar.axis,
643 state: self.horizontal_scrollbar.state.clone(),
644 show_scrollbar: show_horizontal,
645 show_track: show_horizontal_track,
646 auto_hide: autohide(show_setting, cx),
647 hide_task: None,
648 };
649
650 cx.notify();
651 }
652
653 pub fn entry_by_path(&self, path: &RepoPath, cx: &App) -> Option<usize> {
654 if GitPanelSettings::get_global(cx).sort_by_path {
655 return self
656 .entries
657 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(&path))
658 .ok();
659 }
660
661 if self.conflicted_count > 0 {
662 let conflicted_start = 1;
663 if let Ok(ix) = self.entries[conflicted_start..conflicted_start + self.conflicted_count]
664 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(&path))
665 {
666 return Some(conflicted_start + ix);
667 }
668 }
669 if self.tracked_count > 0 {
670 let tracked_start = if self.conflicted_count > 0 {
671 1 + self.conflicted_count
672 } else {
673 0
674 } + 1;
675 if let Ok(ix) = self.entries[tracked_start..tracked_start + self.tracked_count]
676 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(&path))
677 {
678 return Some(tracked_start + ix);
679 }
680 }
681 if self.new_count > 0 {
682 let untracked_start = if self.conflicted_count > 0 {
683 1 + self.conflicted_count
684 } else {
685 0
686 } + if self.tracked_count > 0 {
687 1 + self.tracked_count
688 } else {
689 0
690 } + 1;
691 if let Ok(ix) = self.entries[untracked_start..untracked_start + self.new_count]
692 .binary_search_by(|entry| entry.status_entry().unwrap().repo_path.cmp(&path))
693 {
694 return Some(untracked_start + ix);
695 }
696 }
697 None
698 }
699
700 pub fn select_entry_by_path(
701 &mut self,
702 path: ProjectPath,
703 _: &mut Window,
704 cx: &mut Context<Self>,
705 ) {
706 let Some(git_repo) = self.active_repository.as_ref() else {
707 return;
708 };
709 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path, cx) else {
710 return;
711 };
712 let Some(ix) = self.entry_by_path(&repo_path, cx) else {
713 return;
714 };
715 self.selected_entry = Some(ix);
716 cx.notify();
717 }
718
719 fn serialization_key(workspace: &Workspace) -> Option<String> {
720 workspace
721 .database_id()
722 .map(|id| i64::from(id).to_string())
723 .or(workspace.session_id())
724 .map(|id| format!("{}-{:?}", GIT_PANEL_KEY, id))
725 }
726
727 fn serialize(&mut self, cx: &mut Context<Self>) {
728 let width = self.width;
729 let amend_pending = self.amend_pending;
730 let signoff_enabled = self.signoff_enabled;
731
732 self.pending_serialization = cx.spawn(async move |git_panel, cx| {
733 cx.background_executor()
734 .timer(SERIALIZATION_THROTTLE_TIME)
735 .await;
736 let Some(serialization_key) = git_panel
737 .update(cx, |git_panel, cx| {
738 git_panel
739 .workspace
740 .read_with(cx, |workspace, _| Self::serialization_key(workspace))
741 .ok()
742 .flatten()
743 })
744 .ok()
745 .flatten()
746 else {
747 return;
748 };
749 cx.background_spawn(
750 async move {
751 KEY_VALUE_STORE
752 .write_kvp(
753 serialization_key,
754 serde_json::to_string(&SerializedGitPanel {
755 width,
756 amend_pending,
757 signoff_enabled,
758 })?,
759 )
760 .await?;
761 anyhow::Ok(())
762 }
763 .log_err(),
764 )
765 .await;
766 });
767 }
768
769 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
770 self.modal_open = open;
771 cx.notify();
772 }
773
774 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
775 let mut dispatch_context = KeyContext::new_with_defaults();
776 dispatch_context.add("GitPanel");
777
778 if window
779 .focused(cx)
780 .map_or(false, |focused| self.focus_handle == focused)
781 {
782 dispatch_context.add("menu");
783 dispatch_context.add("ChangesList");
784 }
785
786 if self.commit_editor.read(cx).is_focused(window) {
787 dispatch_context.add("CommitEditor");
788 }
789
790 dispatch_context
791 }
792
793 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
794 cx.emit(PanelEvent::Close);
795 }
796
797 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
798 if !self.focus_handle.contains_focused(window, cx) {
799 cx.emit(Event::Focus);
800 }
801 }
802
803 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
804 if let Some(selected_entry) = self.selected_entry {
805 self.scroll_handle
806 .scroll_to_item(selected_entry, ScrollStrategy::Center);
807 }
808
809 cx.notify();
810 }
811
812 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
813 if !self.entries.is_empty() {
814 self.selected_entry = Some(1);
815 self.scroll_to_selected_entry(cx);
816 }
817 }
818
819 fn select_previous(
820 &mut self,
821 _: &SelectPrevious,
822 _window: &mut Window,
823 cx: &mut Context<Self>,
824 ) {
825 let item_count = self.entries.len();
826 if item_count == 0 {
827 return;
828 }
829
830 if let Some(selected_entry) = self.selected_entry {
831 let new_selected_entry = if selected_entry > 0 {
832 selected_entry - 1
833 } else {
834 selected_entry
835 };
836
837 if matches!(
838 self.entries.get(new_selected_entry),
839 Some(GitListEntry::Header(..))
840 ) {
841 if new_selected_entry > 0 {
842 self.selected_entry = Some(new_selected_entry - 1)
843 }
844 } else {
845 self.selected_entry = Some(new_selected_entry);
846 }
847
848 self.scroll_to_selected_entry(cx);
849 }
850
851 cx.notify();
852 }
853
854 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
855 let item_count = self.entries.len();
856 if item_count == 0 {
857 return;
858 }
859
860 if let Some(selected_entry) = self.selected_entry {
861 let new_selected_entry = if selected_entry < item_count - 1 {
862 selected_entry + 1
863 } else {
864 selected_entry
865 };
866 if matches!(
867 self.entries.get(new_selected_entry),
868 Some(GitListEntry::Header(..))
869 ) {
870 self.selected_entry = Some(new_selected_entry + 1);
871 } else {
872 self.selected_entry = Some(new_selected_entry);
873 }
874
875 self.scroll_to_selected_entry(cx);
876 }
877
878 cx.notify();
879 }
880
881 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
882 if self.entries.last().is_some() {
883 self.selected_entry = Some(self.entries.len() - 1);
884 self.scroll_to_selected_entry(cx);
885 }
886 }
887
888 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
889 self.commit_editor.update(cx, |editor, cx| {
890 window.focus(&editor.focus_handle(cx));
891 });
892 cx.notify();
893 }
894
895 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
896 let have_entries = self
897 .active_repository
898 .as_ref()
899 .map_or(false, |active_repository| {
900 active_repository.read(cx).status_summary().count > 0
901 });
902 if have_entries && self.selected_entry.is_none() {
903 self.selected_entry = Some(1);
904 self.scroll_to_selected_entry(cx);
905 cx.notify();
906 }
907 }
908
909 fn focus_changes_list(
910 &mut self,
911 _: &FocusChanges,
912 window: &mut Window,
913 cx: &mut Context<Self>,
914 ) {
915 self.select_first_entry_if_none(cx);
916
917 cx.focus_self(window);
918 cx.notify();
919 }
920
921 fn get_selected_entry(&self) -> Option<&GitListEntry> {
922 self.selected_entry.and_then(|i| self.entries.get(i))
923 }
924
925 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
926 maybe!({
927 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
928 let workspace = self.workspace.upgrade()?;
929 let git_repo = self.active_repository.as_ref()?;
930
931 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
932 if let Some(project_path) = project_diff.read(cx).active_path(cx) {
933 if Some(&entry.repo_path)
934 == git_repo
935 .read(cx)
936 .project_path_to_repo_path(&project_path, cx)
937 .as_ref()
938 {
939 project_diff.focus_handle(cx).focus(window);
940 project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
941 return None;
942 }
943 }
944 };
945
946 self.workspace
947 .update(cx, |workspace, cx| {
948 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
949 })
950 .ok();
951 self.focus_handle.focus(window);
952
953 Some(())
954 });
955 }
956
957 fn open_file(
958 &mut self,
959 _: &menu::SecondaryConfirm,
960 window: &mut Window,
961 cx: &mut Context<Self>,
962 ) {
963 maybe!({
964 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
965 let active_repo = self.active_repository.as_ref()?;
966 let path = active_repo
967 .read(cx)
968 .repo_path_to_project_path(&entry.repo_path, cx)?;
969 if entry.status.is_deleted() {
970 return None;
971 }
972
973 self.workspace
974 .update(cx, |workspace, cx| {
975 workspace
976 .open_path_preview(path, None, false, false, true, window, cx)
977 .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
978 Some(format!("{e}"))
979 });
980 })
981 .ok()
982 });
983 }
984
985 fn revert_selected(
986 &mut self,
987 action: &git::RestoreFile,
988 window: &mut Window,
989 cx: &mut Context<Self>,
990 ) {
991 maybe!({
992 let list_entry = self.entries.get(self.selected_entry?)?.clone();
993 let entry = list_entry.status_entry()?.to_owned();
994 let skip_prompt = action.skip_prompt || entry.status.is_created();
995
996 let prompt = if skip_prompt {
997 Task::ready(Ok(0))
998 } else {
999 let prompt = window.prompt(
1000 PromptLevel::Warning,
1001 &format!(
1002 "Are you sure you want to restore {}?",
1003 entry
1004 .repo_path
1005 .file_name()
1006 .unwrap_or(entry.repo_path.as_os_str())
1007 .to_string_lossy()
1008 ),
1009 None,
1010 &["Restore", "Cancel"],
1011 cx,
1012 );
1013 cx.background_spawn(prompt)
1014 };
1015
1016 let this = cx.weak_entity();
1017 window
1018 .spawn(cx, async move |cx| {
1019 if prompt.await? != 0 {
1020 return anyhow::Ok(());
1021 }
1022
1023 this.update_in(cx, |this, window, cx| {
1024 this.revert_entry(&entry, window, cx);
1025 })?;
1026
1027 Ok(())
1028 })
1029 .detach();
1030 Some(())
1031 });
1032 }
1033
1034 fn revert_entry(
1035 &mut self,
1036 entry: &GitStatusEntry,
1037 window: &mut Window,
1038 cx: &mut Context<Self>,
1039 ) {
1040 maybe!({
1041 let active_repo = self.active_repository.clone()?;
1042 let path = active_repo
1043 .read(cx)
1044 .repo_path_to_project_path(&entry.repo_path, cx)?;
1045 let workspace = self.workspace.clone();
1046
1047 if entry.status.staging().has_staged() {
1048 self.change_file_stage(false, vec![entry.clone()], cx);
1049 }
1050 let filename = path.path.file_name()?.to_string_lossy();
1051
1052 if !entry.status.is_created() {
1053 self.perform_checkout(vec![entry.clone()], cx);
1054 } else {
1055 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
1056 cx.spawn_in(window, async move |_, cx| {
1057 match prompt.await? {
1058 TrashCancel::Trash => {}
1059 TrashCancel::Cancel => return Ok(()),
1060 }
1061 let task = workspace.update(cx, |workspace, cx| {
1062 workspace
1063 .project()
1064 .update(cx, |project, cx| project.delete_file(path, true, cx))
1065 })?;
1066 if let Some(task) = task {
1067 task.await?;
1068 }
1069 Ok(())
1070 })
1071 .detach_and_prompt_err(
1072 "Failed to trash file",
1073 window,
1074 cx,
1075 |e, _, _| Some(format!("{e}")),
1076 );
1077 }
1078 Some(())
1079 });
1080 }
1081
1082 fn perform_checkout(&mut self, entries: Vec<GitStatusEntry>, cx: &mut Context<Self>) {
1083 let workspace = self.workspace.clone();
1084 let Some(active_repository) = self.active_repository.clone() else {
1085 return;
1086 };
1087
1088 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1089 self.pending.push(PendingOperation {
1090 op_id,
1091 target_status: TargetStatus::Reverted,
1092 entries: entries.clone(),
1093 finished: false,
1094 });
1095 self.update_visible_entries(cx);
1096 let task = cx.spawn(async move |_, cx| {
1097 let tasks: Vec<_> = workspace.update(cx, |workspace, cx| {
1098 workspace.project().update(cx, |project, cx| {
1099 entries
1100 .iter()
1101 .filter_map(|entry| {
1102 let path = active_repository
1103 .read(cx)
1104 .repo_path_to_project_path(&entry.repo_path, cx)?;
1105 Some(project.open_buffer(path, cx))
1106 })
1107 .collect()
1108 })
1109 })?;
1110
1111 let buffers = futures::future::join_all(tasks).await;
1112
1113 active_repository
1114 .update(cx, |repo, cx| {
1115 repo.checkout_files(
1116 "HEAD",
1117 entries
1118 .into_iter()
1119 .map(|entries| entries.repo_path)
1120 .collect(),
1121 cx,
1122 )
1123 })?
1124 .await??;
1125
1126 let tasks: Vec<_> = cx.update(|cx| {
1127 buffers
1128 .iter()
1129 .filter_map(|buffer| {
1130 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
1131 buffer.is_dirty().then(|| buffer.reload(cx))
1132 })
1133 })
1134 .collect()
1135 })?;
1136
1137 futures::future::join_all(tasks).await;
1138
1139 Ok(())
1140 });
1141
1142 cx.spawn(async move |this, cx| {
1143 let result = task.await;
1144
1145 this.update(cx, |this, cx| {
1146 for pending in this.pending.iter_mut() {
1147 if pending.op_id == op_id {
1148 pending.finished = true;
1149 if result.is_err() {
1150 pending.target_status = TargetStatus::Unchanged;
1151 this.update_visible_entries(cx);
1152 }
1153 break;
1154 }
1155 }
1156 result
1157 .map_err(|e| {
1158 this.show_error_toast("checkout", e, cx);
1159 })
1160 .ok();
1161 })
1162 .ok();
1163 })
1164 .detach();
1165 }
1166
1167 fn restore_tracked_files(
1168 &mut self,
1169 _: &RestoreTrackedFiles,
1170 window: &mut Window,
1171 cx: &mut Context<Self>,
1172 ) {
1173 let entries = self
1174 .entries
1175 .iter()
1176 .filter_map(|entry| entry.status_entry().cloned())
1177 .filter(|status_entry| !status_entry.status.is_created())
1178 .collect::<Vec<_>>();
1179
1180 match entries.len() {
1181 0 => return,
1182 1 => return self.revert_entry(&entries[0], window, cx),
1183 _ => {}
1184 }
1185 let mut details = entries
1186 .iter()
1187 .filter_map(|entry| entry.repo_path.0.file_name())
1188 .map(|filename| filename.to_string_lossy())
1189 .take(5)
1190 .join("\n");
1191 if entries.len() > 5 {
1192 details.push_str(&format!("\nand {} more…", entries.len() - 5))
1193 }
1194
1195 #[derive(strum::EnumIter, strum::VariantNames)]
1196 #[strum(serialize_all = "title_case")]
1197 enum RestoreCancel {
1198 RestoreTrackedFiles,
1199 Cancel,
1200 }
1201 let prompt = prompt(
1202 "Discard changes to these files?",
1203 Some(&details),
1204 window,
1205 cx,
1206 );
1207 cx.spawn(async move |this, cx| match prompt.await {
1208 Ok(RestoreCancel::RestoreTrackedFiles) => {
1209 this.update(cx, |this, cx| {
1210 this.perform_checkout(entries, cx);
1211 })
1212 .ok();
1213 }
1214 _ => {
1215 return;
1216 }
1217 })
1218 .detach();
1219 }
1220
1221 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1222 let workspace = self.workspace.clone();
1223 let Some(active_repo) = self.active_repository.clone() else {
1224 return;
1225 };
1226 let to_delete = self
1227 .entries
1228 .iter()
1229 .filter_map(|entry| entry.status_entry())
1230 .filter(|status_entry| status_entry.status.is_created())
1231 .cloned()
1232 .collect::<Vec<_>>();
1233
1234 match to_delete.len() {
1235 0 => return,
1236 1 => return self.revert_entry(&to_delete[0], window, cx),
1237 _ => {}
1238 };
1239
1240 let mut details = to_delete
1241 .iter()
1242 .map(|entry| {
1243 entry
1244 .repo_path
1245 .0
1246 .file_name()
1247 .map(|f| f.to_string_lossy())
1248 .unwrap_or_default()
1249 })
1250 .take(5)
1251 .join("\n");
1252
1253 if to_delete.len() > 5 {
1254 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1255 }
1256
1257 let prompt = prompt("Trash these files?", Some(&details), window, cx);
1258 cx.spawn_in(window, async move |this, cx| {
1259 match prompt.await? {
1260 TrashCancel::Trash => {}
1261 TrashCancel::Cancel => return Ok(()),
1262 }
1263 let tasks = workspace.update(cx, |workspace, cx| {
1264 to_delete
1265 .iter()
1266 .filter_map(|entry| {
1267 workspace.project().update(cx, |project, cx| {
1268 let project_path = active_repo
1269 .read(cx)
1270 .repo_path_to_project_path(&entry.repo_path, cx)?;
1271 project.delete_file(project_path, true, cx)
1272 })
1273 })
1274 .collect::<Vec<_>>()
1275 })?;
1276 let to_unstage = to_delete
1277 .into_iter()
1278 .filter(|entry| !entry.status.staging().is_fully_unstaged())
1279 .collect();
1280 this.update(cx, |this, cx| this.change_file_stage(false, to_unstage, cx))?;
1281 for task in tasks {
1282 task.await?;
1283 }
1284 Ok(())
1285 })
1286 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1287 Some(format!("{e}"))
1288 });
1289 }
1290
1291 pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1292 let entries = self
1293 .entries
1294 .iter()
1295 .filter_map(|entry| entry.status_entry())
1296 .filter(|status_entry| status_entry.staging.has_unstaged())
1297 .cloned()
1298 .collect::<Vec<_>>();
1299 self.change_file_stage(true, entries, cx);
1300 }
1301
1302 pub fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1303 let entries = self
1304 .entries
1305 .iter()
1306 .filter_map(|entry| entry.status_entry())
1307 .filter(|status_entry| status_entry.staging.has_staged())
1308 .cloned()
1309 .collect::<Vec<_>>();
1310 self.change_file_stage(false, entries, cx);
1311 }
1312
1313 fn toggle_staged_for_entry(
1314 &mut self,
1315 entry: &GitListEntry,
1316 _window: &mut Window,
1317 cx: &mut Context<Self>,
1318 ) {
1319 let Some(active_repository) = self.active_repository.as_ref() else {
1320 return;
1321 };
1322 let (stage, repo_paths) = match entry {
1323 GitListEntry::Status(status_entry) => {
1324 if status_entry.status.staging().is_fully_staged() {
1325 if let Some(op) = self.bulk_staging.clone()
1326 && op.anchor == status_entry.repo_path
1327 {
1328 self.bulk_staging = None;
1329 }
1330
1331 (false, vec![status_entry.clone()])
1332 } else {
1333 self.set_bulk_staging_anchor(status_entry.repo_path.clone(), cx);
1334
1335 (true, vec![status_entry.clone()])
1336 }
1337 }
1338 GitListEntry::Header(section) => {
1339 let goal_staged_state = !self.header_state(section.header).selected();
1340 let repository = active_repository.read(cx);
1341 let entries = self
1342 .entries
1343 .iter()
1344 .filter_map(|entry| entry.status_entry())
1345 .filter(|status_entry| {
1346 section.contains(&status_entry, repository)
1347 && status_entry.staging.as_bool() != Some(goal_staged_state)
1348 })
1349 .map(|status_entry| status_entry.clone())
1350 .collect::<Vec<_>>();
1351
1352 (goal_staged_state, entries)
1353 }
1354 };
1355 self.change_file_stage(stage, repo_paths, cx);
1356 }
1357
1358 fn change_file_stage(
1359 &mut self,
1360 stage: bool,
1361 entries: Vec<GitStatusEntry>,
1362 cx: &mut Context<Self>,
1363 ) {
1364 let Some(active_repository) = self.active_repository.clone() else {
1365 return;
1366 };
1367 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1368 self.pending.push(PendingOperation {
1369 op_id,
1370 target_status: if stage {
1371 TargetStatus::Staged
1372 } else {
1373 TargetStatus::Unstaged
1374 },
1375 entries: entries.clone(),
1376 finished: false,
1377 });
1378 let repository = active_repository.read(cx);
1379 self.update_counts(repository);
1380 cx.notify();
1381
1382 cx.spawn({
1383 async move |this, cx| {
1384 let result = cx
1385 .update(|cx| {
1386 if stage {
1387 active_repository.update(cx, |repo, cx| {
1388 let repo_paths = entries
1389 .iter()
1390 .map(|entry| entry.repo_path.clone())
1391 .collect();
1392 repo.stage_entries(repo_paths, cx)
1393 })
1394 } else {
1395 active_repository.update(cx, |repo, cx| {
1396 let repo_paths = entries
1397 .iter()
1398 .map(|entry| entry.repo_path.clone())
1399 .collect();
1400 repo.unstage_entries(repo_paths, cx)
1401 })
1402 }
1403 })?
1404 .await;
1405
1406 this.update(cx, |this, cx| {
1407 for pending in this.pending.iter_mut() {
1408 if pending.op_id == op_id {
1409 pending.finished = true
1410 }
1411 }
1412 result
1413 .map_err(|e| {
1414 this.show_error_toast(if stage { "add" } else { "reset" }, e, cx);
1415 })
1416 .ok();
1417 cx.notify();
1418 })
1419 }
1420 })
1421 .detach();
1422 }
1423
1424 pub fn total_staged_count(&self) -> usize {
1425 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1426 }
1427
1428 pub fn stash_pop(&mut self, _: &StashPop, _window: &mut Window, cx: &mut Context<Self>) {
1429 let Some(active_repository) = self.active_repository.clone() else {
1430 return;
1431 };
1432
1433 cx.spawn({
1434 async move |this, cx| {
1435 let stash_task = active_repository
1436 .update(cx, |repo, cx| repo.stash_pop(cx))?
1437 .await;
1438 this.update(cx, |this, cx| {
1439 stash_task
1440 .map_err(|e| {
1441 this.show_error_toast("stash pop", e, cx);
1442 })
1443 .ok();
1444 cx.notify();
1445 })
1446 }
1447 })
1448 .detach();
1449 }
1450
1451 pub fn stash_all(&mut self, _: &StashAll, _window: &mut Window, cx: &mut Context<Self>) {
1452 let Some(active_repository) = self.active_repository.clone() else {
1453 return;
1454 };
1455
1456 cx.spawn({
1457 async move |this, cx| {
1458 let stash_task = active_repository
1459 .update(cx, |repo, cx| repo.stash_all(cx))?
1460 .await;
1461 this.update(cx, |this, cx| {
1462 stash_task
1463 .map_err(|e| {
1464 this.show_error_toast("stash", e, cx);
1465 })
1466 .ok();
1467 cx.notify();
1468 })
1469 }
1470 })
1471 .detach();
1472 }
1473
1474 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1475 self.commit_editor
1476 .read(cx)
1477 .buffer()
1478 .read(cx)
1479 .as_singleton()
1480 .unwrap()
1481 .clone()
1482 }
1483
1484 fn toggle_staged_for_selected(
1485 &mut self,
1486 _: &git::ToggleStaged,
1487 window: &mut Window,
1488 cx: &mut Context<Self>,
1489 ) {
1490 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1491 self.toggle_staged_for_entry(&selected_entry, window, cx);
1492 }
1493 }
1494
1495 fn stage_range(&mut self, _: &git::StageRange, _window: &mut Window, cx: &mut Context<Self>) {
1496 let Some(index) = self.selected_entry else {
1497 return;
1498 };
1499 self.stage_bulk(index, cx);
1500 }
1501
1502 fn stage_selected(&mut self, _: &git::StageFile, _window: &mut Window, cx: &mut Context<Self>) {
1503 let Some(selected_entry) = self.get_selected_entry() else {
1504 return;
1505 };
1506 let Some(status_entry) = selected_entry.status_entry() else {
1507 return;
1508 };
1509 if status_entry.staging != StageStatus::Staged {
1510 self.change_file_stage(true, vec![status_entry.clone()], cx);
1511 }
1512 }
1513
1514 fn unstage_selected(
1515 &mut self,
1516 _: &git::UnstageFile,
1517 _window: &mut Window,
1518 cx: &mut Context<Self>,
1519 ) {
1520 let Some(selected_entry) = self.get_selected_entry() else {
1521 return;
1522 };
1523 let Some(status_entry) = selected_entry.status_entry() else {
1524 return;
1525 };
1526 if status_entry.staging != StageStatus::Unstaged {
1527 self.change_file_stage(false, vec![status_entry.clone()], cx);
1528 }
1529 }
1530
1531 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1532 if self.amend_pending {
1533 return;
1534 }
1535 if self
1536 .commit_editor
1537 .focus_handle(cx)
1538 .contains_focused(window, cx)
1539 {
1540 telemetry::event!("Git Committed", source = "Git Panel");
1541 self.commit_changes(
1542 CommitOptions {
1543 amend: false,
1544 signoff: self.signoff_enabled,
1545 },
1546 window,
1547 cx,
1548 )
1549 } else {
1550 cx.propagate();
1551 }
1552 }
1553
1554 fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
1555 if self
1556 .commit_editor
1557 .focus_handle(cx)
1558 .contains_focused(window, cx)
1559 {
1560 if self.head_commit(cx).is_some() {
1561 if !self.amend_pending {
1562 self.set_amend_pending(true, cx);
1563 self.load_last_commit_message_if_empty(cx);
1564 } else {
1565 telemetry::event!("Git Amended", source = "Git Panel");
1566 self.set_amend_pending(false, cx);
1567 self.commit_changes(
1568 CommitOptions {
1569 amend: true,
1570 signoff: self.signoff_enabled,
1571 },
1572 window,
1573 cx,
1574 );
1575 }
1576 }
1577 } else {
1578 cx.propagate();
1579 }
1580 }
1581
1582 pub fn head_commit(&self, cx: &App) -> Option<CommitDetails> {
1583 self.active_repository
1584 .as_ref()
1585 .and_then(|repo| repo.read(cx).head_commit.as_ref())
1586 .cloned()
1587 }
1588
1589 pub fn load_last_commit_message_if_empty(&mut self, cx: &mut Context<Self>) {
1590 if !self.commit_editor.read(cx).is_empty(cx) {
1591 return;
1592 }
1593 let Some(head_commit) = self.head_commit(cx) else {
1594 return;
1595 };
1596 let recent_sha = head_commit.sha.to_string();
1597 let detail_task = self.load_commit_details(recent_sha, cx);
1598 cx.spawn(async move |this, cx| {
1599 if let Ok(message) = detail_task.await.map(|detail| detail.message) {
1600 this.update(cx, |this, cx| {
1601 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1602 let start = buffer.anchor_before(0);
1603 let end = buffer.anchor_after(buffer.len());
1604 buffer.edit([(start..end, message)], None, cx);
1605 });
1606 })
1607 .log_err();
1608 }
1609 })
1610 .detach();
1611 }
1612
1613 fn custom_or_suggested_commit_message(
1614 &self,
1615 window: &mut Window,
1616 cx: &mut Context<Self>,
1617 ) -> Option<String> {
1618 let git_commit_language = self.commit_editor.read(cx).language_at(0, cx);
1619 let message = self.commit_editor.read(cx).text(cx);
1620 if message.is_empty() {
1621 return self
1622 .suggest_commit_message(cx)
1623 .filter(|message| !message.trim().is_empty());
1624 } else if message.trim().is_empty() {
1625 return None;
1626 }
1627 let buffer = cx.new(|cx| {
1628 let mut buffer = Buffer::local(message, cx);
1629 buffer.set_language(git_commit_language, cx);
1630 buffer
1631 });
1632 let editor = cx.new(|cx| Editor::for_buffer(buffer, None, window, cx));
1633 let wrapped_message = editor.update(cx, |editor, cx| {
1634 editor.select_all(&Default::default(), window, cx);
1635 editor.rewrap(&Default::default(), window, cx);
1636 editor.text(cx)
1637 });
1638 if wrapped_message.trim().is_empty() {
1639 return None;
1640 }
1641 Some(wrapped_message)
1642 }
1643
1644 fn has_commit_message(&self, cx: &mut Context<Self>) -> bool {
1645 let text = self.commit_editor.read(cx).text(cx);
1646 if !text.trim().is_empty() {
1647 return true;
1648 } else if text.is_empty() {
1649 return self
1650 .suggest_commit_message(cx)
1651 .is_some_and(|text| !text.trim().is_empty());
1652 } else {
1653 return false;
1654 }
1655 }
1656
1657 pub(crate) fn commit_changes(
1658 &mut self,
1659 options: CommitOptions,
1660 window: &mut Window,
1661 cx: &mut Context<Self>,
1662 ) {
1663 let Some(active_repository) = self.active_repository.clone() else {
1664 return;
1665 };
1666 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1667 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1668 cx.spawn(async move |_| {
1669 prompt.await.ok();
1670 })
1671 .detach();
1672 };
1673
1674 if self.has_unstaged_conflicts() {
1675 error_spawn(
1676 "There are still conflicts. You must stage these before committing",
1677 window,
1678 cx,
1679 );
1680 return;
1681 }
1682
1683 let commit_message = self.custom_or_suggested_commit_message(window, cx);
1684
1685 let Some(mut message) = commit_message else {
1686 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1687 return;
1688 };
1689
1690 if self.add_coauthors {
1691 self.fill_co_authors(&mut message, cx);
1692 }
1693
1694 let task = if self.has_staged_changes() {
1695 // Repository serializes all git operations, so we can just send a commit immediately
1696 let commit_task = active_repository.update(cx, |repo, cx| {
1697 repo.commit(message.into(), None, options, cx)
1698 });
1699 cx.background_spawn(async move { commit_task.await? })
1700 } else {
1701 let changed_files = self
1702 .entries
1703 .iter()
1704 .filter_map(|entry| entry.status_entry())
1705 .filter(|status_entry| !status_entry.status.is_created())
1706 .map(|status_entry| status_entry.repo_path.clone())
1707 .collect::<Vec<_>>();
1708
1709 if changed_files.is_empty() {
1710 error_spawn("No changes to commit", window, cx);
1711 return;
1712 }
1713
1714 let stage_task =
1715 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1716 cx.spawn(async move |_, cx| {
1717 stage_task.await?;
1718 let commit_task = active_repository.update(cx, |repo, cx| {
1719 repo.commit(message.into(), None, options, cx)
1720 })?;
1721 commit_task.await?
1722 })
1723 };
1724 let task = cx.spawn_in(window, async move |this, cx| {
1725 let result = task.await;
1726 this.update_in(cx, |this, window, cx| {
1727 this.pending_commit.take();
1728 match result {
1729 Ok(()) => {
1730 this.commit_editor
1731 .update(cx, |editor, cx| editor.clear(window, cx));
1732 }
1733 Err(e) => this.show_error_toast("commit", e, cx),
1734 }
1735 })
1736 .ok();
1737 });
1738
1739 self.pending_commit = Some(task);
1740 }
1741
1742 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1743 let Some(repo) = self.active_repository.clone() else {
1744 return;
1745 };
1746 telemetry::event!("Git Uncommitted");
1747
1748 let confirmation = self.check_for_pushed_commits(window, cx);
1749 let prior_head = self.load_commit_details("HEAD".to_string(), cx);
1750
1751 let task = cx.spawn_in(window, async move |this, cx| {
1752 let result = maybe!(async {
1753 if let Ok(true) = confirmation.await {
1754 let prior_head = prior_head.await?;
1755
1756 repo.update(cx, |repo, cx| {
1757 repo.reset("HEAD^".to_string(), ResetMode::Soft, cx)
1758 })?
1759 .await??;
1760
1761 Ok(Some(prior_head))
1762 } else {
1763 Ok(None)
1764 }
1765 })
1766 .await;
1767
1768 this.update_in(cx, |this, window, cx| {
1769 this.pending_commit.take();
1770 match result {
1771 Ok(None) => {}
1772 Ok(Some(prior_commit)) => {
1773 this.commit_editor.update(cx, |editor, cx| {
1774 editor.set_text(prior_commit.message, window, cx)
1775 });
1776 }
1777 Err(e) => this.show_error_toast("reset", e, cx),
1778 }
1779 })
1780 .ok();
1781 });
1782
1783 self.pending_commit = Some(task);
1784 }
1785
1786 fn check_for_pushed_commits(
1787 &mut self,
1788 window: &mut Window,
1789 cx: &mut Context<Self>,
1790 ) -> impl Future<Output = anyhow::Result<bool>> + use<> {
1791 let repo = self.active_repository.clone();
1792 let mut cx = window.to_async(cx);
1793
1794 async move {
1795 let repo = repo.context("No active repository")?;
1796
1797 let pushed_to: Vec<SharedString> = repo
1798 .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1799 .await??;
1800
1801 if pushed_to.is_empty() {
1802 Ok(true)
1803 } else {
1804 #[derive(strum::EnumIter, strum::VariantNames)]
1805 #[strum(serialize_all = "title_case")]
1806 enum CancelUncommit {
1807 Uncommit,
1808 Cancel,
1809 }
1810 let detail = format!(
1811 "This commit was already pushed to {}.",
1812 pushed_to.into_iter().join(", ")
1813 );
1814 let result = cx
1815 .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1816 .await?;
1817
1818 match result {
1819 CancelUncommit::Cancel => Ok(false),
1820 CancelUncommit::Uncommit => Ok(true),
1821 }
1822 }
1823 }
1824 }
1825
1826 /// Suggests a commit message based on the changed files and their statuses
1827 pub fn suggest_commit_message(&self, cx: &App) -> Option<String> {
1828 if let Some(merge_message) = self
1829 .active_repository
1830 .as_ref()
1831 .and_then(|repo| repo.read(cx).merge.message.as_ref())
1832 {
1833 return Some(merge_message.to_string());
1834 }
1835
1836 let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1837 Some(staged_entry)
1838 } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1839 Some(single_tracked_entry)
1840 } else {
1841 None
1842 }?;
1843
1844 let action_text = if git_status_entry.status.is_deleted() {
1845 Some("Delete")
1846 } else if git_status_entry.status.is_created() {
1847 Some("Create")
1848 } else if git_status_entry.status.is_modified() {
1849 Some("Update")
1850 } else {
1851 None
1852 }?;
1853
1854 let file_name = git_status_entry
1855 .repo_path
1856 .file_name()
1857 .unwrap_or_default()
1858 .to_string_lossy();
1859
1860 Some(format!("{} {}", action_text, file_name))
1861 }
1862
1863 fn generate_commit_message_action(
1864 &mut self,
1865 _: &git::GenerateCommitMessage,
1866 _window: &mut Window,
1867 cx: &mut Context<Self>,
1868 ) {
1869 self.generate_commit_message(cx);
1870 }
1871
1872 /// Generates a commit message using an LLM.
1873 pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1874 if !self.can_commit() || DisableAiSettings::get_global(cx).disable_ai {
1875 return;
1876 }
1877
1878 let model = match current_language_model(cx) {
1879 Some(value) => value,
1880 None => return,
1881 };
1882
1883 let Some(repo) = self.active_repository.as_ref() else {
1884 return;
1885 };
1886
1887 telemetry::event!("Git Commit Message Generated");
1888
1889 let diff = repo.update(cx, |repo, cx| {
1890 if self.has_staged_changes() {
1891 repo.diff(DiffType::HeadToIndex, cx)
1892 } else {
1893 repo.diff(DiffType::HeadToWorktree, cx)
1894 }
1895 });
1896
1897 let temperature = AgentSettings::temperature_for_model(&model, cx);
1898
1899 self.generate_commit_message_task = Some(cx.spawn(async move |this, cx| {
1900 async move {
1901 let _defer = cx.on_drop(&this, |this, _cx| {
1902 this.generate_commit_message_task.take();
1903 });
1904
1905 let mut diff_text = match diff.await {
1906 Ok(result) => match result {
1907 Ok(text) => text,
1908 Err(e) => {
1909 Self::show_commit_message_error(&this, &e, cx);
1910 return anyhow::Ok(());
1911 }
1912 },
1913 Err(e) => {
1914 Self::show_commit_message_error(&this, &e, cx);
1915 return anyhow::Ok(());
1916 }
1917 };
1918
1919 const ONE_MB: usize = 1_000_000;
1920 if diff_text.len() > ONE_MB {
1921 diff_text = diff_text.chars().take(ONE_MB).collect()
1922 }
1923
1924 let subject = this.update(cx, |this, cx| {
1925 this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1926 })?;
1927
1928 let text_empty = subject.trim().is_empty();
1929
1930 let content = if text_empty {
1931 format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1932 } else {
1933 format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1934 };
1935
1936 const PROMPT: &str = include_str!("commit_message_prompt.txt");
1937
1938 let request = LanguageModelRequest {
1939 thread_id: None,
1940 prompt_id: None,
1941 intent: Some(CompletionIntent::GenerateGitCommitMessage),
1942 mode: None,
1943 messages: vec![LanguageModelRequestMessage {
1944 role: Role::User,
1945 content: vec![content.into()],
1946 cache: false,
1947 }],
1948 tools: Vec::new(),
1949 tool_choice: None,
1950 stop: Vec::new(),
1951 temperature,
1952 thinking_allowed: false,
1953 };
1954
1955 let stream = model.stream_completion_text(request, &cx);
1956 match stream.await {
1957 Ok(mut messages) => {
1958 if !text_empty {
1959 this.update(cx, |this, cx| {
1960 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1961 let insert_position = buffer.anchor_before(buffer.len());
1962 buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1963 });
1964 })?;
1965 }
1966
1967 while let Some(message) = messages.stream.next().await {
1968 match message {
1969 Ok(text) => {
1970 this.update(cx, |this, cx| {
1971 this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1972 let insert_position = buffer.anchor_before(buffer.len());
1973 buffer.edit([(insert_position..insert_position, text)], None, cx);
1974 });
1975 })?;
1976 }
1977 Err(e) => {
1978 Self::show_commit_message_error(&this, &e, cx);
1979 break;
1980 }
1981 }
1982 }
1983 }
1984 Err(e) => {
1985 Self::show_commit_message_error(&this, &e, cx);
1986 }
1987 }
1988
1989 anyhow::Ok(())
1990 }
1991 .log_err().await
1992 }));
1993 }
1994
1995 fn get_fetch_options(
1996 &self,
1997 window: &mut Window,
1998 cx: &mut Context<Self>,
1999 ) -> Task<Option<FetchOptions>> {
2000 let repo = self.active_repository.clone();
2001 let workspace = self.workspace.clone();
2002
2003 cx.spawn_in(window, async move |_, cx| {
2004 let repo = repo?;
2005 let remotes = repo
2006 .update(cx, |repo, _| repo.get_remotes(None))
2007 .ok()?
2008 .await
2009 .ok()?
2010 .log_err()?;
2011
2012 let mut remotes: Vec<_> = remotes.into_iter().map(FetchOptions::Remote).collect();
2013 if remotes.len() > 1 {
2014 remotes.push(FetchOptions::All);
2015 }
2016 let selection = cx
2017 .update(|window, cx| {
2018 picker_prompt::prompt(
2019 "Pick which remote to fetch",
2020 remotes.iter().map(|r| r.name()).collect(),
2021 workspace,
2022 window,
2023 cx,
2024 )
2025 })
2026 .ok()?
2027 .await?;
2028 remotes.get(selection).cloned()
2029 })
2030 }
2031
2032 pub(crate) fn fetch(
2033 &mut self,
2034 is_fetch_all: bool,
2035 window: &mut Window,
2036 cx: &mut Context<Self>,
2037 ) {
2038 if !self.can_push_and_pull(cx) {
2039 return;
2040 }
2041
2042 let Some(repo) = self.active_repository.clone() else {
2043 return;
2044 };
2045 telemetry::event!("Git Fetched");
2046 let askpass = self.askpass_delegate("git fetch", window, cx);
2047 let this = cx.weak_entity();
2048
2049 let fetch_options = if is_fetch_all {
2050 Task::ready(Some(FetchOptions::All))
2051 } else {
2052 self.get_fetch_options(window, cx)
2053 };
2054
2055 window
2056 .spawn(cx, async move |cx| {
2057 let Some(fetch_options) = fetch_options.await else {
2058 return Ok(());
2059 };
2060 let fetch = repo.update(cx, |repo, cx| {
2061 repo.fetch(fetch_options.clone(), askpass, cx)
2062 })?;
2063
2064 let remote_message = fetch.await?;
2065 this.update(cx, |this, cx| {
2066 let action = match fetch_options {
2067 FetchOptions::All => RemoteAction::Fetch(None),
2068 FetchOptions::Remote(remote) => RemoteAction::Fetch(Some(remote)),
2069 };
2070 match remote_message {
2071 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2072 Err(e) => {
2073 log::error!("Error while fetching {:?}", e);
2074 this.show_error_toast(action.name(), e, cx)
2075 }
2076 }
2077
2078 anyhow::Ok(())
2079 })
2080 .ok();
2081 anyhow::Ok(())
2082 })
2083 .detach_and_log_err(cx);
2084 }
2085
2086 pub(crate) fn git_init(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2087 let worktrees = self
2088 .project
2089 .read(cx)
2090 .visible_worktrees(cx)
2091 .collect::<Vec<_>>();
2092
2093 let worktree = if worktrees.len() == 1 {
2094 Task::ready(Some(worktrees.first().unwrap().clone()))
2095 } else if worktrees.len() == 0 {
2096 let result = window.prompt(
2097 PromptLevel::Warning,
2098 "Unable to initialize a git repository",
2099 Some("Open a directory first"),
2100 &["Ok"],
2101 cx,
2102 );
2103 cx.background_executor()
2104 .spawn(async move {
2105 result.await.ok();
2106 })
2107 .detach();
2108 return;
2109 } else {
2110 let worktree_directories = worktrees
2111 .iter()
2112 .map(|worktree| worktree.read(cx).abs_path())
2113 .map(|worktree_abs_path| {
2114 if let Ok(path) = worktree_abs_path.strip_prefix(util::paths::home_dir()) {
2115 Path::new("~")
2116 .join(path)
2117 .to_string_lossy()
2118 .to_string()
2119 .into()
2120 } else {
2121 worktree_abs_path.to_string_lossy().to_string().into()
2122 }
2123 })
2124 .collect_vec();
2125 let prompt = picker_prompt::prompt(
2126 "Where would you like to initialize this git repository?",
2127 worktree_directories,
2128 self.workspace.clone(),
2129 window,
2130 cx,
2131 );
2132
2133 cx.spawn(async move |_, _| prompt.await.map(|ix| worktrees[ix].clone()))
2134 };
2135
2136 cx.spawn_in(window, async move |this, cx| {
2137 let worktree = match worktree.await {
2138 Some(worktree) => worktree,
2139 None => {
2140 return;
2141 }
2142 };
2143
2144 let Ok(result) = this.update(cx, |this, cx| {
2145 let fallback_branch_name = GitPanelSettings::get_global(cx)
2146 .fallback_branch_name
2147 .clone();
2148 this.project.read(cx).git_init(
2149 worktree.read(cx).abs_path(),
2150 fallback_branch_name,
2151 cx,
2152 )
2153 }) else {
2154 return;
2155 };
2156
2157 let result = result.await;
2158
2159 this.update_in(cx, |this, _, cx| match result {
2160 Ok(()) => {}
2161 Err(e) => this.show_error_toast("init", e, cx),
2162 })
2163 .ok();
2164 })
2165 .detach();
2166 }
2167
2168 pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2169 if !self.can_push_and_pull(cx) {
2170 return;
2171 }
2172 let Some(repo) = self.active_repository.clone() else {
2173 return;
2174 };
2175 let Some(branch) = repo.read(cx).branch.as_ref() else {
2176 return;
2177 };
2178 telemetry::event!("Git Pulled");
2179 let branch = branch.clone();
2180 let remote = self.get_remote(false, window, cx);
2181 cx.spawn_in(window, async move |this, cx| {
2182 let remote = match remote.await {
2183 Ok(Some(remote)) => remote,
2184 Ok(None) => {
2185 return Ok(());
2186 }
2187 Err(e) => {
2188 log::error!("Failed to get current remote: {}", e);
2189 this.update(cx, |this, cx| this.show_error_toast("pull", e, cx))
2190 .ok();
2191 return Ok(());
2192 }
2193 };
2194
2195 let askpass = this.update_in(cx, |this, window, cx| {
2196 this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
2197 })?;
2198
2199 let pull = repo.update(cx, |repo, cx| {
2200 repo.pull(
2201 branch.name().to_owned().into(),
2202 remote.name.clone(),
2203 askpass,
2204 cx,
2205 )
2206 })?;
2207
2208 let remote_message = pull.await?;
2209
2210 let action = RemoteAction::Pull(remote);
2211 this.update(cx, |this, cx| match remote_message {
2212 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2213 Err(e) => {
2214 log::error!("Error while pulling {:?}", e);
2215 this.show_error_toast(action.name(), e, cx)
2216 }
2217 })
2218 .ok();
2219
2220 anyhow::Ok(())
2221 })
2222 .detach_and_log_err(cx);
2223 }
2224
2225 pub(crate) fn push(
2226 &mut self,
2227 force_push: bool,
2228 select_remote: bool,
2229 window: &mut Window,
2230 cx: &mut Context<Self>,
2231 ) {
2232 if !self.can_push_and_pull(cx) {
2233 return;
2234 }
2235 let Some(repo) = self.active_repository.clone() else {
2236 return;
2237 };
2238 let Some(branch) = repo.read(cx).branch.as_ref() else {
2239 return;
2240 };
2241 telemetry::event!("Git Pushed");
2242 let branch = branch.clone();
2243
2244 let options = if force_push {
2245 Some(PushOptions::Force)
2246 } else {
2247 match branch.upstream {
2248 Some(Upstream {
2249 tracking: UpstreamTracking::Gone,
2250 ..
2251 })
2252 | None => Some(PushOptions::SetUpstream),
2253 _ => None,
2254 }
2255 };
2256 let remote = self.get_remote(select_remote, window, cx);
2257
2258 cx.spawn_in(window, async move |this, cx| {
2259 let remote = match remote.await {
2260 Ok(Some(remote)) => remote,
2261 Ok(None) => {
2262 return Ok(());
2263 }
2264 Err(e) => {
2265 log::error!("Failed to get current remote: {}", e);
2266 this.update(cx, |this, cx| this.show_error_toast("push", e, cx))
2267 .ok();
2268 return Ok(());
2269 }
2270 };
2271
2272 let askpass_delegate = this.update_in(cx, |this, window, cx| {
2273 this.askpass_delegate(format!("git push {}", remote.name), window, cx)
2274 })?;
2275
2276 let push = repo.update(cx, |repo, cx| {
2277 repo.push(
2278 branch.name().to_owned().into(),
2279 remote.name.clone(),
2280 options,
2281 askpass_delegate,
2282 cx,
2283 )
2284 })?;
2285
2286 let remote_output = push.await?;
2287
2288 let action = RemoteAction::Push(branch.name().to_owned().into(), remote);
2289 this.update(cx, |this, cx| match remote_output {
2290 Ok(remote_message) => this.show_remote_output(action, remote_message, cx),
2291 Err(e) => {
2292 log::error!("Error while pushing {:?}", e);
2293 this.show_error_toast(action.name(), e, cx)
2294 }
2295 })?;
2296
2297 anyhow::Ok(())
2298 })
2299 .detach_and_log_err(cx);
2300 }
2301
2302 fn askpass_delegate(
2303 &self,
2304 operation: impl Into<SharedString>,
2305 window: &mut Window,
2306 cx: &mut Context<Self>,
2307 ) -> AskPassDelegate {
2308 let this = cx.weak_entity();
2309 let operation = operation.into();
2310 let window = window.window_handle();
2311 AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
2312 window
2313 .update(cx, |_, window, cx| {
2314 this.update(cx, |this, cx| {
2315 this.workspace.update(cx, |workspace, cx| {
2316 workspace.toggle_modal(window, cx, |window, cx| {
2317 AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
2318 });
2319 })
2320 })
2321 })
2322 .ok();
2323 })
2324 }
2325
2326 fn can_push_and_pull(&self, cx: &App) -> bool {
2327 !self.project.read(cx).is_via_collab()
2328 }
2329
2330 fn get_remote(
2331 &mut self,
2332 always_select: bool,
2333 window: &mut Window,
2334 cx: &mut Context<Self>,
2335 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2336 let repo = self.active_repository.clone();
2337 let workspace = self.workspace.clone();
2338 let mut cx = window.to_async(cx);
2339
2340 async move {
2341 let repo = repo.context("No active repository")?;
2342 let current_remotes: Vec<Remote> = repo
2343 .update(&mut cx, |repo, _| {
2344 let current_branch = if always_select {
2345 None
2346 } else {
2347 let current_branch = repo.branch.as_ref().context("No active branch")?;
2348 Some(current_branch.name().to_string())
2349 };
2350 anyhow::Ok(repo.get_remotes(current_branch))
2351 })??
2352 .await??;
2353
2354 let current_remotes: Vec<_> = current_remotes
2355 .into_iter()
2356 .map(|remotes| remotes.name)
2357 .collect();
2358 let selection = cx
2359 .update(|window, cx| {
2360 picker_prompt::prompt(
2361 "Pick which remote to push to",
2362 current_remotes.clone(),
2363 workspace,
2364 window,
2365 cx,
2366 )
2367 })?
2368 .await;
2369
2370 Ok(selection.map(|selection| Remote {
2371 name: current_remotes[selection].clone(),
2372 }))
2373 }
2374 }
2375
2376 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2377 if self.local_committer_task.is_none() {
2378 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2379 let committer = get_git_committer(cx).await;
2380 this.update(cx, |this, cx| {
2381 this.local_committer = Some(committer);
2382 cx.notify()
2383 })
2384 .ok();
2385 }));
2386 }
2387 }
2388
2389 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2390 let mut new_co_authors = Vec::new();
2391 let project = self.project.read(cx);
2392
2393 let Some(room) = self
2394 .workspace
2395 .upgrade()
2396 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2397 else {
2398 return Vec::default();
2399 };
2400
2401 let room = room.read(cx);
2402
2403 for (peer_id, collaborator) in project.collaborators() {
2404 if collaborator.is_host {
2405 continue;
2406 }
2407
2408 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2409 continue;
2410 };
2411 if !participant.can_write() {
2412 continue;
2413 }
2414 if let Some(email) = &collaborator.committer_email {
2415 let name = collaborator
2416 .committer_name
2417 .clone()
2418 .or_else(|| participant.user.name.clone())
2419 .unwrap_or_else(|| participant.user.github_login.clone());
2420 new_co_authors.push((name.clone(), email.clone()))
2421 }
2422 }
2423 if !project.is_local() && !project.is_read_only(cx) {
2424 if let Some(local_committer) = self.local_committer(room, cx) {
2425 new_co_authors.push(local_committer);
2426 }
2427 }
2428 new_co_authors
2429 }
2430
2431 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2432 let user = room.local_participant_user(cx)?;
2433 let committer = self.local_committer.as_ref()?;
2434 let email = committer.email.clone()?;
2435 let name = committer
2436 .name
2437 .clone()
2438 .or_else(|| user.name.clone())
2439 .unwrap_or_else(|| user.github_login.clone());
2440 Some((name, email))
2441 }
2442
2443 fn toggle_fill_co_authors(
2444 &mut self,
2445 _: &ToggleFillCoAuthors,
2446 _: &mut Window,
2447 cx: &mut Context<Self>,
2448 ) {
2449 self.add_coauthors = !self.add_coauthors;
2450 cx.notify();
2451 }
2452
2453 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2454 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2455
2456 let existing_text = message.to_ascii_lowercase();
2457 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2458 let mut ends_with_co_authors = false;
2459 let existing_co_authors = existing_text
2460 .lines()
2461 .filter_map(|line| {
2462 let line = line.trim();
2463 if line.starts_with(&lowercase_co_author_prefix) {
2464 ends_with_co_authors = true;
2465 Some(line)
2466 } else {
2467 ends_with_co_authors = false;
2468 None
2469 }
2470 })
2471 .collect::<HashSet<_>>();
2472
2473 let new_co_authors = self
2474 .potential_co_authors(cx)
2475 .into_iter()
2476 .filter(|(_, email)| {
2477 !existing_co_authors
2478 .iter()
2479 .any(|existing| existing.contains(email.as_str()))
2480 })
2481 .collect::<Vec<_>>();
2482
2483 if new_co_authors.is_empty() {
2484 return;
2485 }
2486
2487 if !ends_with_co_authors {
2488 message.push('\n');
2489 }
2490 for (name, email) in new_co_authors {
2491 message.push('\n');
2492 message.push_str(CO_AUTHOR_PREFIX);
2493 message.push_str(&name);
2494 message.push_str(" <");
2495 message.push_str(&email);
2496 message.push('>');
2497 }
2498 message.push('\n');
2499 }
2500
2501 fn schedule_update(
2502 &mut self,
2503 clear_pending: bool,
2504 window: &mut Window,
2505 cx: &mut Context<Self>,
2506 ) {
2507 let handle = cx.entity().downgrade();
2508 self.reopen_commit_buffer(window, cx);
2509 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2510 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2511 if let Some(git_panel) = handle.upgrade() {
2512 git_panel
2513 .update_in(cx, |git_panel, window, cx| {
2514 if clear_pending {
2515 git_panel.clear_pending();
2516 }
2517 git_panel.update_visible_entries(cx);
2518 git_panel.update_scrollbar_properties(window, cx);
2519 })
2520 .ok();
2521 }
2522 });
2523 }
2524
2525 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2526 let Some(active_repo) = self.active_repository.as_ref() else {
2527 return;
2528 };
2529 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2530 let project = self.project.read(cx);
2531 active_repo.open_commit_buffer(
2532 Some(project.languages().clone()),
2533 project.buffer_store().clone(),
2534 cx,
2535 )
2536 });
2537
2538 cx.spawn_in(window, async move |git_panel, cx| {
2539 let buffer = load_buffer.await?;
2540 git_panel.update_in(cx, |git_panel, window, cx| {
2541 if git_panel
2542 .commit_editor
2543 .read(cx)
2544 .buffer()
2545 .read(cx)
2546 .as_singleton()
2547 .as_ref()
2548 != Some(&buffer)
2549 {
2550 git_panel.commit_editor = cx.new(|cx| {
2551 commit_message_editor(
2552 buffer,
2553 git_panel.suggest_commit_message(cx).map(SharedString::from),
2554 git_panel.project.clone(),
2555 true,
2556 window,
2557 cx,
2558 )
2559 });
2560 }
2561 })
2562 })
2563 .detach_and_log_err(cx);
2564 }
2565
2566 fn clear_pending(&mut self) {
2567 self.pending.retain(|v| !v.finished)
2568 }
2569
2570 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2571 let bulk_staging = self.bulk_staging.take();
2572 let last_staged_path_prev_index = bulk_staging
2573 .as_ref()
2574 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2575
2576 self.entries.clear();
2577 self.single_staged_entry.take();
2578 self.single_tracked_entry.take();
2579 self.conflicted_count = 0;
2580 self.conflicted_staged_count = 0;
2581 self.new_count = 0;
2582 self.tracked_count = 0;
2583 self.new_staged_count = 0;
2584 self.tracked_staged_count = 0;
2585 self.entry_count = 0;
2586
2587 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2588
2589 let mut changed_entries = Vec::new();
2590 let mut new_entries = Vec::new();
2591 let mut conflict_entries = Vec::new();
2592 let mut single_staged_entry = None;
2593 let mut staged_count = 0;
2594 let mut max_width_item: Option<(RepoPath, usize)> = None;
2595
2596 let Some(repo) = self.active_repository.as_ref() else {
2597 // Just clear entries if no repository is active.
2598 cx.notify();
2599 return;
2600 };
2601
2602 let repo = repo.read(cx);
2603
2604 for entry in repo.cached_status() {
2605 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2606 let is_new = entry.status.is_created();
2607 let staging = entry.status.staging();
2608
2609 if self.pending.iter().any(|pending| {
2610 pending.target_status == TargetStatus::Reverted
2611 && !pending.finished
2612 && pending
2613 .entries
2614 .iter()
2615 .any(|pending| pending.repo_path == entry.repo_path)
2616 }) {
2617 continue;
2618 }
2619
2620 let abs_path = repo.work_directory_abs_path.join(&entry.repo_path.0);
2621 let entry = GitStatusEntry {
2622 repo_path: entry.repo_path.clone(),
2623 abs_path,
2624 status: entry.status,
2625 staging,
2626 };
2627
2628 if staging.has_staged() {
2629 staged_count += 1;
2630 single_staged_entry = Some(entry.clone());
2631 }
2632
2633 let width_estimate = Self::item_width_estimate(
2634 entry.parent_dir().map(|s| s.len()).unwrap_or(0),
2635 entry.display_name().len(),
2636 );
2637
2638 match max_width_item.as_mut() {
2639 Some((repo_path, estimate)) => {
2640 if width_estimate > *estimate {
2641 *repo_path = entry.repo_path.clone();
2642 *estimate = width_estimate;
2643 }
2644 }
2645 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2646 }
2647
2648 if sort_by_path {
2649 changed_entries.push(entry);
2650 } else if is_conflict {
2651 conflict_entries.push(entry);
2652 } else if is_new {
2653 new_entries.push(entry);
2654 } else {
2655 changed_entries.push(entry);
2656 }
2657 }
2658
2659 let mut pending_staged_count = 0;
2660 let mut last_pending_staged = None;
2661 let mut pending_status_for_single_staged = None;
2662 for pending in self.pending.iter() {
2663 if pending.target_status == TargetStatus::Staged {
2664 pending_staged_count += pending.entries.len();
2665 last_pending_staged = pending.entries.iter().next().cloned();
2666 }
2667 if let Some(single_staged) = &single_staged_entry {
2668 if pending
2669 .entries
2670 .iter()
2671 .any(|entry| entry.repo_path == single_staged.repo_path)
2672 {
2673 pending_status_for_single_staged = Some(pending.target_status);
2674 }
2675 }
2676 }
2677
2678 if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2679 match pending_status_for_single_staged {
2680 Some(TargetStatus::Staged) | None => {
2681 self.single_staged_entry = single_staged_entry;
2682 }
2683 _ => {}
2684 }
2685 } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2686 self.single_staged_entry = last_pending_staged;
2687 }
2688
2689 if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2690 self.single_tracked_entry = changed_entries.first().cloned();
2691 }
2692
2693 if conflict_entries.len() > 0 {
2694 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2695 header: Section::Conflict,
2696 }));
2697 self.entries
2698 .extend(conflict_entries.into_iter().map(GitListEntry::Status));
2699 }
2700
2701 if changed_entries.len() > 0 {
2702 if !sort_by_path {
2703 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2704 header: Section::Tracked,
2705 }));
2706 }
2707 self.entries
2708 .extend(changed_entries.into_iter().map(GitListEntry::Status));
2709 }
2710 if new_entries.len() > 0 {
2711 self.entries.push(GitListEntry::Header(GitHeaderEntry {
2712 header: Section::New,
2713 }));
2714 self.entries
2715 .extend(new_entries.into_iter().map(GitListEntry::Status));
2716 }
2717
2718 if let Some((repo_path, _)) = max_width_item {
2719 self.max_width_item_index = self.entries.iter().position(|entry| match entry {
2720 GitListEntry::Status(git_status_entry) => git_status_entry.repo_path == repo_path,
2721 GitListEntry::Header(_) => false,
2722 });
2723 }
2724
2725 self.update_counts(repo);
2726
2727 let bulk_staging_anchor_new_index = bulk_staging
2728 .as_ref()
2729 .filter(|op| op.repo_id == repo.id)
2730 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2731 if bulk_staging_anchor_new_index == last_staged_path_prev_index
2732 && let Some(index) = bulk_staging_anchor_new_index
2733 && let Some(entry) = self.entries.get(index)
2734 && let Some(entry) = entry.status_entry()
2735 && self.entry_staging(entry) == StageStatus::Staged
2736 {
2737 self.bulk_staging = bulk_staging;
2738 }
2739
2740 self.select_first_entry_if_none(cx);
2741
2742 let suggested_commit_message = self.suggest_commit_message(cx);
2743 let placeholder_text = suggested_commit_message.unwrap_or("Enter commit message".into());
2744
2745 self.commit_editor.update(cx, |editor, cx| {
2746 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
2747 });
2748
2749 cx.notify();
2750 }
2751
2752 fn header_state(&self, header_type: Section) -> ToggleState {
2753 let (staged_count, count) = match header_type {
2754 Section::New => (self.new_staged_count, self.new_count),
2755 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2756 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2757 };
2758 if staged_count == 0 {
2759 ToggleState::Unselected
2760 } else if count == staged_count {
2761 ToggleState::Selected
2762 } else {
2763 ToggleState::Indeterminate
2764 }
2765 }
2766
2767 fn update_counts(&mut self, repo: &Repository) {
2768 self.show_placeholders = false;
2769 self.conflicted_count = 0;
2770 self.conflicted_staged_count = 0;
2771 self.new_count = 0;
2772 self.tracked_count = 0;
2773 self.new_staged_count = 0;
2774 self.tracked_staged_count = 0;
2775 self.entry_count = 0;
2776 for entry in &self.entries {
2777 let Some(status_entry) = entry.status_entry() else {
2778 continue;
2779 };
2780 self.entry_count += 1;
2781 if repo.had_conflict_on_last_merge_head_change(&status_entry.repo_path) {
2782 self.conflicted_count += 1;
2783 if self.entry_staging(status_entry).has_staged() {
2784 self.conflicted_staged_count += 1;
2785 }
2786 } else if status_entry.status.is_created() {
2787 self.new_count += 1;
2788 if self.entry_staging(status_entry).has_staged() {
2789 self.new_staged_count += 1;
2790 }
2791 } else {
2792 self.tracked_count += 1;
2793 if self.entry_staging(status_entry).has_staged() {
2794 self.tracked_staged_count += 1;
2795 }
2796 }
2797 }
2798 }
2799
2800 fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2801 for pending in self.pending.iter().rev() {
2802 if pending
2803 .entries
2804 .iter()
2805 .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2806 {
2807 match pending.target_status {
2808 TargetStatus::Staged => return StageStatus::Staged,
2809 TargetStatus::Unstaged => return StageStatus::Unstaged,
2810 TargetStatus::Reverted => continue,
2811 TargetStatus::Unchanged => continue,
2812 }
2813 }
2814 }
2815 entry.staging
2816 }
2817
2818 pub(crate) fn has_staged_changes(&self) -> bool {
2819 self.tracked_staged_count > 0
2820 || self.new_staged_count > 0
2821 || self.conflicted_staged_count > 0
2822 }
2823
2824 pub(crate) fn has_unstaged_changes(&self) -> bool {
2825 self.tracked_count > self.tracked_staged_count
2826 || self.new_count > self.new_staged_count
2827 || self.conflicted_count > self.conflicted_staged_count
2828 }
2829
2830 fn has_tracked_changes(&self) -> bool {
2831 self.tracked_count > 0
2832 }
2833
2834 pub fn has_unstaged_conflicts(&self) -> bool {
2835 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2836 }
2837
2838 fn show_error_toast(&self, action: impl Into<SharedString>, e: anyhow::Error, cx: &mut App) {
2839 let action = action.into();
2840 let Some(workspace) = self.workspace.upgrade() else {
2841 return;
2842 };
2843
2844 let message = e.to_string().trim().to_string();
2845 if message
2846 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2847 .next()
2848 .is_some()
2849 {
2850 return; // Hide the cancelled by user message
2851 } else {
2852 workspace.update(cx, |workspace, cx| {
2853 let workspace_weak = cx.weak_entity();
2854 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
2855 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
2856 .action("View Log", move |window, cx| {
2857 let message = message.clone();
2858 let action = action.clone();
2859 workspace_weak
2860 .update(cx, move |workspace, cx| {
2861 Self::open_output(action, workspace, &message, window, cx)
2862 })
2863 .ok();
2864 })
2865 });
2866 workspace.toggle_status_toast(toast, cx)
2867 });
2868 }
2869 }
2870
2871 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
2872 where
2873 E: std::fmt::Debug + std::fmt::Display,
2874 {
2875 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
2876 let _ = workspace.update(cx, |workspace, cx| {
2877 struct CommitMessageError;
2878 let notification_id = NotificationId::unique::<CommitMessageError>();
2879 workspace.show_notification(notification_id, cx, |cx| {
2880 cx.new(|cx| {
2881 ErrorMessagePrompt::new(
2882 format!("Failed to generate commit message: {err}"),
2883 cx,
2884 )
2885 })
2886 });
2887 });
2888 }
2889 }
2890
2891 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2892 let Some(workspace) = self.workspace.upgrade() else {
2893 return;
2894 };
2895
2896 workspace.update(cx, |workspace, cx| {
2897 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
2898 let workspace_weak = cx.weak_entity();
2899 let operation = action.name();
2900
2901 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
2902 use remote_output::SuccessStyle::*;
2903 match style {
2904 Toast { .. } => this,
2905 ToastWithLog { output } => this
2906 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2907 .action("View Log", move |window, cx| {
2908 let output = output.clone();
2909 let output =
2910 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
2911 workspace_weak
2912 .update(cx, move |workspace, cx| {
2913 Self::open_output(operation, workspace, &output, window, cx)
2914 })
2915 .ok();
2916 }),
2917 PushPrLink { link } => this
2918 .icon(ToastIcon::new(IconName::GitBranchSmall).color(Color::Muted))
2919 .action("Open Pull Request", move |_, cx| cx.open_url(&link)),
2920 }
2921 });
2922 workspace.toggle_status_toast(status_toast, cx)
2923 });
2924 }
2925
2926 fn open_output(
2927 operation: impl Into<SharedString>,
2928 workspace: &mut Workspace,
2929 output: &str,
2930 window: &mut Window,
2931 cx: &mut Context<Workspace>,
2932 ) {
2933 let operation = operation.into();
2934 let buffer = cx.new(|cx| Buffer::local(output, cx));
2935 buffer.update(cx, |buffer, cx| {
2936 buffer.set_capability(language::Capability::ReadOnly, cx);
2937 });
2938 let editor = cx.new(|cx| {
2939 let mut editor = Editor::for_buffer(buffer, None, window, cx);
2940 editor.buffer().update(cx, |buffer, cx| {
2941 buffer.set_title(format!("Output from git {operation}"), cx);
2942 });
2943 editor.set_read_only(true);
2944 editor
2945 });
2946
2947 workspace.add_item_to_center(Box::new(editor), window, cx);
2948 }
2949
2950 pub fn can_commit(&self) -> bool {
2951 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2952 }
2953
2954 pub fn can_stage_all(&self) -> bool {
2955 self.has_unstaged_changes()
2956 }
2957
2958 pub fn can_unstage_all(&self) -> bool {
2959 self.has_staged_changes()
2960 }
2961
2962 // eventually we'll need to take depth into account here
2963 // if we add a tree view
2964 fn item_width_estimate(path: usize, file_name: usize) -> usize {
2965 path + file_name
2966 }
2967
2968 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
2969 let focus_handle = self.focus_handle.clone();
2970 let has_tracked_changes = self.has_tracked_changes();
2971 let has_staged_changes = self.has_staged_changes();
2972 let has_unstaged_changes = self.has_unstaged_changes();
2973 let has_new_changes = self.new_count > 0;
2974
2975 PopoverMenu::new(id.into())
2976 .trigger(
2977 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
2978 .icon_size(IconSize::Small)
2979 .icon_color(Color::Muted),
2980 )
2981 .menu(move |window, cx| {
2982 Some(git_panel_context_menu(
2983 focus_handle.clone(),
2984 GitMenuState {
2985 has_tracked_changes,
2986 has_staged_changes,
2987 has_unstaged_changes,
2988 has_new_changes,
2989 },
2990 window,
2991 cx,
2992 ))
2993 })
2994 .anchor(Corner::TopRight)
2995 }
2996
2997 pub(crate) fn render_generate_commit_message_button(
2998 &self,
2999 cx: &Context<Self>,
3000 ) -> Option<AnyElement> {
3001 current_language_model(cx).is_some().then(|| {
3002 if self.generate_commit_message_task.is_some() {
3003 return h_flex()
3004 .gap_1()
3005 .child(
3006 Icon::new(IconName::ArrowCircle)
3007 .size(IconSize::XSmall)
3008 .color(Color::Info)
3009 .with_animation(
3010 "arrow-circle",
3011 Animation::new(Duration::from_secs(2)).repeat(),
3012 |icon, delta| {
3013 icon.transform(Transformation::rotate(percentage(delta)))
3014 },
3015 ),
3016 )
3017 .child(
3018 Label::new("Generating Commit...")
3019 .size(LabelSize::Small)
3020 .color(Color::Muted),
3021 )
3022 .into_any_element();
3023 }
3024
3025 let can_commit = self.can_commit();
3026 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3027 IconButton::new("generate-commit-message", IconName::AiEdit)
3028 .shape(ui::IconButtonShape::Square)
3029 .icon_color(Color::Muted)
3030 .tooltip(move |window, cx| {
3031 if can_commit {
3032 Tooltip::for_action_in(
3033 "Generate Commit Message",
3034 &git::GenerateCommitMessage,
3035 &editor_focus_handle,
3036 window,
3037 cx,
3038 )
3039 } else {
3040 Tooltip::simple("No changes to commit", cx)
3041 }
3042 })
3043 .disabled(!can_commit)
3044 .on_click(cx.listener(move |this, _event, _window, cx| {
3045 this.generate_commit_message(cx);
3046 }))
3047 .into_any_element()
3048 })
3049 }
3050
3051 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3052 let potential_co_authors = self.potential_co_authors(cx);
3053
3054 let (tooltip_label, icon) = if self.add_coauthors {
3055 ("Remove co-authored-by", IconName::Person)
3056 } else {
3057 ("Add co-authored-by", IconName::UserCheck)
3058 };
3059
3060 if potential_co_authors.is_empty() {
3061 None
3062 } else {
3063 Some(
3064 IconButton::new("co-authors", icon)
3065 .shape(ui::IconButtonShape::Square)
3066 .icon_color(Color::Disabled)
3067 .selected_icon_color(Color::Selected)
3068 .toggle_state(self.add_coauthors)
3069 .tooltip(move |_, cx| {
3070 let title = format!(
3071 "{}:{}{}",
3072 tooltip_label,
3073 if potential_co_authors.len() == 1 {
3074 ""
3075 } else {
3076 "\n"
3077 },
3078 potential_co_authors
3079 .iter()
3080 .map(|(name, email)| format!(" {} <{}>", name, email))
3081 .join("\n")
3082 );
3083 Tooltip::simple(title, cx)
3084 })
3085 .on_click(cx.listener(|this, _, _, cx| {
3086 this.add_coauthors = !this.add_coauthors;
3087 cx.notify();
3088 }))
3089 .into_any_element(),
3090 )
3091 }
3092 }
3093
3094 fn render_git_commit_menu(
3095 &self,
3096 id: impl Into<ElementId>,
3097 keybinding_target: Option<FocusHandle>,
3098 cx: &mut Context<Self>,
3099 ) -> impl IntoElement {
3100 PopoverMenu::new(id.into())
3101 .trigger(
3102 ui::ButtonLike::new_rounded_right("commit-split-button-right")
3103 .layer(ui::ElevationIndex::ModalSurface)
3104 .size(ButtonSize::None)
3105 .child(
3106 h_flex()
3107 .px_1()
3108 .h_full()
3109 .justify_center()
3110 .border_l_1()
3111 .border_color(cx.theme().colors().border)
3112 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3113 ),
3114 )
3115 .menu({
3116 let has_previous_commit = self.head_commit(cx).is_some();
3117 let amend = self.amend_pending();
3118 let signoff = self.signoff_enabled;
3119
3120 move |window, cx| {
3121 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3122 context_menu
3123 .when_some(keybinding_target.clone(), |el, keybinding_target| {
3124 el.context(keybinding_target.clone())
3125 })
3126 .when(has_previous_commit, |this| {
3127 this.toggleable_entry(
3128 "Amend",
3129 amend,
3130 IconPosition::Start,
3131 Some(Box::new(Amend)),
3132 move |window, cx| window.dispatch_action(Box::new(Amend), cx),
3133 )
3134 })
3135 .toggleable_entry(
3136 "Signoff",
3137 signoff,
3138 IconPosition::Start,
3139 Some(Box::new(Signoff)),
3140 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3141 )
3142 }))
3143 }
3144 })
3145 .anchor(Corner::TopRight)
3146 }
3147
3148 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3149 if self.has_unstaged_conflicts() {
3150 (false, "You must resolve conflicts before committing")
3151 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
3152 (false, "No changes to commit")
3153 } else if self.pending_commit.is_some() {
3154 (false, "Commit in progress")
3155 } else if !self.has_commit_message(cx) {
3156 (false, "No commit message")
3157 } else if !self.has_write_access(cx) {
3158 (false, "You do not have write access to this project")
3159 } else {
3160 (true, self.commit_button_title())
3161 }
3162 }
3163
3164 pub fn commit_button_title(&self) -> &'static str {
3165 if self.amend_pending {
3166 if self.has_staged_changes() {
3167 "Amend"
3168 } else {
3169 "Amend Tracked"
3170 }
3171 } else {
3172 if self.has_staged_changes() {
3173 "Commit"
3174 } else {
3175 "Commit Tracked"
3176 }
3177 }
3178 }
3179
3180 fn expand_commit_editor(
3181 &mut self,
3182 _: &git::ExpandCommitEditor,
3183 window: &mut Window,
3184 cx: &mut Context<Self>,
3185 ) {
3186 let workspace = self.workspace.clone();
3187 window.defer(cx, move |window, cx| {
3188 workspace
3189 .update(cx, |workspace, cx| {
3190 CommitModal::toggle(workspace, None, window, cx)
3191 })
3192 .ok();
3193 })
3194 }
3195
3196 fn render_panel_header(
3197 &self,
3198 window: &mut Window,
3199 cx: &mut Context<Self>,
3200 ) -> Option<impl IntoElement> {
3201 self.active_repository.as_ref()?;
3202
3203 let text;
3204 let action;
3205 let tooltip;
3206 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3207 text = "Unstage All";
3208 action = git::UnstageAll.boxed_clone();
3209 tooltip = "git reset";
3210 } else {
3211 text = "Stage All";
3212 action = git::StageAll.boxed_clone();
3213 tooltip = "git add --all ."
3214 }
3215
3216 let change_string = match self.entry_count {
3217 0 => "No Changes".to_string(),
3218 1 => "1 Change".to_string(),
3219 _ => format!("{} Changes", self.entry_count),
3220 };
3221
3222 Some(
3223 self.panel_header_container(window, cx)
3224 .px_2()
3225 .justify_between()
3226 .child(
3227 panel_button(change_string)
3228 .color(Color::Muted)
3229 .tooltip(Tooltip::for_action_title_in(
3230 "Open Diff",
3231 &Diff,
3232 &self.focus_handle,
3233 ))
3234 .on_click(|_, _, cx| {
3235 cx.defer(|cx| {
3236 cx.dispatch_action(&Diff);
3237 })
3238 }),
3239 )
3240 .child(
3241 h_flex()
3242 .gap_1()
3243 .child(self.render_overflow_menu("overflow_menu"))
3244 .child(
3245 panel_filled_button(text)
3246 .tooltip(Tooltip::for_action_title_in(
3247 tooltip,
3248 action.as_ref(),
3249 &self.focus_handle,
3250 ))
3251 .disabled(self.entry_count == 0)
3252 .on_click(move |_, _, cx| {
3253 let action = action.boxed_clone();
3254 cx.defer(move |cx| {
3255 cx.dispatch_action(action.as_ref());
3256 })
3257 }),
3258 ),
3259 ),
3260 )
3261 }
3262
3263 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3264 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3265 if !self.can_push_and_pull(cx) {
3266 return None;
3267 }
3268 Some(
3269 h_flex()
3270 .gap_1()
3271 .flex_shrink_0()
3272 .when_some(branch, |this, branch| {
3273 let focus_handle = Some(self.focus_handle(cx));
3274
3275 this.children(render_remote_button(
3276 "remote-button",
3277 &branch,
3278 focus_handle,
3279 true,
3280 ))
3281 })
3282 .into_any_element(),
3283 )
3284 }
3285
3286 pub fn render_footer(
3287 &self,
3288 window: &mut Window,
3289 cx: &mut Context<Self>,
3290 ) -> Option<impl IntoElement> {
3291 let active_repository = self.active_repository.clone()?;
3292 let panel_editor_style = panel_editor_style(true, window, cx);
3293
3294 let enable_coauthors = self.render_co_authors(cx);
3295
3296 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3297 let expand_tooltip_focus_handle = editor_focus_handle.clone();
3298
3299 let branch = active_repository.read(cx).branch.clone();
3300 let head_commit = active_repository.read(cx).head_commit.clone();
3301
3302 let footer_size = px(32.);
3303 let gap = px(9.0);
3304 let max_height = panel_editor_style
3305 .text
3306 .line_height_in_pixels(window.rem_size())
3307 * MAX_PANEL_EDITOR_LINES
3308 + gap;
3309
3310 let git_panel = cx.entity().clone();
3311 let display_name = SharedString::from(Arc::from(
3312 active_repository
3313 .read(cx)
3314 .display_name()
3315 .trim_end_matches("/"),
3316 ));
3317 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3318 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3319 });
3320
3321 let footer = v_flex()
3322 .child(PanelRepoFooter::new(
3323 display_name,
3324 branch,
3325 head_commit,
3326 Some(git_panel.clone()),
3327 ))
3328 .child(
3329 panel_editor_container(window, cx)
3330 .id("commit-editor-container")
3331 .relative()
3332 .w_full()
3333 .h(max_height + footer_size)
3334 .border_t_1()
3335 .border_color(cx.theme().colors().border)
3336 .cursor_text()
3337 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3338 window.focus(&this.commit_editor.focus_handle(cx));
3339 }))
3340 .child(
3341 h_flex()
3342 .id("commit-footer")
3343 .border_t_1()
3344 .when(editor_is_long, |el| {
3345 el.border_color(cx.theme().colors().border_variant)
3346 })
3347 .absolute()
3348 .bottom_0()
3349 .left_0()
3350 .w_full()
3351 .px_2()
3352 .h(footer_size)
3353 .flex_none()
3354 .justify_between()
3355 .child(
3356 self.render_generate_commit_message_button(cx)
3357 .unwrap_or_else(|| div().into_any_element()),
3358 )
3359 .child(
3360 h_flex()
3361 .gap_0p5()
3362 .children(enable_coauthors)
3363 .child(self.render_commit_button(cx)),
3364 ),
3365 )
3366 .child(
3367 div()
3368 .pr_2p5()
3369 .on_action(|&editor::actions::MoveUp, _, cx| {
3370 cx.stop_propagation();
3371 })
3372 .on_action(|&editor::actions::MoveDown, _, cx| {
3373 cx.stop_propagation();
3374 })
3375 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3376 )
3377 .child(
3378 h_flex()
3379 .absolute()
3380 .top_2()
3381 .right_2()
3382 .opacity(0.5)
3383 .hover(|this| this.opacity(1.0))
3384 .child(
3385 panel_icon_button("expand-commit-editor", IconName::Maximize)
3386 .icon_size(IconSize::Small)
3387 .size(ui::ButtonSize::Default)
3388 .tooltip(move |window, cx| {
3389 Tooltip::for_action_in(
3390 "Open Commit Modal",
3391 &git::ExpandCommitEditor,
3392 &expand_tooltip_focus_handle,
3393 window,
3394 cx,
3395 )
3396 })
3397 .on_click(cx.listener({
3398 move |_, _, window, cx| {
3399 window.dispatch_action(
3400 git::ExpandCommitEditor.boxed_clone(),
3401 cx,
3402 )
3403 }
3404 })),
3405 ),
3406 ),
3407 );
3408
3409 Some(footer)
3410 }
3411
3412 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3413 let (can_commit, tooltip) = self.configure_commit_button(cx);
3414 let title = self.commit_button_title();
3415 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3416 let amend = self.amend_pending();
3417 let signoff = self.signoff_enabled;
3418
3419 div()
3420 .id("commit-wrapper")
3421 .on_hover(cx.listener(move |this, hovered, _, cx| {
3422 this.show_placeholders =
3423 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3424 cx.notify()
3425 }))
3426 .child(SplitButton::new(
3427 ui::ButtonLike::new_rounded_left(ElementId::Name(
3428 format!("split-button-left-{}", title).into(),
3429 ))
3430 .layer(ui::ElevationIndex::ModalSurface)
3431 .size(ui::ButtonSize::Compact)
3432 .child(
3433 div()
3434 .child(Label::new(title).size(LabelSize::Small))
3435 .mr_0p5(),
3436 )
3437 .on_click({
3438 let git_panel = cx.weak_entity();
3439 move |_, window, cx| {
3440 telemetry::event!("Git Committed", source = "Git Panel");
3441 git_panel
3442 .update(cx, |git_panel, cx| {
3443 git_panel.set_amend_pending(false, cx);
3444 git_panel.commit_changes(
3445 CommitOptions { amend, signoff },
3446 window,
3447 cx,
3448 );
3449 })
3450 .ok();
3451 }
3452 })
3453 .disabled(!can_commit || self.modal_open)
3454 .tooltip({
3455 let handle = commit_tooltip_focus_handle.clone();
3456 move |window, cx| {
3457 if can_commit {
3458 Tooltip::with_meta_in(
3459 tooltip,
3460 Some(&git::Commit),
3461 format!(
3462 "git commit{}{}",
3463 if amend { " --amend" } else { "" },
3464 if signoff { " --signoff" } else { "" }
3465 ),
3466 &handle.clone(),
3467 window,
3468 cx,
3469 )
3470 } else {
3471 Tooltip::simple(tooltip, cx)
3472 }
3473 }
3474 }),
3475 self.render_git_commit_menu(
3476 ElementId::Name(format!("split-button-right-{}", title).into()),
3477 Some(commit_tooltip_focus_handle.clone()),
3478 cx,
3479 )
3480 .into_any_element(),
3481 ))
3482 }
3483
3484 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3485 h_flex()
3486 .py_1p5()
3487 .px_2()
3488 .gap_1p5()
3489 .justify_between()
3490 .border_t_1()
3491 .border_color(cx.theme().colors().border.opacity(0.8))
3492 .child(
3493 div()
3494 .flex_grow()
3495 .overflow_hidden()
3496 .max_w(relative(0.85))
3497 .child(
3498 Label::new("This will update your most recent commit.")
3499 .size(LabelSize::Small)
3500 .truncate(),
3501 ),
3502 )
3503 .child(panel_button("Cancel").size(ButtonSize::Default).on_click(
3504 cx.listener(|this, _, window, cx| this.toggle_amend_pending(&Amend, window, cx)),
3505 ))
3506 }
3507
3508 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3509 let active_repository = self.active_repository.as_ref()?;
3510 let branch = active_repository.read(cx).branch.as_ref()?;
3511 let commit = branch.most_recent_commit.as_ref()?.clone();
3512 let workspace = self.workspace.clone();
3513 let this = cx.entity();
3514
3515 Some(
3516 h_flex()
3517 .py_1p5()
3518 .px_2()
3519 .gap_1p5()
3520 .justify_between()
3521 .border_t_1()
3522 .border_color(cx.theme().colors().border.opacity(0.8))
3523 .child(
3524 div()
3525 .flex_grow()
3526 .overflow_hidden()
3527 .max_w(relative(0.85))
3528 .child(
3529 Label::new(commit.subject.clone())
3530 .size(LabelSize::Small)
3531 .truncate(),
3532 )
3533 .id("commit-msg-hover")
3534 .on_click({
3535 let commit = commit.clone();
3536 let repo = active_repository.downgrade();
3537 move |_, window, cx| {
3538 CommitView::open(
3539 commit.clone(),
3540 repo.clone(),
3541 workspace.clone().clone(),
3542 window,
3543 cx,
3544 );
3545 }
3546 })
3547 .hoverable_tooltip({
3548 let repo = active_repository.clone();
3549 move |window, cx| {
3550 GitPanelMessageTooltip::new(
3551 this.clone(),
3552 commit.sha.clone(),
3553 repo.clone(),
3554 window,
3555 cx,
3556 )
3557 .into()
3558 }
3559 }),
3560 )
3561 .when(commit.has_parent, |this| {
3562 let has_unstaged = self.has_unstaged_changes();
3563 this.child(
3564 panel_icon_button("undo", IconName::Undo)
3565 .icon_size(IconSize::XSmall)
3566 .icon_color(Color::Muted)
3567 .tooltip(move |window, cx| {
3568 Tooltip::with_meta(
3569 "Uncommit",
3570 Some(&git::Uncommit),
3571 if has_unstaged {
3572 "git reset HEAD^ --soft"
3573 } else {
3574 "git reset HEAD^"
3575 },
3576 window,
3577 cx,
3578 )
3579 })
3580 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3581 )
3582 }),
3583 )
3584 }
3585
3586 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3587 h_flex().h_full().flex_grow().justify_center().child(
3588 v_flex()
3589 .gap_2()
3590 .child(h_flex().w_full().justify_around().child(
3591 if self.active_repository.is_some() {
3592 "No changes to commit"
3593 } else {
3594 "No Git repositories"
3595 },
3596 ))
3597 .children({
3598 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3599 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3600 h_flex().w_full().justify_around().child(
3601 panel_filled_button("Initialize Repository")
3602 .tooltip(Tooltip::for_action_title_in(
3603 "git init",
3604 &git::Init,
3605 &self.focus_handle,
3606 ))
3607 .on_click(move |_, _, cx| {
3608 cx.defer(move |cx| {
3609 cx.dispatch_action(&git::Init);
3610 })
3611 }),
3612 )
3613 })
3614 })
3615 .text_ui_sm(cx)
3616 .mx_auto()
3617 .text_color(Color::Placeholder.color(cx)),
3618 )
3619 }
3620
3621 fn render_vertical_scrollbar(
3622 &self,
3623 show_horizontal_scrollbar_container: bool,
3624 cx: &mut Context<Self>,
3625 ) -> impl IntoElement {
3626 div()
3627 .id("git-panel-vertical-scroll")
3628 .occlude()
3629 .flex_none()
3630 .h_full()
3631 .cursor_default()
3632 .absolute()
3633 .right_0()
3634 .top_0()
3635 .bottom_0()
3636 .w(px(12.))
3637 .when(show_horizontal_scrollbar_container, |this| {
3638 this.pb_neg_3p5()
3639 })
3640 .on_mouse_move(cx.listener(|_, _, _, cx| {
3641 cx.notify();
3642 cx.stop_propagation()
3643 }))
3644 .on_hover(|_, _, cx| {
3645 cx.stop_propagation();
3646 })
3647 .on_any_mouse_down(|_, _, cx| {
3648 cx.stop_propagation();
3649 })
3650 .on_mouse_up(
3651 MouseButton::Left,
3652 cx.listener(|this, _, window, cx| {
3653 if !this.vertical_scrollbar.state.is_dragging()
3654 && !this.focus_handle.contains_focused(window, cx)
3655 {
3656 this.vertical_scrollbar.hide(window, cx);
3657 cx.notify();
3658 }
3659
3660 cx.stop_propagation();
3661 }),
3662 )
3663 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3664 cx.notify();
3665 }))
3666 .children(Scrollbar::vertical(
3667 // percentage as f32..end_offset as f32,
3668 self.vertical_scrollbar.state.clone(),
3669 ))
3670 }
3671
3672 /// Renders the horizontal scrollbar.
3673 ///
3674 /// The right offset is used to determine how far to the right the
3675 /// scrollbar should extend to, useful for ensuring it doesn't collide
3676 /// with the vertical scrollbar when visible.
3677 fn render_horizontal_scrollbar(
3678 &self,
3679 right_offset: Pixels,
3680 cx: &mut Context<Self>,
3681 ) -> impl IntoElement {
3682 div()
3683 .id("git-panel-horizontal-scroll")
3684 .occlude()
3685 .flex_none()
3686 .w_full()
3687 .cursor_default()
3688 .absolute()
3689 .bottom_neg_px()
3690 .left_0()
3691 .right_0()
3692 .pr(right_offset)
3693 .on_mouse_move(cx.listener(|_, _, _, cx| {
3694 cx.notify();
3695 cx.stop_propagation()
3696 }))
3697 .on_hover(|_, _, cx| {
3698 cx.stop_propagation();
3699 })
3700 .on_any_mouse_down(|_, _, cx| {
3701 cx.stop_propagation();
3702 })
3703 .on_mouse_up(
3704 MouseButton::Left,
3705 cx.listener(|this, _, window, cx| {
3706 if !this.horizontal_scrollbar.state.is_dragging()
3707 && !this.focus_handle.contains_focused(window, cx)
3708 {
3709 this.horizontal_scrollbar.hide(window, cx);
3710 cx.notify();
3711 }
3712
3713 cx.stop_propagation();
3714 }),
3715 )
3716 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3717 cx.notify();
3718 }))
3719 .children(Scrollbar::horizontal(
3720 // percentage as f32..end_offset as f32,
3721 self.horizontal_scrollbar.state.clone(),
3722 ))
3723 }
3724
3725 fn render_buffer_header_controls(
3726 &self,
3727 entity: &Entity<Self>,
3728 file: &Arc<dyn File>,
3729 _: &Window,
3730 cx: &App,
3731 ) -> Option<AnyElement> {
3732 let repo = self.active_repository.as_ref()?.read(cx);
3733 let project_path = (file.worktree_id(cx), file.path()).into();
3734 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3735 let ix = self.entry_by_path(&repo_path, cx)?;
3736 let entry = self.entries.get(ix)?;
3737
3738 let entry_staging = self.entry_staging(entry.status_entry()?);
3739
3740 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3741 .disabled(!self.has_write_access(cx))
3742 .fill()
3743 .elevation(ElevationIndex::Surface)
3744 .on_click({
3745 let entry = entry.clone();
3746 let git_panel = entity.downgrade();
3747 move |_, window, cx| {
3748 git_panel
3749 .update(cx, |this, cx| {
3750 this.toggle_staged_for_entry(&entry, window, cx);
3751 cx.stop_propagation();
3752 })
3753 .ok();
3754 }
3755 });
3756 Some(
3757 h_flex()
3758 .id("start-slot")
3759 .text_lg()
3760 .child(checkbox)
3761 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3762 // prevent the list item active state triggering when toggling checkbox
3763 cx.stop_propagation();
3764 })
3765 .into_any_element(),
3766 )
3767 }
3768
3769 fn render_entries(
3770 &self,
3771 has_write_access: bool,
3772 _: &Window,
3773 cx: &mut Context<Self>,
3774 ) -> impl IntoElement {
3775 let entry_count = self.entries.len();
3776
3777 let scroll_track_size = px(16.);
3778
3779 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3780 // magic number
3781 px(3.)
3782 } else {
3783 px(0.)
3784 };
3785
3786 v_flex()
3787 .flex_1()
3788 .size_full()
3789 .overflow_hidden()
3790 .relative()
3791 // Show a border on the top and bottom of the container when
3792 // the vertical scrollbar container is visible so we don't have a
3793 // floating left border in the panel.
3794 .when(self.vertical_scrollbar.show_track, |this| {
3795 this.border_t_1()
3796 .border_b_1()
3797 .border_color(cx.theme().colors().border)
3798 })
3799 .child(
3800 h_flex()
3801 .flex_1()
3802 .size_full()
3803 .relative()
3804 .overflow_hidden()
3805 .child(
3806 uniform_list(
3807 "entries",
3808 entry_count,
3809 cx.processor(move |this, range: Range<usize>, window, cx| {
3810 let mut items = Vec::with_capacity(range.end - range.start);
3811
3812 for ix in range {
3813 match &this.entries.get(ix) {
3814 Some(GitListEntry::Status(entry)) => {
3815 items.push(this.render_entry(
3816 ix,
3817 entry,
3818 has_write_access,
3819 window,
3820 cx,
3821 ));
3822 }
3823 Some(GitListEntry::Header(header)) => {
3824 items.push(this.render_list_header(
3825 ix,
3826 header,
3827 has_write_access,
3828 window,
3829 cx,
3830 ));
3831 }
3832 None => {}
3833 }
3834 }
3835
3836 items
3837 }),
3838 )
3839 .when(
3840 !self.horizontal_scrollbar.show_track
3841 && self.horizontal_scrollbar.show_scrollbar,
3842 |this| {
3843 // when not showing the horizontal scrollbar track, make sure we don't
3844 // obscure the last entry
3845 this.pb(scroll_track_size)
3846 },
3847 )
3848 .size_full()
3849 .flex_grow()
3850 .with_sizing_behavior(ListSizingBehavior::Auto)
3851 .with_horizontal_sizing_behavior(
3852 ListHorizontalSizingBehavior::Unconstrained,
3853 )
3854 .with_width_from_item(self.max_width_item_index)
3855 .track_scroll(self.scroll_handle.clone()),
3856 )
3857 .on_mouse_down(
3858 MouseButton::Right,
3859 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3860 this.deploy_panel_context_menu(event.position, window, cx)
3861 }),
3862 )
3863 .when(self.vertical_scrollbar.show_track, |this| {
3864 this.child(
3865 v_flex()
3866 .h_full()
3867 .flex_none()
3868 .w(scroll_track_size)
3869 .bg(cx.theme().colors().panel_background)
3870 .child(
3871 div()
3872 .size_full()
3873 .flex_1()
3874 .border_l_1()
3875 .border_color(cx.theme().colors().border),
3876 ),
3877 )
3878 })
3879 .when(self.vertical_scrollbar.show_scrollbar, |this| {
3880 this.child(
3881 self.render_vertical_scrollbar(
3882 self.horizontal_scrollbar.show_track,
3883 cx,
3884 ),
3885 )
3886 }),
3887 )
3888 .when(self.horizontal_scrollbar.show_track, |this| {
3889 this.child(
3890 h_flex()
3891 .w_full()
3892 .h(scroll_track_size)
3893 .flex_none()
3894 .relative()
3895 .child(
3896 div()
3897 .w_full()
3898 .flex_1()
3899 // for some reason the horizontal scrollbar is 1px
3900 // taller than the vertical scrollbar??
3901 .h(scroll_track_size - px(1.))
3902 .bg(cx.theme().colors().panel_background)
3903 .border_t_1()
3904 .border_color(cx.theme().colors().border),
3905 )
3906 .when(self.vertical_scrollbar.show_track, |this| {
3907 this.child(
3908 div()
3909 .flex_none()
3910 // -1px prevents a missing pixel between the two container borders
3911 .w(scroll_track_size - px(1.))
3912 .h_full(),
3913 )
3914 .child(
3915 // HACK: Fill the missing 1px 🥲
3916 div()
3917 .absolute()
3918 .right(scroll_track_size - px(1.))
3919 .bottom(scroll_track_size - px(1.))
3920 .size_px()
3921 .bg(cx.theme().colors().border),
3922 )
3923 }),
3924 )
3925 })
3926 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
3927 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
3928 })
3929 }
3930
3931 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3932 Label::new(label.into()).color(color).single_line()
3933 }
3934
3935 fn list_item_height(&self) -> Rems {
3936 rems(1.75)
3937 }
3938
3939 fn render_list_header(
3940 &self,
3941 ix: usize,
3942 header: &GitHeaderEntry,
3943 _: bool,
3944 _: &Window,
3945 _: &Context<Self>,
3946 ) -> AnyElement {
3947 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3948
3949 h_flex()
3950 .id(id)
3951 .h(self.list_item_height())
3952 .w_full()
3953 .items_end()
3954 .px(rems(0.75)) // ~12px
3955 .pb(rems(0.3125)) // ~ 5px
3956 .child(
3957 Label::new(header.title())
3958 .color(Color::Muted)
3959 .size(LabelSize::Small)
3960 .line_height_style(LineHeightStyle::UiLabel)
3961 .single_line(),
3962 )
3963 .into_any_element()
3964 }
3965
3966 pub fn load_commit_details(
3967 &self,
3968 sha: String,
3969 cx: &mut Context<Self>,
3970 ) -> Task<anyhow::Result<CommitDetails>> {
3971 let Some(repo) = self.active_repository.clone() else {
3972 return Task::ready(Err(anyhow::anyhow!("no active repo")));
3973 };
3974 repo.update(cx, |repo, cx| {
3975 let show = repo.show(sha);
3976 cx.spawn(async move |_, _| show.await?)
3977 })
3978 }
3979
3980 fn deploy_entry_context_menu(
3981 &mut self,
3982 position: Point<Pixels>,
3983 ix: usize,
3984 window: &mut Window,
3985 cx: &mut Context<Self>,
3986 ) {
3987 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
3988 return;
3989 };
3990 let stage_title = if entry.status.staging().is_fully_staged() {
3991 "Unstage File"
3992 } else {
3993 "Stage File"
3994 };
3995 let restore_title = if entry.status.is_created() {
3996 "Trash File"
3997 } else {
3998 "Restore File"
3999 };
4000 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4001 context_menu
4002 .context(self.focus_handle.clone())
4003 .action(stage_title, ToggleStaged.boxed_clone())
4004 .action(restore_title, git::RestoreFile::default().boxed_clone())
4005 .separator()
4006 .action("Open Diff", Confirm.boxed_clone())
4007 .action("Open File", SecondaryConfirm.boxed_clone())
4008 });
4009 self.selected_entry = Some(ix);
4010 self.set_context_menu(context_menu, position, window, cx);
4011 }
4012
4013 fn deploy_panel_context_menu(
4014 &mut self,
4015 position: Point<Pixels>,
4016 window: &mut Window,
4017 cx: &mut Context<Self>,
4018 ) {
4019 let context_menu = git_panel_context_menu(
4020 self.focus_handle.clone(),
4021 GitMenuState {
4022 has_tracked_changes: self.has_tracked_changes(),
4023 has_staged_changes: self.has_staged_changes(),
4024 has_unstaged_changes: self.has_unstaged_changes(),
4025 has_new_changes: self.new_count > 0,
4026 },
4027 window,
4028 cx,
4029 );
4030 self.set_context_menu(context_menu, position, window, cx);
4031 }
4032
4033 fn set_context_menu(
4034 &mut self,
4035 context_menu: Entity<ContextMenu>,
4036 position: Point<Pixels>,
4037 window: &Window,
4038 cx: &mut Context<Self>,
4039 ) {
4040 let subscription = cx.subscribe_in(
4041 &context_menu,
4042 window,
4043 |this, _, _: &DismissEvent, window, cx| {
4044 if this.context_menu.as_ref().is_some_and(|context_menu| {
4045 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4046 }) {
4047 cx.focus_self(window);
4048 }
4049 this.context_menu.take();
4050 cx.notify();
4051 },
4052 );
4053 self.context_menu = Some((context_menu, position, subscription));
4054 cx.notify();
4055 }
4056
4057 fn render_entry(
4058 &self,
4059 ix: usize,
4060 entry: &GitStatusEntry,
4061 has_write_access: bool,
4062 window: &Window,
4063 cx: &Context<Self>,
4064 ) -> AnyElement {
4065 let display_name = entry.display_name();
4066
4067 let selected = self.selected_entry == Some(ix);
4068 let marked = self.marked_entries.contains(&ix);
4069 let status_style = GitPanelSettings::get_global(cx).status_style;
4070 let status = entry.status;
4071
4072 let has_conflict = status.is_conflicted();
4073 let is_modified = status.is_modified();
4074 let is_deleted = status.is_deleted();
4075
4076 let label_color = if status_style == StatusStyle::LabelColor {
4077 if has_conflict {
4078 Color::VersionControlConflict
4079 } else if is_modified {
4080 Color::VersionControlModified
4081 } else if is_deleted {
4082 // We don't want a bunch of red labels in the list
4083 Color::Disabled
4084 } else {
4085 Color::VersionControlAdded
4086 }
4087 } else {
4088 Color::Default
4089 };
4090
4091 let path_color = if status.is_deleted() {
4092 Color::Disabled
4093 } else {
4094 Color::Muted
4095 };
4096
4097 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4098 let checkbox_wrapper_id: ElementId =
4099 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4100 let checkbox_id: ElementId =
4101 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4102
4103 let entry_staging = self.entry_staging(entry);
4104 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4105 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4106 is_staged = ToggleState::Selected;
4107 }
4108
4109 let handle = cx.weak_entity();
4110
4111 let selected_bg_alpha = 0.08;
4112 let marked_bg_alpha = 0.12;
4113 let state_opacity_step = 0.04;
4114
4115 let base_bg = match (selected, marked) {
4116 (true, true) => cx
4117 .theme()
4118 .status()
4119 .info
4120 .alpha(selected_bg_alpha + marked_bg_alpha),
4121 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4122 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4123 _ => cx.theme().colors().ghost_element_background,
4124 };
4125
4126 let hover_bg = if selected {
4127 cx.theme()
4128 .status()
4129 .info
4130 .alpha(selected_bg_alpha + state_opacity_step)
4131 } else {
4132 cx.theme().colors().ghost_element_hover
4133 };
4134
4135 let active_bg = if selected {
4136 cx.theme()
4137 .status()
4138 .info
4139 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4140 } else {
4141 cx.theme().colors().ghost_element_active
4142 };
4143
4144 h_flex()
4145 .id(id)
4146 .h(self.list_item_height())
4147 .w_full()
4148 .items_center()
4149 .border_1()
4150 .when(selected && self.focus_handle.is_focused(window), |el| {
4151 el.border_color(cx.theme().colors().border_focused)
4152 })
4153 .px(rems(0.75)) // ~12px
4154 .overflow_hidden()
4155 .flex_none()
4156 .gap_1p5()
4157 .bg(base_bg)
4158 .hover(|this| this.bg(hover_bg))
4159 .active(|this| this.bg(active_bg))
4160 .on_click({
4161 cx.listener(move |this, event: &ClickEvent, window, cx| {
4162 this.selected_entry = Some(ix);
4163 cx.notify();
4164 if event.modifiers().secondary() {
4165 this.open_file(&Default::default(), window, cx)
4166 } else {
4167 this.open_diff(&Default::default(), window, cx);
4168 this.focus_handle.focus(window);
4169 }
4170 })
4171 })
4172 .on_mouse_down(
4173 MouseButton::Right,
4174 move |event: &MouseDownEvent, window, cx| {
4175 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4176 if event.button != MouseButton::Right {
4177 return;
4178 }
4179
4180 let Some(this) = handle.upgrade() else {
4181 return;
4182 };
4183 this.update(cx, |this, cx| {
4184 this.deploy_entry_context_menu(event.position, ix, window, cx);
4185 });
4186 cx.stop_propagation();
4187 },
4188 )
4189 .child(
4190 div()
4191 .id(checkbox_wrapper_id)
4192 .flex_none()
4193 .occlude()
4194 .cursor_pointer()
4195 .child(
4196 Checkbox::new(checkbox_id, is_staged)
4197 .disabled(!has_write_access)
4198 .fill()
4199 .elevation(ElevationIndex::Surface)
4200 .on_click_ext({
4201 let entry = entry.clone();
4202 let this = cx.weak_entity();
4203 move |_, click, window, cx| {
4204 this.update(cx, |this, cx| {
4205 if !has_write_access {
4206 return;
4207 }
4208 if click.modifiers().shift {
4209 this.stage_bulk(ix, cx);
4210 } else {
4211 this.toggle_staged_for_entry(
4212 &GitListEntry::Status(entry.clone()),
4213 window,
4214 cx,
4215 );
4216 }
4217 cx.stop_propagation();
4218 })
4219 .ok();
4220 }
4221 })
4222 .tooltip(move |window, cx| {
4223 let is_staged = entry_staging.is_fully_staged();
4224
4225 let action = if is_staged { "Unstage" } else { "Stage" };
4226 let tooltip_name = action.to_string();
4227
4228 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4229 }),
4230 ),
4231 )
4232 .child(git_status_icon(status))
4233 .child(
4234 h_flex()
4235 .items_center()
4236 .flex_1()
4237 // .overflow_hidden()
4238 .when_some(entry.parent_dir(), |this, parent| {
4239 if !parent.is_empty() {
4240 this.child(
4241 self.entry_label(format!("{}/", parent), path_color)
4242 .when(status.is_deleted(), |this| this.strikethrough()),
4243 )
4244 } else {
4245 this
4246 }
4247 })
4248 .child(
4249 self.entry_label(display_name.clone(), label_color)
4250 .when(status.is_deleted(), |this| this.strikethrough()),
4251 ),
4252 )
4253 .into_any_element()
4254 }
4255
4256 fn has_write_access(&self, cx: &App) -> bool {
4257 !self.project.read(cx).is_read_only(cx)
4258 }
4259
4260 pub fn amend_pending(&self) -> bool {
4261 self.amend_pending
4262 }
4263
4264 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4265 self.amend_pending = value;
4266 cx.notify();
4267 }
4268
4269 pub fn toggle_amend_pending(
4270 &mut self,
4271 _: &Amend,
4272 _window: &mut Window,
4273 cx: &mut Context<Self>,
4274 ) {
4275 self.set_amend_pending(!self.amend_pending, cx);
4276 self.serialize(cx);
4277 }
4278
4279 pub fn signoff_enabled(&self) -> bool {
4280 self.signoff_enabled
4281 }
4282
4283 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4284 self.signoff_enabled = value;
4285 self.serialize(cx);
4286 cx.notify();
4287 }
4288
4289 pub fn toggle_signoff_enabled(
4290 &mut self,
4291 _: &Signoff,
4292 _window: &mut Window,
4293 cx: &mut Context<Self>,
4294 ) {
4295 self.set_signoff_enabled(!self.signoff_enabled, cx);
4296 }
4297
4298 pub async fn load(
4299 workspace: WeakEntity<Workspace>,
4300 mut cx: AsyncWindowContext,
4301 ) -> anyhow::Result<Entity<Self>> {
4302 let serialized_panel = match workspace
4303 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4304 .ok()
4305 .flatten()
4306 {
4307 Some(serialization_key) => cx
4308 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4309 .await
4310 .context("loading git panel")
4311 .log_err()
4312 .flatten()
4313 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4314 .transpose()
4315 .log_err()
4316 .flatten(),
4317 None => None,
4318 };
4319
4320 workspace.update_in(&mut cx, |workspace, window, cx| {
4321 let panel = GitPanel::new(workspace, window, cx);
4322
4323 if let Some(serialized_panel) = serialized_panel {
4324 panel.update(cx, |panel, cx| {
4325 panel.width = serialized_panel.width;
4326 panel.amend_pending = serialized_panel.amend_pending;
4327 panel.signoff_enabled = serialized_panel.signoff_enabled;
4328 cx.notify();
4329 })
4330 }
4331
4332 panel
4333 })
4334 }
4335
4336 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4337 let Some(op) = self.bulk_staging.as_ref() else {
4338 return;
4339 };
4340 let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4341 return;
4342 };
4343 if let Some(entry) = self.entries.get(index)
4344 && let Some(entry) = entry.status_entry()
4345 {
4346 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4347 }
4348 if index < anchor_index {
4349 std::mem::swap(&mut index, &mut anchor_index);
4350 }
4351 let entries = self
4352 .entries
4353 .get(anchor_index..=index)
4354 .unwrap_or_default()
4355 .iter()
4356 .filter_map(|entry| entry.status_entry().cloned())
4357 .collect::<Vec<_>>();
4358 self.change_file_stage(true, entries, cx);
4359 }
4360
4361 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4362 let Some(repo) = self.active_repository.as_ref() else {
4363 return;
4364 };
4365 self.bulk_staging = Some(BulkStaging {
4366 repo_id: repo.read(cx).id,
4367 anchor: path,
4368 });
4369 }
4370}
4371
4372fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
4373 let is_enabled = agent_settings::AgentSettings::get_global(cx).enabled
4374 && !DisableAiSettings::get_global(cx).disable_ai;
4375
4376 is_enabled
4377 .then(|| {
4378 let ConfiguredModel { provider, model } =
4379 LanguageModelRegistry::read_global(cx).commit_message_model()?;
4380
4381 provider.is_authenticated(cx).then(|| model)
4382 })
4383 .flatten()
4384}
4385
4386impl Render for GitPanel {
4387 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4388 let project = self.project.read(cx);
4389 let has_entries = self.entries.len() > 0;
4390 let room = self
4391 .workspace
4392 .upgrade()
4393 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4394
4395 let has_write_access = self.has_write_access(cx);
4396
4397 let has_co_authors = room.map_or(false, |room| {
4398 self.load_local_committer(cx);
4399 let room = room.read(cx);
4400 room.remote_participants()
4401 .values()
4402 .any(|remote_participant| remote_participant.can_write())
4403 });
4404
4405 v_flex()
4406 .id("git_panel")
4407 .key_context(self.dispatch_context(window, cx))
4408 .track_focus(&self.focus_handle)
4409 .when(has_write_access && !project.is_read_only(cx), |this| {
4410 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4411 .on_action(cx.listener(Self::stage_range))
4412 .on_action(cx.listener(GitPanel::commit))
4413 .on_action(cx.listener(GitPanel::amend))
4414 .on_action(cx.listener(GitPanel::toggle_amend_pending))
4415 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4416 .on_action(cx.listener(Self::stage_all))
4417 .on_action(cx.listener(Self::unstage_all))
4418 .on_action(cx.listener(Self::stage_selected))
4419 .on_action(cx.listener(Self::unstage_selected))
4420 .on_action(cx.listener(Self::restore_tracked_files))
4421 .on_action(cx.listener(Self::revert_selected))
4422 .on_action(cx.listener(Self::clean_all))
4423 .on_action(cx.listener(Self::generate_commit_message_action))
4424 .on_action(cx.listener(Self::stash_all))
4425 .on_action(cx.listener(Self::stash_pop))
4426 })
4427 .on_action(cx.listener(Self::select_first))
4428 .on_action(cx.listener(Self::select_next))
4429 .on_action(cx.listener(Self::select_previous))
4430 .on_action(cx.listener(Self::select_last))
4431 .on_action(cx.listener(Self::close_panel))
4432 .on_action(cx.listener(Self::open_diff))
4433 .on_action(cx.listener(Self::open_file))
4434 .on_action(cx.listener(Self::focus_changes_list))
4435 .on_action(cx.listener(Self::focus_editor))
4436 .on_action(cx.listener(Self::expand_commit_editor))
4437 .when(has_write_access && has_co_authors, |git_panel| {
4438 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4439 })
4440 .on_hover(cx.listener(move |this, hovered, window, cx| {
4441 if *hovered {
4442 this.horizontal_scrollbar.show(cx);
4443 this.vertical_scrollbar.show(cx);
4444 cx.notify();
4445 } else if !this.focus_handle.contains_focused(window, cx) {
4446 this.hide_scrollbars(window, cx);
4447 }
4448 }))
4449 .size_full()
4450 .overflow_hidden()
4451 .bg(cx.theme().colors().panel_background)
4452 .child(
4453 v_flex()
4454 .size_full()
4455 .children(self.render_panel_header(window, cx))
4456 .map(|this| {
4457 if has_entries {
4458 this.child(self.render_entries(has_write_access, window, cx))
4459 } else {
4460 this.child(self.render_empty_state(cx).into_any_element())
4461 }
4462 })
4463 .children(self.render_footer(window, cx))
4464 .when(self.amend_pending, |this| {
4465 this.child(self.render_pending_amend(cx))
4466 })
4467 .when(!self.amend_pending, |this| {
4468 this.children(self.render_previous_commit(cx))
4469 })
4470 .into_any_element(),
4471 )
4472 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4473 deferred(
4474 anchored()
4475 .position(*position)
4476 .anchor(Corner::TopLeft)
4477 .child(menu.clone()),
4478 )
4479 .with_priority(1)
4480 }))
4481 }
4482}
4483
4484impl Focusable for GitPanel {
4485 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4486 if self.entries.is_empty() {
4487 self.commit_editor.focus_handle(cx)
4488 } else {
4489 self.focus_handle.clone()
4490 }
4491 }
4492}
4493
4494impl EventEmitter<Event> for GitPanel {}
4495
4496impl EventEmitter<PanelEvent> for GitPanel {}
4497
4498pub(crate) struct GitPanelAddon {
4499 pub(crate) workspace: WeakEntity<Workspace>,
4500}
4501
4502impl editor::Addon for GitPanelAddon {
4503 fn to_any(&self) -> &dyn std::any::Any {
4504 self
4505 }
4506
4507 fn render_buffer_header_controls(
4508 &self,
4509 excerpt_info: &ExcerptInfo,
4510 window: &Window,
4511 cx: &App,
4512 ) -> Option<AnyElement> {
4513 let file = excerpt_info.buffer.file()?;
4514 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4515
4516 git_panel
4517 .read(cx)
4518 .render_buffer_header_controls(&git_panel, &file, window, cx)
4519 }
4520}
4521
4522impl Panel for GitPanel {
4523 fn persistent_name() -> &'static str {
4524 "GitPanel"
4525 }
4526
4527 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4528 GitPanelSettings::get_global(cx).dock
4529 }
4530
4531 fn position_is_valid(&self, position: DockPosition) -> bool {
4532 matches!(position, DockPosition::Left | DockPosition::Right)
4533 }
4534
4535 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4536 settings::update_settings_file::<GitPanelSettings>(
4537 self.fs.clone(),
4538 cx,
4539 move |settings, _| settings.dock = Some(position),
4540 );
4541 }
4542
4543 fn size(&self, _: &Window, cx: &App) -> Pixels {
4544 self.width
4545 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4546 }
4547
4548 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4549 self.width = size;
4550 self.serialize(cx);
4551 cx.notify();
4552 }
4553
4554 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4555 Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
4556 }
4557
4558 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4559 Some("Git Panel")
4560 }
4561
4562 fn toggle_action(&self) -> Box<dyn Action> {
4563 Box::new(ToggleFocus)
4564 }
4565
4566 fn activation_priority(&self) -> u32 {
4567 2
4568 }
4569}
4570
4571impl PanelHeader for GitPanel {}
4572
4573struct GitPanelMessageTooltip {
4574 commit_tooltip: Option<Entity<CommitTooltip>>,
4575}
4576
4577impl GitPanelMessageTooltip {
4578 fn new(
4579 git_panel: Entity<GitPanel>,
4580 sha: SharedString,
4581 repository: Entity<Repository>,
4582 window: &mut Window,
4583 cx: &mut App,
4584 ) -> Entity<Self> {
4585 cx.new(|cx| {
4586 cx.spawn_in(window, async move |this, cx| {
4587 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4588 (
4589 git_panel.load_commit_details(sha.to_string(), cx),
4590 git_panel.workspace.clone(),
4591 )
4592 })?;
4593 let details = details.await?;
4594
4595 let commit_details = crate::commit_tooltip::CommitDetails {
4596 sha: details.sha.clone(),
4597 author_name: details.author_name.clone(),
4598 author_email: details.author_email.clone(),
4599 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4600 message: Some(ParsedCommitMessage {
4601 message: details.message.clone(),
4602 ..Default::default()
4603 }),
4604 };
4605
4606 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4607 this.commit_tooltip = Some(cx.new(move |cx| {
4608 CommitTooltip::new(commit_details, repository, workspace, cx)
4609 }));
4610 cx.notify();
4611 })
4612 })
4613 .detach();
4614
4615 Self {
4616 commit_tooltip: None,
4617 }
4618 })
4619 }
4620}
4621
4622impl Render for GitPanelMessageTooltip {
4623 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4624 if let Some(commit_tooltip) = &self.commit_tooltip {
4625 commit_tooltip.clone().into_any_element()
4626 } else {
4627 gpui::Empty.into_any_element()
4628 }
4629 }
4630}
4631
4632#[derive(IntoElement, RegisterComponent)]
4633pub struct PanelRepoFooter {
4634 active_repository: SharedString,
4635 branch: Option<Branch>,
4636 head_commit: Option<CommitDetails>,
4637
4638 // Getting a GitPanel in previews will be difficult.
4639 //
4640 // For now just take an option here, and we won't bind handlers to buttons in previews.
4641 git_panel: Option<Entity<GitPanel>>,
4642}
4643
4644impl PanelRepoFooter {
4645 pub fn new(
4646 active_repository: SharedString,
4647 branch: Option<Branch>,
4648 head_commit: Option<CommitDetails>,
4649 git_panel: Option<Entity<GitPanel>>,
4650 ) -> Self {
4651 Self {
4652 active_repository,
4653 branch,
4654 head_commit,
4655 git_panel,
4656 }
4657 }
4658
4659 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4660 Self {
4661 active_repository,
4662 branch,
4663 head_commit: None,
4664 git_panel: None,
4665 }
4666 }
4667}
4668
4669impl RenderOnce for PanelRepoFooter {
4670 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4671 let project = self
4672 .git_panel
4673 .as_ref()
4674 .map(|panel| panel.read(cx).project.clone());
4675
4676 let repo = self
4677 .git_panel
4678 .as_ref()
4679 .and_then(|panel| panel.read(cx).active_repository.clone());
4680
4681 let single_repo = project
4682 .as_ref()
4683 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4684 .unwrap_or(true);
4685
4686 const MAX_BRANCH_LEN: usize = 16;
4687 const MAX_REPO_LEN: usize = 16;
4688 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4689 const MAX_SHORT_SHA_LEN: usize = 8;
4690
4691 let branch_name = self
4692 .branch
4693 .as_ref()
4694 .map(|branch| branch.name().to_owned())
4695 .or_else(|| {
4696 self.head_commit.as_ref().map(|commit| {
4697 commit
4698 .sha
4699 .chars()
4700 .take(MAX_SHORT_SHA_LEN)
4701 .collect::<String>()
4702 })
4703 })
4704 .unwrap_or_else(|| " (no branch)".to_owned());
4705 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4706
4707 let active_repo_name = self.active_repository.clone();
4708
4709 let branch_actual_len = branch_name.len();
4710 let repo_actual_len = active_repo_name.len();
4711
4712 // ideally, show the whole branch and repo names but
4713 // when we can't, use a budget to allocate space between the two
4714 let (repo_display_len, branch_display_len) = if branch_actual_len + repo_actual_len
4715 <= LABEL_CHARACTER_BUDGET
4716 {
4717 (repo_actual_len, branch_actual_len)
4718 } else {
4719 if branch_actual_len <= MAX_BRANCH_LEN {
4720 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4721 (repo_space, branch_actual_len)
4722 } else if repo_actual_len <= MAX_REPO_LEN {
4723 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4724 (repo_actual_len, branch_space)
4725 } else {
4726 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4727 }
4728 };
4729
4730 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4731 active_repo_name.to_string()
4732 } else {
4733 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4734 };
4735
4736 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4737 branch_name.to_string()
4738 } else {
4739 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4740 };
4741
4742 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4743 .style(ButtonStyle::Transparent)
4744 .size(ButtonSize::None)
4745 .label_size(LabelSize::Small)
4746 .color(Color::Muted);
4747
4748 let repo_selector = PopoverMenu::new("repository-switcher")
4749 .menu({
4750 let project = project.clone();
4751 move |window, cx| {
4752 let project = project.clone()?;
4753 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4754 }
4755 })
4756 .trigger_with_tooltip(
4757 repo_selector_trigger.disabled(single_repo).truncate(true),
4758 Tooltip::text("Switch Active Repository"),
4759 )
4760 .anchor(Corner::BottomLeft)
4761 .into_any_element();
4762
4763 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4764 .style(ButtonStyle::Transparent)
4765 .size(ButtonSize::None)
4766 .label_size(LabelSize::Small)
4767 .truncate(true)
4768 .tooltip(Tooltip::for_action_title(
4769 "Switch Branch",
4770 &zed_actions::git::Switch,
4771 ))
4772 .on_click(|_, window, cx| {
4773 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4774 });
4775
4776 let branch_selector = PopoverMenu::new("popover-button")
4777 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4778 .trigger_with_tooltip(
4779 branch_selector_button,
4780 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4781 )
4782 .anchor(Corner::BottomLeft)
4783 .offset(gpui::Point {
4784 x: px(0.0),
4785 y: px(-2.0),
4786 });
4787
4788 h_flex()
4789 .w_full()
4790 .px_2()
4791 .h(px(36.))
4792 .items_center()
4793 .justify_between()
4794 .gap_1()
4795 .child(
4796 h_flex()
4797 .flex_1()
4798 .overflow_hidden()
4799 .items_center()
4800 .child(
4801 div().child(
4802 Icon::new(IconName::GitBranchSmall)
4803 .size(IconSize::Small)
4804 .color(if single_repo {
4805 Color::Disabled
4806 } else {
4807 Color::Muted
4808 }),
4809 ),
4810 )
4811 .child(repo_selector)
4812 .when(show_separator, |this| {
4813 this.child(
4814 div()
4815 .text_color(cx.theme().colors().text_muted)
4816 .text_sm()
4817 .child("/"),
4818 )
4819 })
4820 .child(branch_selector),
4821 )
4822 .children(if let Some(git_panel) = self.git_panel {
4823 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4824 } else {
4825 None
4826 })
4827 }
4828}
4829
4830impl Component for PanelRepoFooter {
4831 fn scope() -> ComponentScope {
4832 ComponentScope::VersionControl
4833 }
4834
4835 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4836 let unknown_upstream = None;
4837 let no_remote_upstream = Some(UpstreamTracking::Gone);
4838 let ahead_of_upstream = Some(
4839 UpstreamTrackingStatus {
4840 ahead: 2,
4841 behind: 0,
4842 }
4843 .into(),
4844 );
4845 let behind_upstream = Some(
4846 UpstreamTrackingStatus {
4847 ahead: 0,
4848 behind: 2,
4849 }
4850 .into(),
4851 );
4852 let ahead_and_behind_upstream = Some(
4853 UpstreamTrackingStatus {
4854 ahead: 3,
4855 behind: 1,
4856 }
4857 .into(),
4858 );
4859
4860 let not_ahead_or_behind_upstream = Some(
4861 UpstreamTrackingStatus {
4862 ahead: 0,
4863 behind: 0,
4864 }
4865 .into(),
4866 );
4867
4868 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4869 Branch {
4870 is_head: true,
4871 ref_name: "some-branch".into(),
4872 upstream: upstream.map(|tracking| Upstream {
4873 ref_name: "origin/some-branch".into(),
4874 tracking,
4875 }),
4876 most_recent_commit: Some(CommitSummary {
4877 sha: "abc123".into(),
4878 subject: "Modify stuff".into(),
4879 commit_timestamp: 1710932954,
4880 has_parent: true,
4881 }),
4882 }
4883 }
4884
4885 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4886 Branch {
4887 is_head: true,
4888 ref_name: branch_name.to_string().into(),
4889 upstream: upstream.map(|tracking| Upstream {
4890 ref_name: format!("zed/{}", branch_name).into(),
4891 tracking,
4892 }),
4893 most_recent_commit: Some(CommitSummary {
4894 sha: "abc123".into(),
4895 subject: "Modify stuff".into(),
4896 commit_timestamp: 1710932954,
4897 has_parent: true,
4898 }),
4899 }
4900 }
4901
4902 fn active_repository(id: usize) -> SharedString {
4903 format!("repo-{}", id).into()
4904 }
4905
4906 let example_width = px(340.);
4907 Some(
4908 v_flex()
4909 .gap_6()
4910 .w_full()
4911 .flex_none()
4912 .children(vec![
4913 example_group_with_title(
4914 "Action Button States",
4915 vec![
4916 single_example(
4917 "No Branch",
4918 div()
4919 .w(example_width)
4920 .overflow_hidden()
4921 .child(PanelRepoFooter::new_preview(
4922 active_repository(1).clone(),
4923 None,
4924 ))
4925 .into_any_element(),
4926 ),
4927 single_example(
4928 "Remote status unknown",
4929 div()
4930 .w(example_width)
4931 .overflow_hidden()
4932 .child(PanelRepoFooter::new_preview(
4933 active_repository(2).clone(),
4934 Some(branch(unknown_upstream)),
4935 ))
4936 .into_any_element(),
4937 ),
4938 single_example(
4939 "No Remote Upstream",
4940 div()
4941 .w(example_width)
4942 .overflow_hidden()
4943 .child(PanelRepoFooter::new_preview(
4944 active_repository(3).clone(),
4945 Some(branch(no_remote_upstream)),
4946 ))
4947 .into_any_element(),
4948 ),
4949 single_example(
4950 "Not Ahead or Behind",
4951 div()
4952 .w(example_width)
4953 .overflow_hidden()
4954 .child(PanelRepoFooter::new_preview(
4955 active_repository(4).clone(),
4956 Some(branch(not_ahead_or_behind_upstream)),
4957 ))
4958 .into_any_element(),
4959 ),
4960 single_example(
4961 "Behind remote",
4962 div()
4963 .w(example_width)
4964 .overflow_hidden()
4965 .child(PanelRepoFooter::new_preview(
4966 active_repository(5).clone(),
4967 Some(branch(behind_upstream)),
4968 ))
4969 .into_any_element(),
4970 ),
4971 single_example(
4972 "Ahead of remote",
4973 div()
4974 .w(example_width)
4975 .overflow_hidden()
4976 .child(PanelRepoFooter::new_preview(
4977 active_repository(6).clone(),
4978 Some(branch(ahead_of_upstream)),
4979 ))
4980 .into_any_element(),
4981 ),
4982 single_example(
4983 "Ahead and behind remote",
4984 div()
4985 .w(example_width)
4986 .overflow_hidden()
4987 .child(PanelRepoFooter::new_preview(
4988 active_repository(7).clone(),
4989 Some(branch(ahead_and_behind_upstream)),
4990 ))
4991 .into_any_element(),
4992 ),
4993 ],
4994 )
4995 .grow()
4996 .vertical(),
4997 ])
4998 .children(vec![
4999 example_group_with_title(
5000 "Labels",
5001 vec![
5002 single_example(
5003 "Short Branch & Repo",
5004 div()
5005 .w(example_width)
5006 .overflow_hidden()
5007 .child(PanelRepoFooter::new_preview(
5008 SharedString::from("zed"),
5009 Some(custom("main", behind_upstream)),
5010 ))
5011 .into_any_element(),
5012 ),
5013 single_example(
5014 "Long Branch",
5015 div()
5016 .w(example_width)
5017 .overflow_hidden()
5018 .child(PanelRepoFooter::new_preview(
5019 SharedString::from("zed"),
5020 Some(custom(
5021 "redesign-and-update-git-ui-list-entry-style",
5022 behind_upstream,
5023 )),
5024 ))
5025 .into_any_element(),
5026 ),
5027 single_example(
5028 "Long Repo",
5029 div()
5030 .w(example_width)
5031 .overflow_hidden()
5032 .child(PanelRepoFooter::new_preview(
5033 SharedString::from("zed-industries-community-examples"),
5034 Some(custom("gpui", ahead_of_upstream)),
5035 ))
5036 .into_any_element(),
5037 ),
5038 single_example(
5039 "Long Repo & Branch",
5040 div()
5041 .w(example_width)
5042 .overflow_hidden()
5043 .child(PanelRepoFooter::new_preview(
5044 SharedString::from("zed-industries-community-examples"),
5045 Some(custom(
5046 "redesign-and-update-git-ui-list-entry-style",
5047 behind_upstream,
5048 )),
5049 ))
5050 .into_any_element(),
5051 ),
5052 single_example(
5053 "Uppercase Repo",
5054 div()
5055 .w(example_width)
5056 .overflow_hidden()
5057 .child(PanelRepoFooter::new_preview(
5058 SharedString::from("LICENSES"),
5059 Some(custom("main", ahead_of_upstream)),
5060 ))
5061 .into_any_element(),
5062 ),
5063 single_example(
5064 "Uppercase Branch",
5065 div()
5066 .w(example_width)
5067 .overflow_hidden()
5068 .child(PanelRepoFooter::new_preview(
5069 SharedString::from("zed"),
5070 Some(custom("update-README", behind_upstream)),
5071 ))
5072 .into_any_element(),
5073 ),
5074 ],
5075 )
5076 .grow()
5077 .vertical(),
5078 ])
5079 .into_any_element(),
5080 )
5081 }
5082}
5083
5084#[cfg(test)]
5085mod tests {
5086 use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
5087 use gpui::{TestAppContext, VisualTestContext};
5088 use project::{FakeFs, WorktreeSettings};
5089 use serde_json::json;
5090 use settings::SettingsStore;
5091 use theme::LoadThemes;
5092 use util::path;
5093
5094 use super::*;
5095
5096 fn init_test(cx: &mut gpui::TestAppContext) {
5097 zlog::init_test();
5098
5099 cx.update(|cx| {
5100 let settings_store = SettingsStore::test(cx);
5101 cx.set_global(settings_store);
5102 AgentSettings::register(cx);
5103 WorktreeSettings::register(cx);
5104 workspace::init_settings(cx);
5105 theme::init(LoadThemes::JustBase, cx);
5106 language::init(cx);
5107 editor::init(cx);
5108 Project::init_settings(cx);
5109 client::DisableAiSettings::register(cx);
5110 crate::init(cx);
5111 });
5112 }
5113
5114 #[gpui::test]
5115 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5116 init_test(cx);
5117 let fs = FakeFs::new(cx.background_executor.clone());
5118 fs.insert_tree(
5119 "/root",
5120 json!({
5121 "zed": {
5122 ".git": {},
5123 "crates": {
5124 "gpui": {
5125 "gpui.rs": "fn main() {}"
5126 },
5127 "util": {
5128 "util.rs": "fn do_it() {}"
5129 }
5130 }
5131 },
5132 }),
5133 )
5134 .await;
5135
5136 fs.set_status_for_repo(
5137 Path::new(path!("/root/zed/.git")),
5138 &[
5139 (
5140 Path::new("crates/gpui/gpui.rs"),
5141 StatusCode::Modified.worktree(),
5142 ),
5143 (
5144 Path::new("crates/util/util.rs"),
5145 StatusCode::Modified.worktree(),
5146 ),
5147 ],
5148 );
5149
5150 let project =
5151 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5152 let workspace =
5153 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5154 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5155
5156 cx.read(|cx| {
5157 project
5158 .read(cx)
5159 .worktrees(cx)
5160 .nth(0)
5161 .unwrap()
5162 .read(cx)
5163 .as_local()
5164 .unwrap()
5165 .scan_complete()
5166 })
5167 .await;
5168
5169 cx.executor().run_until_parked();
5170
5171 let panel = workspace.update(cx, GitPanel::new).unwrap();
5172
5173 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5174 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5175 });
5176 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5177 handle.await;
5178
5179 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5180 pretty_assertions::assert_eq!(
5181 entries,
5182 [
5183 GitListEntry::Header(GitHeaderEntry {
5184 header: Section::Tracked
5185 }),
5186 GitListEntry::Status(GitStatusEntry {
5187 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5188 repo_path: "crates/gpui/gpui.rs".into(),
5189 status: StatusCode::Modified.worktree(),
5190 staging: StageStatus::Unstaged,
5191 }),
5192 GitListEntry::Status(GitStatusEntry {
5193 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5194 repo_path: "crates/util/util.rs".into(),
5195 status: StatusCode::Modified.worktree(),
5196 staging: StageStatus::Unstaged,
5197 },),
5198 ],
5199 );
5200
5201 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5202 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5203 });
5204 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5205 handle.await;
5206 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5207 pretty_assertions::assert_eq!(
5208 entries,
5209 [
5210 GitListEntry::Header(GitHeaderEntry {
5211 header: Section::Tracked
5212 }),
5213 GitListEntry::Status(GitStatusEntry {
5214 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5215 repo_path: "crates/gpui/gpui.rs".into(),
5216 status: StatusCode::Modified.worktree(),
5217 staging: StageStatus::Unstaged,
5218 }),
5219 GitListEntry::Status(GitStatusEntry {
5220 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5221 repo_path: "crates/util/util.rs".into(),
5222 status: StatusCode::Modified.worktree(),
5223 staging: StageStatus::Unstaged,
5224 },),
5225 ],
5226 );
5227 }
5228
5229 #[gpui::test]
5230 async fn test_bulk_staging(cx: &mut TestAppContext) {
5231 use GitListEntry::*;
5232
5233 init_test(cx);
5234 let fs = FakeFs::new(cx.background_executor.clone());
5235 fs.insert_tree(
5236 "/root",
5237 json!({
5238 "project": {
5239 ".git": {},
5240 "src": {
5241 "main.rs": "fn main() {}",
5242 "lib.rs": "pub fn hello() {}",
5243 "utils.rs": "pub fn util() {}"
5244 },
5245 "tests": {
5246 "test.rs": "fn test() {}"
5247 },
5248 "new_file.txt": "new content",
5249 "another_new.rs": "// new file",
5250 "conflict.txt": "conflicted content"
5251 }
5252 }),
5253 )
5254 .await;
5255
5256 fs.set_status_for_repo(
5257 Path::new(path!("/root/project/.git")),
5258 &[
5259 (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5260 (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5261 (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5262 (Path::new("new_file.txt"), FileStatus::Untracked),
5263 (Path::new("another_new.rs"), FileStatus::Untracked),
5264 (Path::new("src/utils.rs"), FileStatus::Untracked),
5265 (
5266 Path::new("conflict.txt"),
5267 UnmergedStatus {
5268 first_head: UnmergedStatusCode::Updated,
5269 second_head: UnmergedStatusCode::Updated,
5270 }
5271 .into(),
5272 ),
5273 ],
5274 );
5275
5276 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5277 let workspace =
5278 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5279 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5280
5281 cx.read(|cx| {
5282 project
5283 .read(cx)
5284 .worktrees(cx)
5285 .nth(0)
5286 .unwrap()
5287 .read(cx)
5288 .as_local()
5289 .unwrap()
5290 .scan_complete()
5291 })
5292 .await;
5293
5294 cx.executor().run_until_parked();
5295
5296 let panel = workspace.update(cx, GitPanel::new).unwrap();
5297
5298 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5299 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5300 });
5301 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5302 handle.await;
5303
5304 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5305 #[rustfmt::skip]
5306 pretty_assertions::assert_matches!(
5307 entries.as_slice(),
5308 &[
5309 Header(GitHeaderEntry { header: Section::Conflict }),
5310 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5311 Header(GitHeaderEntry { header: Section::Tracked }),
5312 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5313 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5314 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5315 Header(GitHeaderEntry { header: Section::New }),
5316 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5317 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5318 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5319 ],
5320 );
5321
5322 let second_status_entry = entries[3].clone();
5323 panel.update_in(cx, |panel, window, cx| {
5324 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5325 });
5326
5327 panel.update_in(cx, |panel, window, cx| {
5328 panel.selected_entry = Some(7);
5329 panel.stage_range(&git::StageRange, window, cx);
5330 });
5331
5332 cx.read(|cx| {
5333 project
5334 .read(cx)
5335 .worktrees(cx)
5336 .nth(0)
5337 .unwrap()
5338 .read(cx)
5339 .as_local()
5340 .unwrap()
5341 .scan_complete()
5342 })
5343 .await;
5344
5345 cx.executor().run_until_parked();
5346
5347 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5348 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5349 });
5350 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5351 handle.await;
5352
5353 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5354 #[rustfmt::skip]
5355 pretty_assertions::assert_matches!(
5356 entries.as_slice(),
5357 &[
5358 Header(GitHeaderEntry { header: Section::Conflict }),
5359 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5360 Header(GitHeaderEntry { header: Section::Tracked }),
5361 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5362 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5363 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5364 Header(GitHeaderEntry { header: Section::New }),
5365 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5366 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5367 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5368 ],
5369 );
5370
5371 let third_status_entry = entries[4].clone();
5372 panel.update_in(cx, |panel, window, cx| {
5373 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5374 });
5375
5376 panel.update_in(cx, |panel, window, cx| {
5377 panel.selected_entry = Some(9);
5378 panel.stage_range(&git::StageRange, window, cx);
5379 });
5380
5381 cx.read(|cx| {
5382 project
5383 .read(cx)
5384 .worktrees(cx)
5385 .nth(0)
5386 .unwrap()
5387 .read(cx)
5388 .as_local()
5389 .unwrap()
5390 .scan_complete()
5391 })
5392 .await;
5393
5394 cx.executor().run_until_parked();
5395
5396 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5397 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5398 });
5399 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5400 handle.await;
5401
5402 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5403 #[rustfmt::skip]
5404 pretty_assertions::assert_matches!(
5405 entries.as_slice(),
5406 &[
5407 Header(GitHeaderEntry { header: Section::Conflict }),
5408 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5409 Header(GitHeaderEntry { header: Section::Tracked }),
5410 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5411 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5412 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5413 Header(GitHeaderEntry { header: Section::New }),
5414 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5415 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5416 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5417 ],
5418 );
5419 }
5420}