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