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() {
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() {
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 {
3316 "Amend Tracked"
3317 }
3318 } else if self.has_staged_changes() {
3319 "Commit"
3320 } else {
3321 "Commit Tracked"
3322 }
3323 }
3324
3325 fn expand_commit_editor(
3326 &mut self,
3327 _: &git::ExpandCommitEditor,
3328 window: &mut Window,
3329 cx: &mut Context<Self>,
3330 ) {
3331 let workspace = self.workspace.clone();
3332 window.defer(cx, move |window, cx| {
3333 workspace
3334 .update(cx, |workspace, cx| {
3335 CommitModal::toggle(workspace, None, window, cx)
3336 })
3337 .ok();
3338 })
3339 }
3340
3341 fn render_panel_header(
3342 &self,
3343 window: &mut Window,
3344 cx: &mut Context<Self>,
3345 ) -> Option<impl IntoElement> {
3346 self.active_repository.as_ref()?;
3347
3348 let text;
3349 let action;
3350 let tooltip;
3351 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3352 text = "Unstage All";
3353 action = git::UnstageAll.boxed_clone();
3354 tooltip = "git reset";
3355 } else {
3356 text = "Stage All";
3357 action = git::StageAll.boxed_clone();
3358 tooltip = "git add --all ."
3359 }
3360
3361 let change_string = match self.entry_count {
3362 0 => "No Changes".to_string(),
3363 1 => "1 Change".to_string(),
3364 _ => format!("{} Changes", self.entry_count),
3365 };
3366
3367 Some(
3368 self.panel_header_container(window, cx)
3369 .px_2()
3370 .justify_between()
3371 .child(
3372 panel_button(change_string)
3373 .color(Color::Muted)
3374 .tooltip(Tooltip::for_action_title_in(
3375 "Open Diff",
3376 &Diff,
3377 &self.focus_handle,
3378 ))
3379 .on_click(|_, _, cx| {
3380 cx.defer(|cx| {
3381 cx.dispatch_action(&Diff);
3382 })
3383 }),
3384 )
3385 .child(
3386 h_flex()
3387 .gap_1()
3388 .child(self.render_overflow_menu("overflow_menu"))
3389 .child(
3390 panel_filled_button(text)
3391 .tooltip(Tooltip::for_action_title_in(
3392 tooltip,
3393 action.as_ref(),
3394 &self.focus_handle,
3395 ))
3396 .disabled(self.entry_count == 0)
3397 .on_click(move |_, _, cx| {
3398 let action = action.boxed_clone();
3399 cx.defer(move |cx| {
3400 cx.dispatch_action(action.as_ref());
3401 })
3402 }),
3403 ),
3404 ),
3405 )
3406 }
3407
3408 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3409 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3410 if !self.can_push_and_pull(cx) {
3411 return None;
3412 }
3413 Some(
3414 h_flex()
3415 .gap_1()
3416 .flex_shrink_0()
3417 .when_some(branch, |this, branch| {
3418 let focus_handle = Some(self.focus_handle(cx));
3419
3420 this.children(render_remote_button(
3421 "remote-button",
3422 &branch,
3423 focus_handle,
3424 true,
3425 ))
3426 })
3427 .into_any_element(),
3428 )
3429 }
3430
3431 pub fn render_footer(
3432 &self,
3433 window: &mut Window,
3434 cx: &mut Context<Self>,
3435 ) -> Option<impl IntoElement> {
3436 let active_repository = self.active_repository.clone()?;
3437 let panel_editor_style = panel_editor_style(true, window, cx);
3438
3439 let enable_coauthors = self.render_co_authors(cx);
3440
3441 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3442 let expand_tooltip_focus_handle = editor_focus_handle;
3443
3444 let branch = active_repository.read(cx).branch.clone();
3445 let head_commit = active_repository.read(cx).head_commit.clone();
3446
3447 let footer_size = px(32.);
3448 let gap = px(9.0);
3449 let max_height = panel_editor_style
3450 .text
3451 .line_height_in_pixels(window.rem_size())
3452 * MAX_PANEL_EDITOR_LINES
3453 + gap;
3454
3455 let git_panel = cx.entity();
3456 let display_name = SharedString::from(Arc::from(
3457 active_repository
3458 .read(cx)
3459 .display_name()
3460 .trim_end_matches("/"),
3461 ));
3462 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3463 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3464 });
3465
3466 let footer = v_flex()
3467 .child(PanelRepoFooter::new(
3468 display_name,
3469 branch,
3470 head_commit,
3471 Some(git_panel),
3472 ))
3473 .child(
3474 panel_editor_container(window, cx)
3475 .id("commit-editor-container")
3476 .relative()
3477 .w_full()
3478 .h(max_height + footer_size)
3479 .border_t_1()
3480 .border_color(cx.theme().colors().border)
3481 .cursor_text()
3482 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3483 window.focus(&this.commit_editor.focus_handle(cx));
3484 }))
3485 .child(
3486 h_flex()
3487 .id("commit-footer")
3488 .border_t_1()
3489 .when(editor_is_long, |el| {
3490 el.border_color(cx.theme().colors().border_variant)
3491 })
3492 .absolute()
3493 .bottom_0()
3494 .left_0()
3495 .w_full()
3496 .px_2()
3497 .h(footer_size)
3498 .flex_none()
3499 .justify_between()
3500 .child(
3501 self.render_generate_commit_message_button(cx)
3502 .unwrap_or_else(|| div().into_any_element()),
3503 )
3504 .child(
3505 h_flex()
3506 .gap_0p5()
3507 .children(enable_coauthors)
3508 .child(self.render_commit_button(cx)),
3509 ),
3510 )
3511 .child(
3512 div()
3513 .pr_2p5()
3514 .on_action(|&editor::actions::MoveUp, _, cx| {
3515 cx.stop_propagation();
3516 })
3517 .on_action(|&editor::actions::MoveDown, _, cx| {
3518 cx.stop_propagation();
3519 })
3520 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3521 )
3522 .child(
3523 h_flex()
3524 .absolute()
3525 .top_2()
3526 .right_2()
3527 .opacity(0.5)
3528 .hover(|this| this.opacity(1.0))
3529 .child(
3530 panel_icon_button("expand-commit-editor", IconName::Maximize)
3531 .icon_size(IconSize::Small)
3532 .size(ui::ButtonSize::Default)
3533 .tooltip(move |window, cx| {
3534 Tooltip::for_action_in(
3535 "Open Commit Modal",
3536 &git::ExpandCommitEditor,
3537 &expand_tooltip_focus_handle,
3538 window,
3539 cx,
3540 )
3541 })
3542 .on_click(cx.listener({
3543 move |_, _, window, cx| {
3544 window.dispatch_action(
3545 git::ExpandCommitEditor.boxed_clone(),
3546 cx,
3547 )
3548 }
3549 })),
3550 ),
3551 ),
3552 );
3553
3554 Some(footer)
3555 }
3556
3557 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3558 let (can_commit, tooltip) = self.configure_commit_button(cx);
3559 let title = self.commit_button_title();
3560 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3561 let amend = self.amend_pending();
3562 let signoff = self.signoff_enabled;
3563
3564 div()
3565 .id("commit-wrapper")
3566 .on_hover(cx.listener(move |this, hovered, _, cx| {
3567 this.show_placeholders =
3568 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3569 cx.notify()
3570 }))
3571 .child(SplitButton::new(
3572 ui::ButtonLike::new_rounded_left(ElementId::Name(
3573 format!("split-button-left-{}", title).into(),
3574 ))
3575 .layer(ui::ElevationIndex::ModalSurface)
3576 .size(ui::ButtonSize::Compact)
3577 .child(
3578 div()
3579 .child(Label::new(title).size(LabelSize::Small))
3580 .mr_0p5(),
3581 )
3582 .on_click({
3583 let git_panel = cx.weak_entity();
3584 move |_, window, cx| {
3585 telemetry::event!("Git Committed", source = "Git Panel");
3586 git_panel
3587 .update(cx, |git_panel, cx| {
3588 git_panel.set_amend_pending(false, cx);
3589 git_panel.commit_changes(
3590 CommitOptions { amend, signoff },
3591 window,
3592 cx,
3593 );
3594 })
3595 .ok();
3596 }
3597 })
3598 .disabled(!can_commit || self.modal_open)
3599 .tooltip({
3600 let handle = commit_tooltip_focus_handle.clone();
3601 move |window, cx| {
3602 if can_commit {
3603 Tooltip::with_meta_in(
3604 tooltip,
3605 Some(&git::Commit),
3606 format!(
3607 "git commit{}{}",
3608 if amend { " --amend" } else { "" },
3609 if signoff { " --signoff" } else { "" }
3610 ),
3611 &handle.clone(),
3612 window,
3613 cx,
3614 )
3615 } else {
3616 Tooltip::simple(tooltip, cx)
3617 }
3618 }
3619 }),
3620 self.render_git_commit_menu(
3621 ElementId::Name(format!("split-button-right-{}", title).into()),
3622 Some(commit_tooltip_focus_handle),
3623 cx,
3624 )
3625 .into_any_element(),
3626 ))
3627 }
3628
3629 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3630 h_flex()
3631 .py_1p5()
3632 .px_2()
3633 .gap_1p5()
3634 .justify_between()
3635 .border_t_1()
3636 .border_color(cx.theme().colors().border.opacity(0.8))
3637 .child(
3638 div()
3639 .flex_grow()
3640 .overflow_hidden()
3641 .max_w(relative(0.85))
3642 .child(
3643 Label::new("This will update your most recent commit.")
3644 .size(LabelSize::Small)
3645 .truncate(),
3646 ),
3647 )
3648 .child(
3649 panel_button("Cancel")
3650 .size(ButtonSize::Default)
3651 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3652 )
3653 }
3654
3655 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3656 let active_repository = self.active_repository.as_ref()?;
3657 let branch = active_repository.read(cx).branch.as_ref()?;
3658 let commit = branch.most_recent_commit.as_ref()?.clone();
3659 let workspace = self.workspace.clone();
3660 let this = cx.entity();
3661
3662 Some(
3663 h_flex()
3664 .py_1p5()
3665 .px_2()
3666 .gap_1p5()
3667 .justify_between()
3668 .border_t_1()
3669 .border_color(cx.theme().colors().border.opacity(0.8))
3670 .child(
3671 div()
3672 .flex_grow()
3673 .overflow_hidden()
3674 .max_w(relative(0.85))
3675 .child(
3676 Label::new(commit.subject.clone())
3677 .size(LabelSize::Small)
3678 .truncate(),
3679 )
3680 .id("commit-msg-hover")
3681 .on_click({
3682 let commit = commit.clone();
3683 let repo = active_repository.downgrade();
3684 move |_, window, cx| {
3685 CommitView::open(
3686 commit.clone(),
3687 repo.clone(),
3688 workspace.clone(),
3689 window,
3690 cx,
3691 );
3692 }
3693 })
3694 .hoverable_tooltip({
3695 let repo = active_repository.clone();
3696 move |window, cx| {
3697 GitPanelMessageTooltip::new(
3698 this.clone(),
3699 commit.sha.clone(),
3700 repo.clone(),
3701 window,
3702 cx,
3703 )
3704 .into()
3705 }
3706 }),
3707 )
3708 .when(commit.has_parent, |this| {
3709 let has_unstaged = self.has_unstaged_changes();
3710 this.child(
3711 panel_icon_button("undo", IconName::Undo)
3712 .icon_size(IconSize::XSmall)
3713 .icon_color(Color::Muted)
3714 .tooltip(move |window, cx| {
3715 Tooltip::with_meta(
3716 "Uncommit",
3717 Some(&git::Uncommit),
3718 if has_unstaged {
3719 "git reset HEAD^ --soft"
3720 } else {
3721 "git reset HEAD^"
3722 },
3723 window,
3724 cx,
3725 )
3726 })
3727 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3728 )
3729 }),
3730 )
3731 }
3732
3733 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3734 h_flex().h_full().flex_grow().justify_center().child(
3735 v_flex()
3736 .gap_2()
3737 .child(h_flex().w_full().justify_around().child(
3738 if self.active_repository.is_some() {
3739 "No changes to commit"
3740 } else {
3741 "No Git repositories"
3742 },
3743 ))
3744 .children({
3745 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3746 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3747 h_flex().w_full().justify_around().child(
3748 panel_filled_button("Initialize Repository")
3749 .tooltip(Tooltip::for_action_title_in(
3750 "git init",
3751 &git::Init,
3752 &self.focus_handle,
3753 ))
3754 .on_click(move |_, _, cx| {
3755 cx.defer(move |cx| {
3756 cx.dispatch_action(&git::Init);
3757 })
3758 }),
3759 )
3760 })
3761 })
3762 .text_ui_sm(cx)
3763 .mx_auto()
3764 .text_color(Color::Placeholder.color(cx)),
3765 )
3766 }
3767
3768 fn render_vertical_scrollbar(
3769 &self,
3770 show_horizontal_scrollbar_container: bool,
3771 cx: &mut Context<Self>,
3772 ) -> impl IntoElement {
3773 div()
3774 .id("git-panel-vertical-scroll")
3775 .occlude()
3776 .flex_none()
3777 .h_full()
3778 .cursor_default()
3779 .absolute()
3780 .right_0()
3781 .top_0()
3782 .bottom_0()
3783 .w(px(12.))
3784 .when(show_horizontal_scrollbar_container, |this| {
3785 this.pb_neg_3p5()
3786 })
3787 .on_mouse_move(cx.listener(|_, _, _, cx| {
3788 cx.notify();
3789 cx.stop_propagation()
3790 }))
3791 .on_hover(|_, _, cx| {
3792 cx.stop_propagation();
3793 })
3794 .on_any_mouse_down(|_, _, cx| {
3795 cx.stop_propagation();
3796 })
3797 .on_mouse_up(
3798 MouseButton::Left,
3799 cx.listener(|this, _, window, cx| {
3800 if !this.vertical_scrollbar.state.is_dragging()
3801 && !this.focus_handle.contains_focused(window, cx)
3802 {
3803 this.vertical_scrollbar.hide(window, cx);
3804 cx.notify();
3805 }
3806
3807 cx.stop_propagation();
3808 }),
3809 )
3810 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3811 cx.notify();
3812 }))
3813 .children(Scrollbar::vertical(
3814 // percentage as f32..end_offset as f32,
3815 self.vertical_scrollbar.state.clone(),
3816 ))
3817 }
3818
3819 /// Renders the horizontal scrollbar.
3820 ///
3821 /// The right offset is used to determine how far to the right the
3822 /// scrollbar should extend to, useful for ensuring it doesn't collide
3823 /// with the vertical scrollbar when visible.
3824 fn render_horizontal_scrollbar(
3825 &self,
3826 right_offset: Pixels,
3827 cx: &mut Context<Self>,
3828 ) -> impl IntoElement {
3829 div()
3830 .id("git-panel-horizontal-scroll")
3831 .occlude()
3832 .flex_none()
3833 .w_full()
3834 .cursor_default()
3835 .absolute()
3836 .bottom_neg_px()
3837 .left_0()
3838 .right_0()
3839 .pr(right_offset)
3840 .on_mouse_move(cx.listener(|_, _, _, cx| {
3841 cx.notify();
3842 cx.stop_propagation()
3843 }))
3844 .on_hover(|_, _, cx| {
3845 cx.stop_propagation();
3846 })
3847 .on_any_mouse_down(|_, _, cx| {
3848 cx.stop_propagation();
3849 })
3850 .on_mouse_up(
3851 MouseButton::Left,
3852 cx.listener(|this, _, window, cx| {
3853 if !this.horizontal_scrollbar.state.is_dragging()
3854 && !this.focus_handle.contains_focused(window, cx)
3855 {
3856 this.horizontal_scrollbar.hide(window, cx);
3857 cx.notify();
3858 }
3859
3860 cx.stop_propagation();
3861 }),
3862 )
3863 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
3864 cx.notify();
3865 }))
3866 .children(Scrollbar::horizontal(
3867 // percentage as f32..end_offset as f32,
3868 self.horizontal_scrollbar.state.clone(),
3869 ))
3870 }
3871
3872 fn render_buffer_header_controls(
3873 &self,
3874 entity: &Entity<Self>,
3875 file: &Arc<dyn File>,
3876 _: &Window,
3877 cx: &App,
3878 ) -> Option<AnyElement> {
3879 let repo = self.active_repository.as_ref()?.read(cx);
3880 let project_path = (file.worktree_id(cx), file.path()).into();
3881 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3882 let ix = self.entry_by_path(&repo_path, cx)?;
3883 let entry = self.entries.get(ix)?;
3884
3885 let entry_staging = self.entry_staging(entry.status_entry()?);
3886
3887 let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
3888 .disabled(!self.has_write_access(cx))
3889 .fill()
3890 .elevation(ElevationIndex::Surface)
3891 .on_click({
3892 let entry = entry.clone();
3893 let git_panel = entity.downgrade();
3894 move |_, window, cx| {
3895 git_panel
3896 .update(cx, |this, cx| {
3897 this.toggle_staged_for_entry(&entry, window, cx);
3898 cx.stop_propagation();
3899 })
3900 .ok();
3901 }
3902 });
3903 Some(
3904 h_flex()
3905 .id("start-slot")
3906 .text_lg()
3907 .child(checkbox)
3908 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3909 // prevent the list item active state triggering when toggling checkbox
3910 cx.stop_propagation();
3911 })
3912 .into_any_element(),
3913 )
3914 }
3915
3916 fn render_entries(
3917 &self,
3918 has_write_access: bool,
3919 _: &Window,
3920 cx: &mut Context<Self>,
3921 ) -> impl IntoElement {
3922 let entry_count = self.entries.len();
3923
3924 let scroll_track_size = px(16.);
3925
3926 let h_scroll_offset = if self.vertical_scrollbar.show_scrollbar {
3927 // magic number
3928 px(3.)
3929 } else {
3930 px(0.)
3931 };
3932
3933 v_flex()
3934 .flex_1()
3935 .size_full()
3936 .overflow_hidden()
3937 .relative()
3938 // Show a border on the top and bottom of the container when
3939 // the vertical scrollbar container is visible so we don't have a
3940 // floating left border in the panel.
3941 .when(self.vertical_scrollbar.show_track, |this| {
3942 this.border_t_1()
3943 .border_b_1()
3944 .border_color(cx.theme().colors().border)
3945 })
3946 .child(
3947 h_flex()
3948 .flex_1()
3949 .size_full()
3950 .relative()
3951 .overflow_hidden()
3952 .child(
3953 uniform_list(
3954 "entries",
3955 entry_count,
3956 cx.processor(move |this, range: Range<usize>, window, cx| {
3957 let mut items = Vec::with_capacity(range.end - range.start);
3958
3959 for ix in range {
3960 match &this.entries.get(ix) {
3961 Some(GitListEntry::Status(entry)) => {
3962 items.push(this.render_entry(
3963 ix,
3964 entry,
3965 has_write_access,
3966 window,
3967 cx,
3968 ));
3969 }
3970 Some(GitListEntry::Header(header)) => {
3971 items.push(this.render_list_header(
3972 ix,
3973 header,
3974 has_write_access,
3975 window,
3976 cx,
3977 ));
3978 }
3979 None => {}
3980 }
3981 }
3982
3983 items
3984 }),
3985 )
3986 .when(
3987 !self.horizontal_scrollbar.show_track
3988 && self.horizontal_scrollbar.show_scrollbar,
3989 |this| {
3990 // when not showing the horizontal scrollbar track, make sure we don't
3991 // obscure the last entry
3992 this.pb(scroll_track_size)
3993 },
3994 )
3995 .size_full()
3996 .flex_grow()
3997 .with_sizing_behavior(ListSizingBehavior::Auto)
3998 .with_horizontal_sizing_behavior(
3999 ListHorizontalSizingBehavior::Unconstrained,
4000 )
4001 .with_width_from_item(self.max_width_item_index)
4002 .track_scroll(self.scroll_handle.clone()),
4003 )
4004 .on_mouse_down(
4005 MouseButton::Right,
4006 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4007 this.deploy_panel_context_menu(event.position, window, cx)
4008 }),
4009 )
4010 .when(self.vertical_scrollbar.show_track, |this| {
4011 this.child(
4012 v_flex()
4013 .h_full()
4014 .flex_none()
4015 .w(scroll_track_size)
4016 .bg(cx.theme().colors().panel_background)
4017 .child(
4018 div()
4019 .size_full()
4020 .flex_1()
4021 .border_l_1()
4022 .border_color(cx.theme().colors().border),
4023 ),
4024 )
4025 })
4026 .when(self.vertical_scrollbar.show_scrollbar, |this| {
4027 this.child(
4028 self.render_vertical_scrollbar(
4029 self.horizontal_scrollbar.show_track,
4030 cx,
4031 ),
4032 )
4033 }),
4034 )
4035 .when(self.horizontal_scrollbar.show_track, |this| {
4036 this.child(
4037 h_flex()
4038 .w_full()
4039 .h(scroll_track_size)
4040 .flex_none()
4041 .relative()
4042 .child(
4043 div()
4044 .w_full()
4045 .flex_1()
4046 // for some reason the horizontal scrollbar is 1px
4047 // taller than the vertical scrollbar??
4048 .h(scroll_track_size - px(1.))
4049 .bg(cx.theme().colors().panel_background)
4050 .border_t_1()
4051 .border_color(cx.theme().colors().border),
4052 )
4053 .when(self.vertical_scrollbar.show_track, |this| {
4054 this.child(
4055 div()
4056 .flex_none()
4057 // -1px prevents a missing pixel between the two container borders
4058 .w(scroll_track_size - px(1.))
4059 .h_full(),
4060 )
4061 .child(
4062 // HACK: Fill the missing 1px 🥲
4063 div()
4064 .absolute()
4065 .right(scroll_track_size - px(1.))
4066 .bottom(scroll_track_size - px(1.))
4067 .size_px()
4068 .bg(cx.theme().colors().border),
4069 )
4070 }),
4071 )
4072 })
4073 .when(self.horizontal_scrollbar.show_scrollbar, |this| {
4074 this.child(self.render_horizontal_scrollbar(h_scroll_offset, cx))
4075 })
4076 }
4077
4078 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4079 Label::new(label.into()).color(color).single_line()
4080 }
4081
4082 fn list_item_height(&self) -> Rems {
4083 rems(1.75)
4084 }
4085
4086 fn render_list_header(
4087 &self,
4088 ix: usize,
4089 header: &GitHeaderEntry,
4090 _: bool,
4091 _: &Window,
4092 _: &Context<Self>,
4093 ) -> AnyElement {
4094 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4095
4096 h_flex()
4097 .id(id)
4098 .h(self.list_item_height())
4099 .w_full()
4100 .items_end()
4101 .px(rems(0.75)) // ~12px
4102 .pb(rems(0.3125)) // ~ 5px
4103 .child(
4104 Label::new(header.title())
4105 .color(Color::Muted)
4106 .size(LabelSize::Small)
4107 .line_height_style(LineHeightStyle::UiLabel)
4108 .single_line(),
4109 )
4110 .into_any_element()
4111 }
4112
4113 pub fn load_commit_details(
4114 &self,
4115 sha: String,
4116 cx: &mut Context<Self>,
4117 ) -> Task<anyhow::Result<CommitDetails>> {
4118 let Some(repo) = self.active_repository.clone() else {
4119 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4120 };
4121 repo.update(cx, |repo, cx| {
4122 let show = repo.show(sha);
4123 cx.spawn(async move |_, _| show.await?)
4124 })
4125 }
4126
4127 fn deploy_entry_context_menu(
4128 &mut self,
4129 position: Point<Pixels>,
4130 ix: usize,
4131 window: &mut Window,
4132 cx: &mut Context<Self>,
4133 ) {
4134 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4135 return;
4136 };
4137 let stage_title = if entry.status.staging().is_fully_staged() {
4138 "Unstage File"
4139 } else {
4140 "Stage File"
4141 };
4142 let restore_title = if entry.status.is_created() {
4143 "Trash File"
4144 } else {
4145 "Restore File"
4146 };
4147 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4148 context_menu
4149 .context(self.focus_handle.clone())
4150 .action(stage_title, ToggleStaged.boxed_clone())
4151 .action(restore_title, git::RestoreFile::default().boxed_clone())
4152 .separator()
4153 .action("Open Diff", Confirm.boxed_clone())
4154 .action("Open File", SecondaryConfirm.boxed_clone())
4155 });
4156 self.selected_entry = Some(ix);
4157 self.set_context_menu(context_menu, position, window, cx);
4158 }
4159
4160 fn deploy_panel_context_menu(
4161 &mut self,
4162 position: Point<Pixels>,
4163 window: &mut Window,
4164 cx: &mut Context<Self>,
4165 ) {
4166 let context_menu = git_panel_context_menu(
4167 self.focus_handle.clone(),
4168 GitMenuState {
4169 has_tracked_changes: self.has_tracked_changes(),
4170 has_staged_changes: self.has_staged_changes(),
4171 has_unstaged_changes: self.has_unstaged_changes(),
4172 has_new_changes: self.new_count > 0,
4173 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4174 },
4175 window,
4176 cx,
4177 );
4178 self.set_context_menu(context_menu, position, window, cx);
4179 }
4180
4181 fn set_context_menu(
4182 &mut self,
4183 context_menu: Entity<ContextMenu>,
4184 position: Point<Pixels>,
4185 window: &Window,
4186 cx: &mut Context<Self>,
4187 ) {
4188 let subscription = cx.subscribe_in(
4189 &context_menu,
4190 window,
4191 |this, _, _: &DismissEvent, window, cx| {
4192 if this.context_menu.as_ref().is_some_and(|context_menu| {
4193 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4194 }) {
4195 cx.focus_self(window);
4196 }
4197 this.context_menu.take();
4198 cx.notify();
4199 },
4200 );
4201 self.context_menu = Some((context_menu, position, subscription));
4202 cx.notify();
4203 }
4204
4205 fn render_entry(
4206 &self,
4207 ix: usize,
4208 entry: &GitStatusEntry,
4209 has_write_access: bool,
4210 window: &Window,
4211 cx: &Context<Self>,
4212 ) -> AnyElement {
4213 let display_name = entry.display_name();
4214
4215 let selected = self.selected_entry == Some(ix);
4216 let marked = self.marked_entries.contains(&ix);
4217 let status_style = GitPanelSettings::get_global(cx).status_style;
4218 let status = entry.status;
4219
4220 let has_conflict = status.is_conflicted();
4221 let is_modified = status.is_modified();
4222 let is_deleted = status.is_deleted();
4223
4224 let label_color = if status_style == StatusStyle::LabelColor {
4225 if has_conflict {
4226 Color::VersionControlConflict
4227 } else if is_modified {
4228 Color::VersionControlModified
4229 } else if is_deleted {
4230 // We don't want a bunch of red labels in the list
4231 Color::Disabled
4232 } else {
4233 Color::VersionControlAdded
4234 }
4235 } else {
4236 Color::Default
4237 };
4238
4239 let path_color = if status.is_deleted() {
4240 Color::Disabled
4241 } else {
4242 Color::Muted
4243 };
4244
4245 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4246 let checkbox_wrapper_id: ElementId =
4247 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4248 let checkbox_id: ElementId =
4249 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4250
4251 let entry_staging = self.entry_staging(entry);
4252 let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
4253 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4254 is_staged = ToggleState::Selected;
4255 }
4256
4257 let handle = cx.weak_entity();
4258
4259 let selected_bg_alpha = 0.08;
4260 let marked_bg_alpha = 0.12;
4261 let state_opacity_step = 0.04;
4262
4263 let base_bg = match (selected, marked) {
4264 (true, true) => cx
4265 .theme()
4266 .status()
4267 .info
4268 .alpha(selected_bg_alpha + marked_bg_alpha),
4269 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4270 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4271 _ => cx.theme().colors().ghost_element_background,
4272 };
4273
4274 let hover_bg = if selected {
4275 cx.theme()
4276 .status()
4277 .info
4278 .alpha(selected_bg_alpha + state_opacity_step)
4279 } else {
4280 cx.theme().colors().ghost_element_hover
4281 };
4282
4283 let active_bg = if selected {
4284 cx.theme()
4285 .status()
4286 .info
4287 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4288 } else {
4289 cx.theme().colors().ghost_element_active
4290 };
4291
4292 h_flex()
4293 .id(id)
4294 .h(self.list_item_height())
4295 .w_full()
4296 .items_center()
4297 .border_1()
4298 .when(selected && self.focus_handle.is_focused(window), |el| {
4299 el.border_color(cx.theme().colors().border_focused)
4300 })
4301 .px(rems(0.75)) // ~12px
4302 .overflow_hidden()
4303 .flex_none()
4304 .gap_1p5()
4305 .bg(base_bg)
4306 .hover(|this| this.bg(hover_bg))
4307 .active(|this| this.bg(active_bg))
4308 .on_click({
4309 cx.listener(move |this, event: &ClickEvent, window, cx| {
4310 this.selected_entry = Some(ix);
4311 cx.notify();
4312 if event.modifiers().secondary() {
4313 this.open_file(&Default::default(), window, cx)
4314 } else {
4315 this.open_diff(&Default::default(), window, cx);
4316 this.focus_handle.focus(window);
4317 }
4318 })
4319 })
4320 .on_mouse_down(
4321 MouseButton::Right,
4322 move |event: &MouseDownEvent, window, cx| {
4323 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4324 if event.button != MouseButton::Right {
4325 return;
4326 }
4327
4328 let Some(this) = handle.upgrade() else {
4329 return;
4330 };
4331 this.update(cx, |this, cx| {
4332 this.deploy_entry_context_menu(event.position, ix, window, cx);
4333 });
4334 cx.stop_propagation();
4335 },
4336 )
4337 .child(
4338 div()
4339 .id(checkbox_wrapper_id)
4340 .flex_none()
4341 .occlude()
4342 .cursor_pointer()
4343 .child(
4344 Checkbox::new(checkbox_id, is_staged)
4345 .disabled(!has_write_access)
4346 .fill()
4347 .elevation(ElevationIndex::Surface)
4348 .on_click_ext({
4349 let entry = entry.clone();
4350 let this = cx.weak_entity();
4351 move |_, click, window, cx| {
4352 this.update(cx, |this, cx| {
4353 if !has_write_access {
4354 return;
4355 }
4356 if click.modifiers().shift {
4357 this.stage_bulk(ix, cx);
4358 } else {
4359 this.toggle_staged_for_entry(
4360 &GitListEntry::Status(entry.clone()),
4361 window,
4362 cx,
4363 );
4364 }
4365 cx.stop_propagation();
4366 })
4367 .ok();
4368 }
4369 })
4370 .tooltip(move |window, cx| {
4371 let is_staged = entry_staging.is_fully_staged();
4372
4373 let action = if is_staged { "Unstage" } else { "Stage" };
4374 let tooltip_name = action.to_string();
4375
4376 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
4377 }),
4378 ),
4379 )
4380 .child(git_status_icon(status))
4381 .child(
4382 h_flex()
4383 .items_center()
4384 .flex_1()
4385 // .overflow_hidden()
4386 .when_some(entry.parent_dir(), |this, parent| {
4387 if !parent.is_empty() {
4388 this.child(
4389 self.entry_label(format!("{}/", parent), path_color)
4390 .when(status.is_deleted(), |this| this.strikethrough()),
4391 )
4392 } else {
4393 this
4394 }
4395 })
4396 .child(
4397 self.entry_label(display_name, label_color)
4398 .when(status.is_deleted(), |this| this.strikethrough()),
4399 ),
4400 )
4401 .into_any_element()
4402 }
4403
4404 fn has_write_access(&self, cx: &App) -> bool {
4405 !self.project.read(cx).is_read_only(cx)
4406 }
4407
4408 pub fn amend_pending(&self) -> bool {
4409 self.amend_pending
4410 }
4411
4412 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4413 if value && !self.amend_pending {
4414 let current_message = self.commit_message_buffer(cx).read(cx).text();
4415 self.original_commit_message = if current_message.trim().is_empty() {
4416 None
4417 } else {
4418 Some(current_message)
4419 };
4420 } else if !value && self.amend_pending {
4421 let message = self.original_commit_message.take().unwrap_or_default();
4422 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4423 let start = buffer.anchor_before(0);
4424 let end = buffer.anchor_after(buffer.len());
4425 buffer.edit([(start..end, message)], None, cx);
4426 });
4427 }
4428
4429 self.amend_pending = value;
4430 self.serialize(cx);
4431 cx.notify();
4432 }
4433
4434 pub fn signoff_enabled(&self) -> bool {
4435 self.signoff_enabled
4436 }
4437
4438 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4439 self.signoff_enabled = value;
4440 self.serialize(cx);
4441 cx.notify();
4442 }
4443
4444 pub fn toggle_signoff_enabled(
4445 &mut self,
4446 _: &Signoff,
4447 _window: &mut Window,
4448 cx: &mut Context<Self>,
4449 ) {
4450 self.set_signoff_enabled(!self.signoff_enabled, cx);
4451 }
4452
4453 pub async fn load(
4454 workspace: WeakEntity<Workspace>,
4455 mut cx: AsyncWindowContext,
4456 ) -> anyhow::Result<Entity<Self>> {
4457 let serialized_panel = match workspace
4458 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4459 .ok()
4460 .flatten()
4461 {
4462 Some(serialization_key) => cx
4463 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4464 .await
4465 .context("loading git panel")
4466 .log_err()
4467 .flatten()
4468 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4469 .transpose()
4470 .log_err()
4471 .flatten(),
4472 None => None,
4473 };
4474
4475 workspace.update_in(&mut cx, |workspace, window, cx| {
4476 let panel = GitPanel::new(workspace, window, cx);
4477
4478 if let Some(serialized_panel) = serialized_panel {
4479 panel.update(cx, |panel, cx| {
4480 panel.width = serialized_panel.width;
4481 panel.amend_pending = serialized_panel.amend_pending;
4482 panel.signoff_enabled = serialized_panel.signoff_enabled;
4483 cx.notify();
4484 })
4485 }
4486
4487 panel
4488 })
4489 }
4490
4491 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4492 let Some(op) = self.bulk_staging.as_ref() else {
4493 return;
4494 };
4495 let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4496 return;
4497 };
4498 if let Some(entry) = self.entries.get(index)
4499 && let Some(entry) = entry.status_entry()
4500 {
4501 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4502 }
4503 if index < anchor_index {
4504 std::mem::swap(&mut index, &mut anchor_index);
4505 }
4506 let entries = self
4507 .entries
4508 .get(anchor_index..=index)
4509 .unwrap_or_default()
4510 .iter()
4511 .filter_map(|entry| entry.status_entry().cloned())
4512 .collect::<Vec<_>>();
4513 self.change_file_stage(true, entries, cx);
4514 }
4515
4516 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4517 let Some(repo) = self.active_repository.as_ref() else {
4518 return;
4519 };
4520 self.bulk_staging = Some(BulkStaging {
4521 repo_id: repo.read(cx).id,
4522 anchor: path,
4523 });
4524 }
4525
4526 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4527 self.set_amend_pending(!self.amend_pending, cx);
4528 if self.amend_pending {
4529 self.load_last_commit_message_if_empty(cx);
4530 }
4531 }
4532}
4533
4534impl Render for GitPanel {
4535 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4536 let project = self.project.read(cx);
4537 let has_entries = !self.entries.is_empty();
4538 let room = self
4539 .workspace
4540 .upgrade()
4541 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4542
4543 let has_write_access = self.has_write_access(cx);
4544
4545 let has_co_authors = room.is_some_and(|room| {
4546 self.load_local_committer(cx);
4547 let room = room.read(cx);
4548 room.remote_participants()
4549 .values()
4550 .any(|remote_participant| remote_participant.can_write())
4551 });
4552
4553 v_flex()
4554 .id("git_panel")
4555 .key_context(self.dispatch_context(window, cx))
4556 .track_focus(&self.focus_handle)
4557 .when(has_write_access && !project.is_read_only(cx), |this| {
4558 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4559 .on_action(cx.listener(Self::stage_range))
4560 .on_action(cx.listener(GitPanel::commit))
4561 .on_action(cx.listener(GitPanel::amend))
4562 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4563 .on_action(cx.listener(Self::stage_all))
4564 .on_action(cx.listener(Self::unstage_all))
4565 .on_action(cx.listener(Self::stage_selected))
4566 .on_action(cx.listener(Self::unstage_selected))
4567 .on_action(cx.listener(Self::restore_tracked_files))
4568 .on_action(cx.listener(Self::revert_selected))
4569 .on_action(cx.listener(Self::clean_all))
4570 .on_action(cx.listener(Self::generate_commit_message_action))
4571 .on_action(cx.listener(Self::stash_all))
4572 .on_action(cx.listener(Self::stash_pop))
4573 })
4574 .on_action(cx.listener(Self::select_first))
4575 .on_action(cx.listener(Self::select_next))
4576 .on_action(cx.listener(Self::select_previous))
4577 .on_action(cx.listener(Self::select_last))
4578 .on_action(cx.listener(Self::close_panel))
4579 .on_action(cx.listener(Self::open_diff))
4580 .on_action(cx.listener(Self::open_file))
4581 .on_action(cx.listener(Self::focus_changes_list))
4582 .on_action(cx.listener(Self::focus_editor))
4583 .on_action(cx.listener(Self::expand_commit_editor))
4584 .when(has_write_access && has_co_authors, |git_panel| {
4585 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4586 })
4587 .on_action(cx.listener(Self::toggle_sort_by_path))
4588 .on_hover(cx.listener(move |this, hovered, window, cx| {
4589 if *hovered {
4590 this.horizontal_scrollbar.show(cx);
4591 this.vertical_scrollbar.show(cx);
4592 cx.notify();
4593 } else if !this.focus_handle.contains_focused(window, cx) {
4594 this.hide_scrollbars(window, cx);
4595 }
4596 }))
4597 .size_full()
4598 .overflow_hidden()
4599 .bg(cx.theme().colors().panel_background)
4600 .child(
4601 v_flex()
4602 .size_full()
4603 .children(self.render_panel_header(window, cx))
4604 .map(|this| {
4605 if has_entries {
4606 this.child(self.render_entries(has_write_access, window, cx))
4607 } else {
4608 this.child(self.render_empty_state(cx).into_any_element())
4609 }
4610 })
4611 .children(self.render_footer(window, cx))
4612 .when(self.amend_pending, |this| {
4613 this.child(self.render_pending_amend(cx))
4614 })
4615 .when(!self.amend_pending, |this| {
4616 this.children(self.render_previous_commit(cx))
4617 })
4618 .into_any_element(),
4619 )
4620 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4621 deferred(
4622 anchored()
4623 .position(*position)
4624 .anchor(Corner::TopLeft)
4625 .child(menu.clone()),
4626 )
4627 .with_priority(1)
4628 }))
4629 }
4630}
4631
4632impl Focusable for GitPanel {
4633 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4634 if self.entries.is_empty() {
4635 self.commit_editor.focus_handle(cx)
4636 } else {
4637 self.focus_handle.clone()
4638 }
4639 }
4640}
4641
4642impl EventEmitter<Event> for GitPanel {}
4643
4644impl EventEmitter<PanelEvent> for GitPanel {}
4645
4646pub(crate) struct GitPanelAddon {
4647 pub(crate) workspace: WeakEntity<Workspace>,
4648}
4649
4650impl editor::Addon for GitPanelAddon {
4651 fn to_any(&self) -> &dyn std::any::Any {
4652 self
4653 }
4654
4655 fn render_buffer_header_controls(
4656 &self,
4657 excerpt_info: &ExcerptInfo,
4658 window: &Window,
4659 cx: &App,
4660 ) -> Option<AnyElement> {
4661 let file = excerpt_info.buffer.file()?;
4662 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4663
4664 git_panel
4665 .read(cx)
4666 .render_buffer_header_controls(&git_panel, file, window, cx)
4667 }
4668}
4669
4670impl Panel for GitPanel {
4671 fn persistent_name() -> &'static str {
4672 "GitPanel"
4673 }
4674
4675 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4676 GitPanelSettings::get_global(cx).dock
4677 }
4678
4679 fn position_is_valid(&self, position: DockPosition) -> bool {
4680 matches!(position, DockPosition::Left | DockPosition::Right)
4681 }
4682
4683 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4684 settings::update_settings_file::<GitPanelSettings>(
4685 self.fs.clone(),
4686 cx,
4687 move |settings, _| settings.dock = Some(position),
4688 );
4689 }
4690
4691 fn size(&self, _: &Window, cx: &App) -> Pixels {
4692 self.width
4693 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4694 }
4695
4696 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4697 self.width = size;
4698 self.serialize(cx);
4699 cx.notify();
4700 }
4701
4702 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4703 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4704 }
4705
4706 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4707 Some("Git Panel")
4708 }
4709
4710 fn toggle_action(&self) -> Box<dyn Action> {
4711 Box::new(ToggleFocus)
4712 }
4713
4714 fn activation_priority(&self) -> u32 {
4715 2
4716 }
4717}
4718
4719impl PanelHeader for GitPanel {}
4720
4721struct GitPanelMessageTooltip {
4722 commit_tooltip: Option<Entity<CommitTooltip>>,
4723}
4724
4725impl GitPanelMessageTooltip {
4726 fn new(
4727 git_panel: Entity<GitPanel>,
4728 sha: SharedString,
4729 repository: Entity<Repository>,
4730 window: &mut Window,
4731 cx: &mut App,
4732 ) -> Entity<Self> {
4733 cx.new(|cx| {
4734 cx.spawn_in(window, async move |this, cx| {
4735 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4736 (
4737 git_panel.load_commit_details(sha.to_string(), cx),
4738 git_panel.workspace.clone(),
4739 )
4740 })?;
4741 let details = details.await?;
4742
4743 let commit_details = crate::commit_tooltip::CommitDetails {
4744 sha: details.sha.clone(),
4745 author_name: details.author_name.clone(),
4746 author_email: details.author_email.clone(),
4747 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4748 message: Some(ParsedCommitMessage {
4749 message: details.message,
4750 ..Default::default()
4751 }),
4752 };
4753
4754 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4755 this.commit_tooltip = Some(cx.new(move |cx| {
4756 CommitTooltip::new(commit_details, repository, workspace, cx)
4757 }));
4758 cx.notify();
4759 })
4760 })
4761 .detach();
4762
4763 Self {
4764 commit_tooltip: None,
4765 }
4766 })
4767 }
4768}
4769
4770impl Render for GitPanelMessageTooltip {
4771 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4772 if let Some(commit_tooltip) = &self.commit_tooltip {
4773 commit_tooltip.clone().into_any_element()
4774 } else {
4775 gpui::Empty.into_any_element()
4776 }
4777 }
4778}
4779
4780#[derive(IntoElement, RegisterComponent)]
4781pub struct PanelRepoFooter {
4782 active_repository: SharedString,
4783 branch: Option<Branch>,
4784 head_commit: Option<CommitDetails>,
4785
4786 // Getting a GitPanel in previews will be difficult.
4787 //
4788 // For now just take an option here, and we won't bind handlers to buttons in previews.
4789 git_panel: Option<Entity<GitPanel>>,
4790}
4791
4792impl PanelRepoFooter {
4793 pub fn new(
4794 active_repository: SharedString,
4795 branch: Option<Branch>,
4796 head_commit: Option<CommitDetails>,
4797 git_panel: Option<Entity<GitPanel>>,
4798 ) -> Self {
4799 Self {
4800 active_repository,
4801 branch,
4802 head_commit,
4803 git_panel,
4804 }
4805 }
4806
4807 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4808 Self {
4809 active_repository,
4810 branch,
4811 head_commit: None,
4812 git_panel: None,
4813 }
4814 }
4815}
4816
4817impl RenderOnce for PanelRepoFooter {
4818 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4819 let project = self
4820 .git_panel
4821 .as_ref()
4822 .map(|panel| panel.read(cx).project.clone());
4823
4824 let repo = self
4825 .git_panel
4826 .as_ref()
4827 .and_then(|panel| panel.read(cx).active_repository.clone());
4828
4829 let single_repo = project
4830 .as_ref()
4831 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4832 .unwrap_or(true);
4833
4834 const MAX_BRANCH_LEN: usize = 16;
4835 const MAX_REPO_LEN: usize = 16;
4836 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4837 const MAX_SHORT_SHA_LEN: usize = 8;
4838
4839 let branch_name = self
4840 .branch
4841 .as_ref()
4842 .map(|branch| branch.name().to_owned())
4843 .or_else(|| {
4844 self.head_commit.as_ref().map(|commit| {
4845 commit
4846 .sha
4847 .chars()
4848 .take(MAX_SHORT_SHA_LEN)
4849 .collect::<String>()
4850 })
4851 })
4852 .unwrap_or_else(|| " (no branch)".to_owned());
4853 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4854
4855 let active_repo_name = self.active_repository.clone();
4856
4857 let branch_actual_len = branch_name.len();
4858 let repo_actual_len = active_repo_name.len();
4859
4860 // ideally, show the whole branch and repo names but
4861 // when we can't, use a budget to allocate space between the two
4862 let (repo_display_len, branch_display_len) =
4863 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4864 (repo_actual_len, branch_actual_len)
4865 } else if branch_actual_len <= MAX_BRANCH_LEN {
4866 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4867 (repo_space, branch_actual_len)
4868 } else if repo_actual_len <= MAX_REPO_LEN {
4869 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4870 (repo_actual_len, branch_space)
4871 } else {
4872 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4873 };
4874
4875 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4876 active_repo_name.to_string()
4877 } else {
4878 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4879 };
4880
4881 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4882 branch_name
4883 } else {
4884 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4885 };
4886
4887 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4888 .style(ButtonStyle::Transparent)
4889 .size(ButtonSize::None)
4890 .label_size(LabelSize::Small)
4891 .color(Color::Muted);
4892
4893 let repo_selector = PopoverMenu::new("repository-switcher")
4894 .menu({
4895 let project = project;
4896 move |window, cx| {
4897 let project = project.clone()?;
4898 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4899 }
4900 })
4901 .trigger_with_tooltip(
4902 repo_selector_trigger.disabled(single_repo).truncate(true),
4903 Tooltip::text("Switch Active Repository"),
4904 )
4905 .anchor(Corner::BottomLeft)
4906 .into_any_element();
4907
4908 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4909 .style(ButtonStyle::Transparent)
4910 .size(ButtonSize::None)
4911 .label_size(LabelSize::Small)
4912 .truncate(true)
4913 .tooltip(Tooltip::for_action_title(
4914 "Switch Branch",
4915 &zed_actions::git::Switch,
4916 ))
4917 .on_click(|_, window, cx| {
4918 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4919 });
4920
4921 let branch_selector = PopoverMenu::new("popover-button")
4922 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4923 .trigger_with_tooltip(
4924 branch_selector_button,
4925 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4926 )
4927 .anchor(Corner::BottomLeft)
4928 .offset(gpui::Point {
4929 x: px(0.0),
4930 y: px(-2.0),
4931 });
4932
4933 h_flex()
4934 .w_full()
4935 .px_2()
4936 .h(px(36.))
4937 .items_center()
4938 .justify_between()
4939 .gap_1()
4940 .child(
4941 h_flex()
4942 .flex_1()
4943 .overflow_hidden()
4944 .items_center()
4945 .child(
4946 div().child(
4947 Icon::new(IconName::GitBranchAlt)
4948 .size(IconSize::Small)
4949 .color(if single_repo {
4950 Color::Disabled
4951 } else {
4952 Color::Muted
4953 }),
4954 ),
4955 )
4956 .child(repo_selector)
4957 .when(show_separator, |this| {
4958 this.child(
4959 div()
4960 .text_color(cx.theme().colors().text_muted)
4961 .text_sm()
4962 .child("/"),
4963 )
4964 })
4965 .child(branch_selector),
4966 )
4967 .children(if let Some(git_panel) = self.git_panel {
4968 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4969 } else {
4970 None
4971 })
4972 }
4973}
4974
4975impl Component for PanelRepoFooter {
4976 fn scope() -> ComponentScope {
4977 ComponentScope::VersionControl
4978 }
4979
4980 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4981 let unknown_upstream = None;
4982 let no_remote_upstream = Some(UpstreamTracking::Gone);
4983 let ahead_of_upstream = Some(
4984 UpstreamTrackingStatus {
4985 ahead: 2,
4986 behind: 0,
4987 }
4988 .into(),
4989 );
4990 let behind_upstream = Some(
4991 UpstreamTrackingStatus {
4992 ahead: 0,
4993 behind: 2,
4994 }
4995 .into(),
4996 );
4997 let ahead_and_behind_upstream = Some(
4998 UpstreamTrackingStatus {
4999 ahead: 3,
5000 behind: 1,
5001 }
5002 .into(),
5003 );
5004
5005 let not_ahead_or_behind_upstream = Some(
5006 UpstreamTrackingStatus {
5007 ahead: 0,
5008 behind: 0,
5009 }
5010 .into(),
5011 );
5012
5013 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
5014 Branch {
5015 is_head: true,
5016 ref_name: "some-branch".into(),
5017 upstream: upstream.map(|tracking| Upstream {
5018 ref_name: "origin/some-branch".into(),
5019 tracking,
5020 }),
5021 most_recent_commit: Some(CommitSummary {
5022 sha: "abc123".into(),
5023 subject: "Modify stuff".into(),
5024 commit_timestamp: 1710932954,
5025 author_name: "John Doe".into(),
5026 has_parent: true,
5027 }),
5028 }
5029 }
5030
5031 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
5032 Branch {
5033 is_head: true,
5034 ref_name: branch_name.to_string().into(),
5035 upstream: upstream.map(|tracking| Upstream {
5036 ref_name: format!("zed/{}", branch_name).into(),
5037 tracking,
5038 }),
5039 most_recent_commit: Some(CommitSummary {
5040 sha: "abc123".into(),
5041 subject: "Modify stuff".into(),
5042 commit_timestamp: 1710932954,
5043 author_name: "John Doe".into(),
5044 has_parent: true,
5045 }),
5046 }
5047 }
5048
5049 fn active_repository(id: usize) -> SharedString {
5050 format!("repo-{}", id).into()
5051 }
5052
5053 let example_width = px(340.);
5054 Some(
5055 v_flex()
5056 .gap_6()
5057 .w_full()
5058 .flex_none()
5059 .children(vec![
5060 example_group_with_title(
5061 "Action Button States",
5062 vec![
5063 single_example(
5064 "No Branch",
5065 div()
5066 .w(example_width)
5067 .overflow_hidden()
5068 .child(PanelRepoFooter::new_preview(active_repository(1), None))
5069 .into_any_element(),
5070 ),
5071 single_example(
5072 "Remote status unknown",
5073 div()
5074 .w(example_width)
5075 .overflow_hidden()
5076 .child(PanelRepoFooter::new_preview(
5077 active_repository(2),
5078 Some(branch(unknown_upstream)),
5079 ))
5080 .into_any_element(),
5081 ),
5082 single_example(
5083 "No Remote Upstream",
5084 div()
5085 .w(example_width)
5086 .overflow_hidden()
5087 .child(PanelRepoFooter::new_preview(
5088 active_repository(3),
5089 Some(branch(no_remote_upstream)),
5090 ))
5091 .into_any_element(),
5092 ),
5093 single_example(
5094 "Not Ahead or Behind",
5095 div()
5096 .w(example_width)
5097 .overflow_hidden()
5098 .child(PanelRepoFooter::new_preview(
5099 active_repository(4),
5100 Some(branch(not_ahead_or_behind_upstream)),
5101 ))
5102 .into_any_element(),
5103 ),
5104 single_example(
5105 "Behind remote",
5106 div()
5107 .w(example_width)
5108 .overflow_hidden()
5109 .child(PanelRepoFooter::new_preview(
5110 active_repository(5),
5111 Some(branch(behind_upstream)),
5112 ))
5113 .into_any_element(),
5114 ),
5115 single_example(
5116 "Ahead of remote",
5117 div()
5118 .w(example_width)
5119 .overflow_hidden()
5120 .child(PanelRepoFooter::new_preview(
5121 active_repository(6),
5122 Some(branch(ahead_of_upstream)),
5123 ))
5124 .into_any_element(),
5125 ),
5126 single_example(
5127 "Ahead and behind remote",
5128 div()
5129 .w(example_width)
5130 .overflow_hidden()
5131 .child(PanelRepoFooter::new_preview(
5132 active_repository(7),
5133 Some(branch(ahead_and_behind_upstream)),
5134 ))
5135 .into_any_element(),
5136 ),
5137 ],
5138 )
5139 .grow()
5140 .vertical(),
5141 ])
5142 .children(vec![
5143 example_group_with_title(
5144 "Labels",
5145 vec![
5146 single_example(
5147 "Short Branch & Repo",
5148 div()
5149 .w(example_width)
5150 .overflow_hidden()
5151 .child(PanelRepoFooter::new_preview(
5152 SharedString::from("zed"),
5153 Some(custom("main", behind_upstream)),
5154 ))
5155 .into_any_element(),
5156 ),
5157 single_example(
5158 "Long Branch",
5159 div()
5160 .w(example_width)
5161 .overflow_hidden()
5162 .child(PanelRepoFooter::new_preview(
5163 SharedString::from("zed"),
5164 Some(custom(
5165 "redesign-and-update-git-ui-list-entry-style",
5166 behind_upstream,
5167 )),
5168 ))
5169 .into_any_element(),
5170 ),
5171 single_example(
5172 "Long Repo",
5173 div()
5174 .w(example_width)
5175 .overflow_hidden()
5176 .child(PanelRepoFooter::new_preview(
5177 SharedString::from("zed-industries-community-examples"),
5178 Some(custom("gpui", ahead_of_upstream)),
5179 ))
5180 .into_any_element(),
5181 ),
5182 single_example(
5183 "Long Repo & Branch",
5184 div()
5185 .w(example_width)
5186 .overflow_hidden()
5187 .child(PanelRepoFooter::new_preview(
5188 SharedString::from("zed-industries-community-examples"),
5189 Some(custom(
5190 "redesign-and-update-git-ui-list-entry-style",
5191 behind_upstream,
5192 )),
5193 ))
5194 .into_any_element(),
5195 ),
5196 single_example(
5197 "Uppercase Repo",
5198 div()
5199 .w(example_width)
5200 .overflow_hidden()
5201 .child(PanelRepoFooter::new_preview(
5202 SharedString::from("LICENSES"),
5203 Some(custom("main", ahead_of_upstream)),
5204 ))
5205 .into_any_element(),
5206 ),
5207 single_example(
5208 "Uppercase Branch",
5209 div()
5210 .w(example_width)
5211 .overflow_hidden()
5212 .child(PanelRepoFooter::new_preview(
5213 SharedString::from("zed"),
5214 Some(custom("update-README", behind_upstream)),
5215 ))
5216 .into_any_element(),
5217 ),
5218 ],
5219 )
5220 .grow()
5221 .vertical(),
5222 ])
5223 .into_any_element(),
5224 )
5225 }
5226}
5227
5228#[cfg(test)]
5229mod tests {
5230 use git::status::{StatusCode, UnmergedStatus, UnmergedStatusCode};
5231 use gpui::{TestAppContext, VisualTestContext};
5232 use project::{FakeFs, WorktreeSettings};
5233 use serde_json::json;
5234 use settings::SettingsStore;
5235 use theme::LoadThemes;
5236 use util::path;
5237
5238 use super::*;
5239
5240 fn init_test(cx: &mut gpui::TestAppContext) {
5241 zlog::init_test();
5242
5243 cx.update(|cx| {
5244 let settings_store = SettingsStore::test(cx);
5245 cx.set_global(settings_store);
5246 AgentSettings::register(cx);
5247 WorktreeSettings::register(cx);
5248 workspace::init_settings(cx);
5249 theme::init(LoadThemes::JustBase, cx);
5250 language::init(cx);
5251 editor::init(cx);
5252 Project::init_settings(cx);
5253 crate::init(cx);
5254 });
5255 }
5256
5257 #[gpui::test]
5258 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5259 init_test(cx);
5260 let fs = FakeFs::new(cx.background_executor.clone());
5261 fs.insert_tree(
5262 "/root",
5263 json!({
5264 "zed": {
5265 ".git": {},
5266 "crates": {
5267 "gpui": {
5268 "gpui.rs": "fn main() {}"
5269 },
5270 "util": {
5271 "util.rs": "fn do_it() {}"
5272 }
5273 }
5274 },
5275 }),
5276 )
5277 .await;
5278
5279 fs.set_status_for_repo(
5280 Path::new(path!("/root/zed/.git")),
5281 &[
5282 (
5283 Path::new("crates/gpui/gpui.rs"),
5284 StatusCode::Modified.worktree(),
5285 ),
5286 (
5287 Path::new("crates/util/util.rs"),
5288 StatusCode::Modified.worktree(),
5289 ),
5290 ],
5291 );
5292
5293 let project =
5294 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5295 let workspace =
5296 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5297 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5298
5299 cx.read(|cx| {
5300 project
5301 .read(cx)
5302 .worktrees(cx)
5303 .next()
5304 .unwrap()
5305 .read(cx)
5306 .as_local()
5307 .unwrap()
5308 .scan_complete()
5309 })
5310 .await;
5311
5312 cx.executor().run_until_parked();
5313
5314 let panel = workspace.update(cx, GitPanel::new).unwrap();
5315
5316 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5317 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5318 });
5319 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5320 handle.await;
5321
5322 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5323 pretty_assertions::assert_eq!(
5324 entries,
5325 [
5326 GitListEntry::Header(GitHeaderEntry {
5327 header: Section::Tracked
5328 }),
5329 GitListEntry::Status(GitStatusEntry {
5330 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5331 repo_path: "crates/gpui/gpui.rs".into(),
5332 status: StatusCode::Modified.worktree(),
5333 staging: StageStatus::Unstaged,
5334 }),
5335 GitListEntry::Status(GitStatusEntry {
5336 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5337 repo_path: "crates/util/util.rs".into(),
5338 status: StatusCode::Modified.worktree(),
5339 staging: StageStatus::Unstaged,
5340 },),
5341 ],
5342 );
5343
5344 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5345 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5346 });
5347 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5348 handle.await;
5349 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5350 pretty_assertions::assert_eq!(
5351 entries,
5352 [
5353 GitListEntry::Header(GitHeaderEntry {
5354 header: Section::Tracked
5355 }),
5356 GitListEntry::Status(GitStatusEntry {
5357 abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
5358 repo_path: "crates/gpui/gpui.rs".into(),
5359 status: StatusCode::Modified.worktree(),
5360 staging: StageStatus::Unstaged,
5361 }),
5362 GitListEntry::Status(GitStatusEntry {
5363 abs_path: path!("/root/zed/crates/util/util.rs").into(),
5364 repo_path: "crates/util/util.rs".into(),
5365 status: StatusCode::Modified.worktree(),
5366 staging: StageStatus::Unstaged,
5367 },),
5368 ],
5369 );
5370 }
5371
5372 #[gpui::test]
5373 async fn test_bulk_staging(cx: &mut TestAppContext) {
5374 use GitListEntry::*;
5375
5376 init_test(cx);
5377 let fs = FakeFs::new(cx.background_executor.clone());
5378 fs.insert_tree(
5379 "/root",
5380 json!({
5381 "project": {
5382 ".git": {},
5383 "src": {
5384 "main.rs": "fn main() {}",
5385 "lib.rs": "pub fn hello() {}",
5386 "utils.rs": "pub fn util() {}"
5387 },
5388 "tests": {
5389 "test.rs": "fn test() {}"
5390 },
5391 "new_file.txt": "new content",
5392 "another_new.rs": "// new file",
5393 "conflict.txt": "conflicted content"
5394 }
5395 }),
5396 )
5397 .await;
5398
5399 fs.set_status_for_repo(
5400 Path::new(path!("/root/project/.git")),
5401 &[
5402 (Path::new("src/main.rs"), StatusCode::Modified.worktree()),
5403 (Path::new("src/lib.rs"), StatusCode::Modified.worktree()),
5404 (Path::new("tests/test.rs"), StatusCode::Modified.worktree()),
5405 (Path::new("new_file.txt"), FileStatus::Untracked),
5406 (Path::new("another_new.rs"), FileStatus::Untracked),
5407 (Path::new("src/utils.rs"), FileStatus::Untracked),
5408 (
5409 Path::new("conflict.txt"),
5410 UnmergedStatus {
5411 first_head: UnmergedStatusCode::Updated,
5412 second_head: UnmergedStatusCode::Updated,
5413 }
5414 .into(),
5415 ),
5416 ],
5417 );
5418
5419 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5420 let workspace =
5421 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5422 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5423
5424 cx.read(|cx| {
5425 project
5426 .read(cx)
5427 .worktrees(cx)
5428 .next()
5429 .unwrap()
5430 .read(cx)
5431 .as_local()
5432 .unwrap()
5433 .scan_complete()
5434 })
5435 .await;
5436
5437 cx.executor().run_until_parked();
5438
5439 let panel = workspace.update(cx, GitPanel::new).unwrap();
5440
5441 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5442 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5443 });
5444 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5445 handle.await;
5446
5447 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5448 #[rustfmt::skip]
5449 pretty_assertions::assert_matches!(
5450 entries.as_slice(),
5451 &[
5452 Header(GitHeaderEntry { header: Section::Conflict }),
5453 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5454 Header(GitHeaderEntry { header: Section::Tracked }),
5455 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5456 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5457 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5458 Header(GitHeaderEntry { header: Section::New }),
5459 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5460 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5461 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5462 ],
5463 );
5464
5465 let second_status_entry = entries[3].clone();
5466 panel.update_in(cx, |panel, window, cx| {
5467 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5468 });
5469
5470 panel.update_in(cx, |panel, window, cx| {
5471 panel.selected_entry = Some(7);
5472 panel.stage_range(&git::StageRange, window, cx);
5473 });
5474
5475 cx.read(|cx| {
5476 project
5477 .read(cx)
5478 .worktrees(cx)
5479 .next()
5480 .unwrap()
5481 .read(cx)
5482 .as_local()
5483 .unwrap()
5484 .scan_complete()
5485 })
5486 .await;
5487
5488 cx.executor().run_until_parked();
5489
5490 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5491 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5492 });
5493 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5494 handle.await;
5495
5496 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5497 #[rustfmt::skip]
5498 pretty_assertions::assert_matches!(
5499 entries.as_slice(),
5500 &[
5501 Header(GitHeaderEntry { header: Section::Conflict }),
5502 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5503 Header(GitHeaderEntry { header: Section::Tracked }),
5504 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5505 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5506 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5507 Header(GitHeaderEntry { header: Section::New }),
5508 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5509 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5510 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5511 ],
5512 );
5513
5514 let third_status_entry = entries[4].clone();
5515 panel.update_in(cx, |panel, window, cx| {
5516 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5517 });
5518
5519 panel.update_in(cx, |panel, window, cx| {
5520 panel.selected_entry = Some(9);
5521 panel.stage_range(&git::StageRange, window, cx);
5522 });
5523
5524 cx.read(|cx| {
5525 project
5526 .read(cx)
5527 .worktrees(cx)
5528 .next()
5529 .unwrap()
5530 .read(cx)
5531 .as_local()
5532 .unwrap()
5533 .scan_complete()
5534 })
5535 .await;
5536
5537 cx.executor().run_until_parked();
5538
5539 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5540 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5541 });
5542 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5543 handle.await;
5544
5545 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5546 #[rustfmt::skip]
5547 pretty_assertions::assert_matches!(
5548 entries.as_slice(),
5549 &[
5550 Header(GitHeaderEntry { header: Section::Conflict }),
5551 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5552 Header(GitHeaderEntry { header: Section::Tracked }),
5553 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5554 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5555 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5556 Header(GitHeaderEntry { header: Section::New }),
5557 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5558 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5559 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5560 ],
5561 );
5562 }
5563
5564 #[gpui::test]
5565 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5566 init_test(cx);
5567 let fs = FakeFs::new(cx.background_executor.clone());
5568 fs.insert_tree(
5569 "/root",
5570 json!({
5571 "project": {
5572 ".git": {},
5573 "src": {
5574 "main.rs": "fn main() {}"
5575 }
5576 }
5577 }),
5578 )
5579 .await;
5580
5581 fs.set_status_for_repo(
5582 Path::new(path!("/root/project/.git")),
5583 &[(Path::new("src/main.rs"), StatusCode::Modified.worktree())],
5584 );
5585
5586 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5587 let workspace =
5588 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5589 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5590
5591 let panel = workspace.update(cx, GitPanel::new).unwrap();
5592
5593 // Test: User has commit message, enables amend (saves message), then disables (restores message)
5594 panel.update(cx, |panel, cx| {
5595 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5596 let start = buffer.anchor_before(0);
5597 let end = buffer.anchor_after(buffer.len());
5598 buffer.edit([(start..end, "Initial commit message")], None, cx);
5599 });
5600
5601 panel.set_amend_pending(true, cx);
5602 assert!(panel.original_commit_message.is_some());
5603
5604 panel.set_amend_pending(false, cx);
5605 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5606 assert_eq!(current_message, "Initial commit message");
5607 assert!(panel.original_commit_message.is_none());
5608 });
5609
5610 // Test: User has empty commit message, enables amend, then disables (clears message)
5611 panel.update(cx, |panel, cx| {
5612 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5613 let start = buffer.anchor_before(0);
5614 let end = buffer.anchor_after(buffer.len());
5615 buffer.edit([(start..end, "")], None, cx);
5616 });
5617
5618 panel.set_amend_pending(true, cx);
5619 assert!(panel.original_commit_message.is_none());
5620
5621 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5622 let start = buffer.anchor_before(0);
5623 let end = buffer.anchor_after(buffer.len());
5624 buffer.edit([(start..end, "Previous commit message")], None, cx);
5625 });
5626
5627 panel.set_amend_pending(false, cx);
5628 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5629 assert_eq!(current_message, "");
5630 });
5631 }
5632}