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