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