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