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