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