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