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