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