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