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))
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, 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, 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 window: &mut Window,
2532 cx: &mut Context<Self>,
2533 ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
2534 let repo = self.active_repository.clone();
2535 let workspace = self.workspace.clone();
2536 let mut cx = window.to_async(cx);
2537
2538 async move {
2539 let repo = repo.context("No active repository")?;
2540 let current_remotes: Vec<Remote> = repo
2541 .update(&mut cx, |repo, _| {
2542 let current_branch = if always_select {
2543 None
2544 } else {
2545 let current_branch = repo.branch.as_ref().context("No active branch")?;
2546 Some(current_branch.name().to_string())
2547 };
2548 anyhow::Ok(repo.get_remotes(current_branch))
2549 })??
2550 .await??;
2551
2552 let current_remotes: Vec<_> = current_remotes
2553 .into_iter()
2554 .map(|remotes| remotes.name)
2555 .collect();
2556 let selection = cx
2557 .update(|window, cx| {
2558 picker_prompt::prompt(
2559 "Pick which remote to push to",
2560 current_remotes.clone(),
2561 workspace,
2562 window,
2563 cx,
2564 )
2565 })?
2566 .await;
2567
2568 Ok(selection.map(|selection| Remote {
2569 name: current_remotes[selection].clone(),
2570 }))
2571 }
2572 }
2573
2574 pub fn load_local_committer(&mut self, cx: &Context<Self>) {
2575 if self.local_committer_task.is_none() {
2576 self.local_committer_task = Some(cx.spawn(async move |this, cx| {
2577 let committer = get_git_committer(cx).await;
2578 this.update(cx, |this, cx| {
2579 this.local_committer = Some(committer);
2580 cx.notify()
2581 })
2582 .ok();
2583 }));
2584 }
2585 }
2586
2587 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
2588 let mut new_co_authors = Vec::new();
2589 let project = self.project.read(cx);
2590
2591 let Some(room) = self
2592 .workspace
2593 .upgrade()
2594 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
2595 else {
2596 return Vec::default();
2597 };
2598
2599 let room = room.read(cx);
2600
2601 for (peer_id, collaborator) in project.collaborators() {
2602 if collaborator.is_host {
2603 continue;
2604 }
2605
2606 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
2607 continue;
2608 };
2609 if !participant.can_write() {
2610 continue;
2611 }
2612 if let Some(email) = &collaborator.committer_email {
2613 let name = collaborator
2614 .committer_name
2615 .clone()
2616 .or_else(|| participant.user.name.clone())
2617 .unwrap_or_else(|| participant.user.github_login.clone().to_string());
2618 new_co_authors.push((name.clone(), email.clone()))
2619 }
2620 }
2621 if !project.is_local()
2622 && !project.is_read_only(cx)
2623 && let Some(local_committer) = self.local_committer(room, cx)
2624 {
2625 new_co_authors.push(local_committer);
2626 }
2627 new_co_authors
2628 }
2629
2630 fn local_committer(&self, room: &call::Room, cx: &App) -> Option<(String, String)> {
2631 let user = room.local_participant_user(cx)?;
2632 let committer = self.local_committer.as_ref()?;
2633 let email = committer.email.clone()?;
2634 let name = committer
2635 .name
2636 .clone()
2637 .or_else(|| user.name.clone())
2638 .unwrap_or_else(|| user.github_login.clone().to_string());
2639 Some((name, email))
2640 }
2641
2642 fn toggle_fill_co_authors(
2643 &mut self,
2644 _: &ToggleFillCoAuthors,
2645 _: &mut Window,
2646 cx: &mut Context<Self>,
2647 ) {
2648 self.add_coauthors = !self.add_coauthors;
2649 cx.notify();
2650 }
2651
2652 fn toggle_sort_by_path(
2653 &mut self,
2654 _: &ToggleSortByPath,
2655 _: &mut Window,
2656 cx: &mut Context<Self>,
2657 ) {
2658 let current_setting = GitPanelSettings::get_global(cx).sort_by_path;
2659 if let Some(workspace) = self.workspace.upgrade() {
2660 let workspace = workspace.read(cx);
2661 let fs = workspace.app_state().fs.clone();
2662 cx.update_global::<SettingsStore, _>(|store, _cx| {
2663 store.update_settings_file(fs, move |settings, _cx| {
2664 settings.git_panel.get_or_insert_default().sort_by_path =
2665 Some(!current_setting);
2666 });
2667 });
2668 }
2669 }
2670
2671 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
2672 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
2673
2674 let existing_text = message.to_ascii_lowercase();
2675 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
2676 let mut ends_with_co_authors = false;
2677 let existing_co_authors = existing_text
2678 .lines()
2679 .filter_map(|line| {
2680 let line = line.trim();
2681 if line.starts_with(&lowercase_co_author_prefix) {
2682 ends_with_co_authors = true;
2683 Some(line)
2684 } else {
2685 ends_with_co_authors = false;
2686 None
2687 }
2688 })
2689 .collect::<HashSet<_>>();
2690
2691 let new_co_authors = self
2692 .potential_co_authors(cx)
2693 .into_iter()
2694 .filter(|(_, email)| {
2695 !existing_co_authors
2696 .iter()
2697 .any(|existing| existing.contains(email.as_str()))
2698 })
2699 .collect::<Vec<_>>();
2700
2701 if new_co_authors.is_empty() {
2702 return;
2703 }
2704
2705 if !ends_with_co_authors {
2706 message.push('\n');
2707 }
2708 for (name, email) in new_co_authors {
2709 message.push('\n');
2710 message.push_str(CO_AUTHOR_PREFIX);
2711 message.push_str(&name);
2712 message.push_str(" <");
2713 message.push_str(&email);
2714 message.push('>');
2715 }
2716 message.push('\n');
2717 }
2718
2719 fn schedule_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2720 let handle = cx.entity().downgrade();
2721 self.reopen_commit_buffer(window, cx);
2722 self.update_visible_entries_task = cx.spawn_in(window, async move |_, cx| {
2723 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2724 if let Some(git_panel) = handle.upgrade() {
2725 git_panel
2726 .update_in(cx, |git_panel, window, cx| {
2727 git_panel.update_visible_entries(window, cx);
2728 })
2729 .ok();
2730 }
2731 });
2732 }
2733
2734 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2735 let Some(active_repo) = self.active_repository.as_ref() else {
2736 return;
2737 };
2738 let load_buffer = active_repo.update(cx, |active_repo, cx| {
2739 let project = self.project.read(cx);
2740 active_repo.open_commit_buffer(
2741 Some(project.languages().clone()),
2742 project.buffer_store().clone(),
2743 cx,
2744 )
2745 });
2746
2747 cx.spawn_in(window, async move |git_panel, cx| {
2748 let buffer = load_buffer.await?;
2749 git_panel.update_in(cx, |git_panel, window, cx| {
2750 if git_panel
2751 .commit_editor
2752 .read(cx)
2753 .buffer()
2754 .read(cx)
2755 .as_singleton()
2756 .as_ref()
2757 != Some(&buffer)
2758 {
2759 git_panel.commit_editor = cx.new(|cx| {
2760 commit_message_editor(
2761 buffer,
2762 git_panel.suggest_commit_message(cx).map(SharedString::from),
2763 git_panel.project.clone(),
2764 true,
2765 window,
2766 cx,
2767 )
2768 });
2769 }
2770 })
2771 })
2772 .detach_and_log_err(cx);
2773 }
2774
2775 fn update_visible_entries(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2776 let path_style = self.project.read(cx).path_style(cx);
2777 let bulk_staging = self.bulk_staging.take();
2778 let last_staged_path_prev_index = bulk_staging
2779 .as_ref()
2780 .and_then(|op| self.entry_by_path(&op.anchor, cx));
2781
2782 self.entries.clear();
2783 self.single_staged_entry.take();
2784 self.single_tracked_entry.take();
2785 self.conflicted_count = 0;
2786 self.conflicted_staged_count = 0;
2787 self.new_count = 0;
2788 self.tracked_count = 0;
2789 self.new_staged_count = 0;
2790 self.tracked_staged_count = 0;
2791 self.entry_count = 0;
2792
2793 let sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;
2794
2795 let mut changed_entries = Vec::new();
2796 let mut new_entries = Vec::new();
2797 let mut conflict_entries = Vec::new();
2798 let mut single_staged_entry = None;
2799 let mut staged_count = 0;
2800 let mut max_width_item: Option<(RepoPath, usize)> = None;
2801
2802 let Some(repo) = self.active_repository.as_ref() else {
2803 // Just clear entries if no repository is active.
2804 cx.notify();
2805 return;
2806 };
2807
2808 let repo = repo.read(cx);
2809
2810 self.stash_entries = repo.cached_stash();
2811
2812 for entry in repo.cached_status() {
2813 let is_conflict = repo.had_conflict_on_last_merge_head_change(&entry.repo_path);
2814 let is_new = entry.status.is_created();
2815 let staging = entry.status.staging();
2816
2817 if let Some(pending) = repo.pending_ops_for_path(&entry.repo_path)
2818 && pending
2819 .ops
2820 .iter()
2821 .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
2822 {
2823 continue;
2824 }
2825
2826 let entry = GitStatusEntry {
2827 repo_path: entry.repo_path.clone(),
2828 status: entry.status,
2829 staging,
2830 };
2831
2832 if staging.has_staged() {
2833 staged_count += 1;
2834 single_staged_entry = Some(entry.clone());
2835 }
2836
2837 let width_estimate = Self::item_width_estimate(
2838 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
2839 entry.display_name(path_style).len(),
2840 );
2841
2842 match max_width_item.as_mut() {
2843 Some((repo_path, estimate)) => {
2844 if width_estimate > *estimate {
2845 *repo_path = entry.repo_path.clone();
2846 *estimate = width_estimate;
2847 }
2848 }
2849 None => max_width_item = Some((entry.repo_path.clone(), width_estimate)),
2850 }
2851
2852 if sort_by_path {
2853 changed_entries.push(entry);
2854 } else if is_conflict {
2855 conflict_entries.push(entry);
2856 } else if is_new {
2857 new_entries.push(entry);
2858 } else {
2859 changed_entries.push(entry);
2860 }
2861 }
2862
2863 if conflict_entries.is_empty() {
2864 if staged_count == 1
2865 && let Some(entry) = single_staged_entry.as_ref()
2866 {
2867 if let Some(ops) = repo.pending_ops_for_path(&entry.repo_path) {
2868 if ops.staged() {
2869 self.single_staged_entry = single_staged_entry;
2870 }
2871 }
2872 } else if repo.pending_ops_summary().item_summary.staging_count == 1 {
2873 self.single_staged_entry = repo.pending_ops().find_map(|ops| {
2874 if ops.staging() {
2875 repo.status_for_path(&ops.repo_path)
2876 .map(|status| GitStatusEntry {
2877 repo_path: ops.repo_path.clone(),
2878 status: status.status,
2879 staging: StageStatus::Staged,
2880 })
2881 } else {
2882 None
2883 }
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 action = action.into();
3028 let Some(workspace) = self.workspace.upgrade() else {
3029 return;
3030 };
3031
3032 let message = e.to_string().trim().to_string();
3033 if message
3034 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
3035 .next()
3036 .is_some()
3037 { // Hide the cancelled by user message
3038 } else {
3039 workspace.update(cx, |workspace, cx| {
3040 let workspace_weak = cx.weak_entity();
3041 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
3042 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
3043 .action("View Log", move |window, cx| {
3044 let message = message.clone();
3045 let action = action.clone();
3046 workspace_weak
3047 .update(cx, move |workspace, cx| {
3048 Self::open_output(action, workspace, &message, window, cx)
3049 })
3050 .ok();
3051 })
3052 });
3053 workspace.toggle_status_toast(toast, cx)
3054 });
3055 }
3056 }
3057
3058 fn show_commit_message_error<E>(weak_this: &WeakEntity<Self>, err: &E, cx: &mut AsyncApp)
3059 where
3060 E: std::fmt::Debug + std::fmt::Display,
3061 {
3062 if let Ok(Some(workspace)) = weak_this.update(cx, |this, _cx| this.workspace.upgrade()) {
3063 let _ = workspace.update(cx, |workspace, cx| {
3064 struct CommitMessageError;
3065 let notification_id = NotificationId::unique::<CommitMessageError>();
3066 workspace.show_notification(notification_id, cx, |cx| {
3067 cx.new(|cx| {
3068 ErrorMessagePrompt::new(
3069 format!("Failed to generate commit message: {err}"),
3070 cx,
3071 )
3072 })
3073 });
3074 });
3075 }
3076 }
3077
3078 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
3079 let Some(workspace) = self.workspace.upgrade() else {
3080 return;
3081 };
3082
3083 workspace.update(cx, |workspace, cx| {
3084 let SuccessMessage { message, style } = remote_output::format_output(&action, info);
3085 let workspace_weak = cx.weak_entity();
3086 let operation = action.name();
3087
3088 let status_toast = StatusToast::new(message, cx, move |this, _cx| {
3089 use remote_output::SuccessStyle::*;
3090 match style {
3091 Toast => this.icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted)),
3092 ToastWithLog { output } => this
3093 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3094 .action("View Log", move |window, cx| {
3095 let output = output.clone();
3096 let output =
3097 format!("stdout:\n{}\nstderr:\n{}", output.stdout, output.stderr);
3098 workspace_weak
3099 .update(cx, move |workspace, cx| {
3100 Self::open_output(operation, workspace, &output, window, cx)
3101 })
3102 .ok();
3103 }),
3104 PushPrLink { text, link } => this
3105 .icon(ToastIcon::new(IconName::GitBranchAlt).color(Color::Muted))
3106 .action(text, move |_, cx| cx.open_url(&link)),
3107 }
3108 });
3109 workspace.toggle_status_toast(status_toast, cx)
3110 });
3111 }
3112
3113 fn open_output(
3114 operation: impl Into<SharedString>,
3115 workspace: &mut Workspace,
3116 output: &str,
3117 window: &mut Window,
3118 cx: &mut Context<Workspace>,
3119 ) {
3120 let operation = operation.into();
3121 let buffer = cx.new(|cx| Buffer::local(output, cx));
3122 buffer.update(cx, |buffer, cx| {
3123 buffer.set_capability(language::Capability::ReadOnly, cx);
3124 });
3125 let editor = cx.new(|cx| {
3126 let mut editor = Editor::for_buffer(buffer, None, window, cx);
3127 editor.buffer().update(cx, |buffer, cx| {
3128 buffer.set_title(format!("Output from git {operation}"), cx);
3129 });
3130 editor.set_read_only(true);
3131 editor
3132 });
3133
3134 workspace.add_item_to_center(Box::new(editor), window, cx);
3135 }
3136
3137 pub fn can_commit(&self) -> bool {
3138 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3139 }
3140
3141 pub fn can_stage_all(&self) -> bool {
3142 self.has_unstaged_changes()
3143 }
3144
3145 pub fn can_unstage_all(&self) -> bool {
3146 self.has_staged_changes()
3147 }
3148
3149 // eventually we'll need to take depth into account here
3150 // if we add a tree view
3151 fn item_width_estimate(path: usize, file_name: usize) -> usize {
3152 path + file_name
3153 }
3154
3155 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3156 let focus_handle = self.focus_handle.clone();
3157 let has_tracked_changes = self.has_tracked_changes();
3158 let has_staged_changes = self.has_staged_changes();
3159 let has_unstaged_changes = self.has_unstaged_changes();
3160 let has_new_changes = self.new_count > 0;
3161 let has_stash_items = self.stash_entries.entries.len() > 0;
3162
3163 PopoverMenu::new(id.into())
3164 .trigger(
3165 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3166 .icon_size(IconSize::Small)
3167 .icon_color(Color::Muted),
3168 )
3169 .menu(move |window, cx| {
3170 Some(git_panel_context_menu(
3171 focus_handle.clone(),
3172 GitMenuState {
3173 has_tracked_changes,
3174 has_staged_changes,
3175 has_unstaged_changes,
3176 has_new_changes,
3177 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3178 has_stash_items,
3179 },
3180 window,
3181 cx,
3182 ))
3183 })
3184 .anchor(Corner::TopRight)
3185 }
3186
3187 pub(crate) fn render_generate_commit_message_button(
3188 &self,
3189 cx: &Context<Self>,
3190 ) -> Option<AnyElement> {
3191 if !agent_settings::AgentSettings::get_global(cx).enabled(cx)
3192 || LanguageModelRegistry::read_global(cx)
3193 .commit_message_model()
3194 .is_none()
3195 {
3196 return None;
3197 }
3198
3199 if self.generate_commit_message_task.is_some() {
3200 return Some(
3201 h_flex()
3202 .gap_1()
3203 .child(
3204 Icon::new(IconName::ArrowCircle)
3205 .size(IconSize::XSmall)
3206 .color(Color::Info)
3207 .with_rotate_animation(2),
3208 )
3209 .child(
3210 Label::new("Generating Commit...")
3211 .size(LabelSize::Small)
3212 .color(Color::Muted),
3213 )
3214 .into_any_element(),
3215 );
3216 }
3217
3218 let can_commit = self.can_commit();
3219 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3220 Some(
3221 IconButton::new("generate-commit-message", IconName::AiEdit)
3222 .shape(ui::IconButtonShape::Square)
3223 .icon_color(Color::Muted)
3224 .tooltip(move |_window, cx| {
3225 if can_commit {
3226 Tooltip::for_action_in(
3227 "Generate Commit Message",
3228 &git::GenerateCommitMessage,
3229 &editor_focus_handle,
3230 cx,
3231 )
3232 } else {
3233 Tooltip::simple("No changes to commit", cx)
3234 }
3235 })
3236 .disabled(!can_commit)
3237 .on_click(cx.listener(move |this, _event, _window, cx| {
3238 this.generate_commit_message(cx);
3239 }))
3240 .into_any_element(),
3241 )
3242 }
3243
3244 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3245 let potential_co_authors = self.potential_co_authors(cx);
3246
3247 let (tooltip_label, icon) = if self.add_coauthors {
3248 ("Remove co-authored-by", IconName::Person)
3249 } else {
3250 ("Add co-authored-by", IconName::UserCheck)
3251 };
3252
3253 if potential_co_authors.is_empty() {
3254 None
3255 } else {
3256 Some(
3257 IconButton::new("co-authors", icon)
3258 .shape(ui::IconButtonShape::Square)
3259 .icon_color(Color::Disabled)
3260 .selected_icon_color(Color::Selected)
3261 .toggle_state(self.add_coauthors)
3262 .tooltip(move |_, cx| {
3263 let title = format!(
3264 "{}:{}{}",
3265 tooltip_label,
3266 if potential_co_authors.len() == 1 {
3267 ""
3268 } else {
3269 "\n"
3270 },
3271 potential_co_authors
3272 .iter()
3273 .map(|(name, email)| format!(" {} <{}>", name, email))
3274 .join("\n")
3275 );
3276 Tooltip::simple(title, cx)
3277 })
3278 .on_click(cx.listener(|this, _, _, cx| {
3279 this.add_coauthors = !this.add_coauthors;
3280 cx.notify();
3281 }))
3282 .into_any_element(),
3283 )
3284 }
3285 }
3286
3287 fn render_git_commit_menu(
3288 &self,
3289 id: impl Into<ElementId>,
3290 keybinding_target: Option<FocusHandle>,
3291 cx: &mut Context<Self>,
3292 ) -> impl IntoElement {
3293 PopoverMenu::new(id.into())
3294 .trigger(
3295 ui::ButtonLike::new_rounded_right("commit-split-button-right")
3296 .layer(ui::ElevationIndex::ModalSurface)
3297 .size(ButtonSize::None)
3298 .child(
3299 h_flex()
3300 .px_1()
3301 .h_full()
3302 .justify_center()
3303 .border_l_1()
3304 .border_color(cx.theme().colors().border)
3305 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3306 ),
3307 )
3308 .menu({
3309 let git_panel = cx.entity();
3310 let has_previous_commit = self.head_commit(cx).is_some();
3311 let amend = self.amend_pending();
3312 let signoff = self.signoff_enabled;
3313
3314 move |window, cx| {
3315 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3316 context_menu
3317 .when_some(keybinding_target.clone(), |el, keybinding_target| {
3318 el.context(keybinding_target)
3319 })
3320 .when(has_previous_commit, |this| {
3321 this.toggleable_entry(
3322 "Amend",
3323 amend,
3324 IconPosition::Start,
3325 Some(Box::new(Amend)),
3326 {
3327 let git_panel = git_panel.downgrade();
3328 move |_, cx| {
3329 git_panel
3330 .update(cx, |git_panel, cx| {
3331 git_panel.toggle_amend_pending(cx);
3332 })
3333 .ok();
3334 }
3335 },
3336 )
3337 })
3338 .toggleable_entry(
3339 "Signoff",
3340 signoff,
3341 IconPosition::Start,
3342 Some(Box::new(Signoff)),
3343 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3344 )
3345 }))
3346 }
3347 })
3348 .anchor(Corner::TopRight)
3349 }
3350
3351 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3352 if self.has_unstaged_conflicts() {
3353 (false, "You must resolve conflicts before committing")
3354 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3355 (false, "No changes to commit")
3356 } else if self.pending_commit.is_some() {
3357 (false, "Commit in progress")
3358 } else if !self.has_commit_message(cx) {
3359 (false, "No commit message")
3360 } else if !self.has_write_access(cx) {
3361 (false, "You do not have write access to this project")
3362 } else {
3363 (true, self.commit_button_title())
3364 }
3365 }
3366
3367 pub fn commit_button_title(&self) -> &'static str {
3368 if self.amend_pending {
3369 if self.has_staged_changes() {
3370 "Amend"
3371 } else if self.has_tracked_changes() {
3372 "Amend Tracked"
3373 } else {
3374 "Amend"
3375 }
3376 } else if self.has_staged_changes() {
3377 "Commit"
3378 } else {
3379 "Commit Tracked"
3380 }
3381 }
3382
3383 fn expand_commit_editor(
3384 &mut self,
3385 _: &git::ExpandCommitEditor,
3386 window: &mut Window,
3387 cx: &mut Context<Self>,
3388 ) {
3389 let workspace = self.workspace.clone();
3390 window.defer(cx, move |window, cx| {
3391 workspace
3392 .update(cx, |workspace, cx| {
3393 CommitModal::toggle(workspace, None, window, cx)
3394 })
3395 .ok();
3396 })
3397 }
3398
3399 fn render_panel_header(
3400 &self,
3401 window: &mut Window,
3402 cx: &mut Context<Self>,
3403 ) -> Option<impl IntoElement> {
3404 self.active_repository.as_ref()?;
3405
3406 let (text, action, stage, tooltip) =
3407 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3408 ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
3409 } else {
3410 ("Stage All", StageAll.boxed_clone(), true, "git add --all")
3411 };
3412
3413 let change_string = match self.entry_count {
3414 0 => "No Changes".to_string(),
3415 1 => "1 Change".to_string(),
3416 _ => format!("{} Changes", self.entry_count),
3417 };
3418
3419 Some(
3420 self.panel_header_container(window, cx)
3421 .px_2()
3422 .justify_between()
3423 .child(
3424 panel_button(change_string)
3425 .color(Color::Muted)
3426 .tooltip(Tooltip::for_action_title_in(
3427 "Open Diff",
3428 &Diff,
3429 &self.focus_handle,
3430 ))
3431 .on_click(|_, _, cx| {
3432 cx.defer(|cx| {
3433 cx.dispatch_action(&Diff);
3434 })
3435 }),
3436 )
3437 .child(
3438 h_flex()
3439 .gap_1()
3440 .child(self.render_overflow_menu("overflow_menu"))
3441 .child(
3442 panel_filled_button(text)
3443 .tooltip(Tooltip::for_action_title_in(
3444 tooltip,
3445 action.as_ref(),
3446 &self.focus_handle,
3447 ))
3448 .disabled(self.entry_count == 0)
3449 .on_click({
3450 let git_panel = cx.weak_entity();
3451 move |_, _, cx| {
3452 git_panel
3453 .update(cx, |git_panel, cx| {
3454 git_panel.change_all_files_stage(stage, cx);
3455 })
3456 .ok();
3457 }
3458 }),
3459 ),
3460 ),
3461 )
3462 }
3463
3464 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3465 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3466 if !self.can_push_and_pull(cx) {
3467 return None;
3468 }
3469 Some(
3470 h_flex()
3471 .gap_1()
3472 .flex_shrink_0()
3473 .when_some(branch, |this, branch| {
3474 let focus_handle = Some(self.focus_handle(cx));
3475
3476 this.children(render_remote_button(
3477 "remote-button",
3478 &branch,
3479 focus_handle,
3480 true,
3481 ))
3482 })
3483 .into_any_element(),
3484 )
3485 }
3486
3487 pub fn render_footer(
3488 &self,
3489 window: &mut Window,
3490 cx: &mut Context<Self>,
3491 ) -> Option<impl IntoElement> {
3492 let active_repository = self.active_repository.clone()?;
3493 let panel_editor_style = panel_editor_style(true, window, cx);
3494
3495 let enable_coauthors = self.render_co_authors(cx);
3496
3497 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3498 let expand_tooltip_focus_handle = editor_focus_handle;
3499
3500 let branch = active_repository.read(cx).branch.clone();
3501 let head_commit = active_repository.read(cx).head_commit.clone();
3502
3503 let footer_size = px(32.);
3504 let gap = px(9.0);
3505 let max_height = panel_editor_style
3506 .text
3507 .line_height_in_pixels(window.rem_size())
3508 * MAX_PANEL_EDITOR_LINES
3509 + gap;
3510
3511 let git_panel = cx.entity();
3512 let display_name = SharedString::from(Arc::from(
3513 active_repository
3514 .read(cx)
3515 .display_name()
3516 .trim_end_matches("/"),
3517 ));
3518 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
3519 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
3520 });
3521
3522 let footer = v_flex()
3523 .child(PanelRepoFooter::new(
3524 display_name,
3525 branch,
3526 head_commit,
3527 Some(git_panel),
3528 ))
3529 .child(
3530 panel_editor_container(window, cx)
3531 .id("commit-editor-container")
3532 .relative()
3533 .w_full()
3534 .h(max_height + footer_size)
3535 .border_t_1()
3536 .border_color(cx.theme().colors().border)
3537 .cursor_text()
3538 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
3539 window.focus(&this.commit_editor.focus_handle(cx));
3540 }))
3541 .child(
3542 h_flex()
3543 .id("commit-footer")
3544 .border_t_1()
3545 .when(editor_is_long, |el| {
3546 el.border_color(cx.theme().colors().border_variant)
3547 })
3548 .absolute()
3549 .bottom_0()
3550 .left_0()
3551 .w_full()
3552 .px_2()
3553 .h(footer_size)
3554 .flex_none()
3555 .justify_between()
3556 .child(
3557 self.render_generate_commit_message_button(cx)
3558 .unwrap_or_else(|| div().into_any_element()),
3559 )
3560 .child(
3561 h_flex()
3562 .gap_0p5()
3563 .children(enable_coauthors)
3564 .child(self.render_commit_button(cx)),
3565 ),
3566 )
3567 .child(
3568 div()
3569 .pr_2p5()
3570 .on_action(|&editor::actions::MoveUp, _, cx| {
3571 cx.stop_propagation();
3572 })
3573 .on_action(|&editor::actions::MoveDown, _, cx| {
3574 cx.stop_propagation();
3575 })
3576 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
3577 )
3578 .child(
3579 h_flex()
3580 .absolute()
3581 .top_2()
3582 .right_2()
3583 .opacity(0.5)
3584 .hover(|this| this.opacity(1.0))
3585 .child(
3586 panel_icon_button("expand-commit-editor", IconName::Maximize)
3587 .icon_size(IconSize::Small)
3588 .size(ui::ButtonSize::Default)
3589 .tooltip(move |_window, cx| {
3590 Tooltip::for_action_in(
3591 "Open Commit Modal",
3592 &git::ExpandCommitEditor,
3593 &expand_tooltip_focus_handle,
3594 cx,
3595 )
3596 })
3597 .on_click(cx.listener({
3598 move |_, _, window, cx| {
3599 window.dispatch_action(
3600 git::ExpandCommitEditor.boxed_clone(),
3601 cx,
3602 )
3603 }
3604 })),
3605 ),
3606 ),
3607 );
3608
3609 Some(footer)
3610 }
3611
3612 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
3613 let (can_commit, tooltip) = self.configure_commit_button(cx);
3614 let title = self.commit_button_title();
3615 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
3616 let amend = self.amend_pending();
3617 let signoff = self.signoff_enabled;
3618
3619 let label_color = if self.pending_commit.is_some() {
3620 Color::Disabled
3621 } else {
3622 Color::Default
3623 };
3624
3625 div()
3626 .id("commit-wrapper")
3627 .on_hover(cx.listener(move |this, hovered, _, cx| {
3628 this.show_placeholders =
3629 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
3630 cx.notify()
3631 }))
3632 .child(SplitButton::new(
3633 ButtonLike::new_rounded_left(ElementId::Name(
3634 format!("split-button-left-{}", title).into(),
3635 ))
3636 .layer(ElevationIndex::ModalSurface)
3637 .size(ButtonSize::Compact)
3638 .child(
3639 Label::new(title)
3640 .size(LabelSize::Small)
3641 .color(label_color)
3642 .mr_0p5(),
3643 )
3644 .on_click({
3645 let git_panel = cx.weak_entity();
3646 move |_, window, cx| {
3647 telemetry::event!("Git Committed", source = "Git Panel");
3648 git_panel
3649 .update(cx, |git_panel, cx| {
3650 git_panel.commit_changes(
3651 CommitOptions { amend, signoff },
3652 window,
3653 cx,
3654 );
3655 })
3656 .ok();
3657 }
3658 })
3659 .disabled(!can_commit || self.modal_open)
3660 .tooltip({
3661 let handle = commit_tooltip_focus_handle.clone();
3662 move |_window, cx| {
3663 if can_commit {
3664 Tooltip::with_meta_in(
3665 tooltip,
3666 Some(if amend { &git::Amend } else { &git::Commit }),
3667 format!(
3668 "git commit{}{}",
3669 if amend { " --amend" } else { "" },
3670 if signoff { " --signoff" } else { "" }
3671 ),
3672 &handle.clone(),
3673 cx,
3674 )
3675 } else {
3676 Tooltip::simple(tooltip, cx)
3677 }
3678 }
3679 }),
3680 self.render_git_commit_menu(
3681 ElementId::Name(format!("split-button-right-{}", title).into()),
3682 Some(commit_tooltip_focus_handle),
3683 cx,
3684 )
3685 .into_any_element(),
3686 ))
3687 }
3688
3689 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
3690 h_flex()
3691 .py_1p5()
3692 .px_2()
3693 .gap_1p5()
3694 .justify_between()
3695 .border_t_1()
3696 .border_color(cx.theme().colors().border.opacity(0.8))
3697 .child(
3698 div()
3699 .flex_grow()
3700 .overflow_hidden()
3701 .max_w(relative(0.85))
3702 .child(
3703 Label::new("This will update your most recent commit.")
3704 .size(LabelSize::Small)
3705 .truncate(),
3706 ),
3707 )
3708 .child(
3709 panel_button("Cancel")
3710 .size(ButtonSize::Default)
3711 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
3712 )
3713 }
3714
3715 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3716 let active_repository = self.active_repository.as_ref()?;
3717 let branch = active_repository.read(cx).branch.as_ref()?;
3718 let commit = branch.most_recent_commit.as_ref()?.clone();
3719 let workspace = self.workspace.clone();
3720 let this = cx.entity();
3721
3722 Some(
3723 h_flex()
3724 .py_1p5()
3725 .px_2()
3726 .gap_1p5()
3727 .justify_between()
3728 .border_t_1()
3729 .border_color(cx.theme().colors().border.opacity(0.8))
3730 .child(
3731 div()
3732 .cursor_pointer()
3733 .overflow_hidden()
3734 .line_clamp(1)
3735 .child(
3736 Label::new(commit.subject.clone())
3737 .size(LabelSize::Small)
3738 .truncate(),
3739 )
3740 .id("commit-msg-hover")
3741 .on_click({
3742 let commit = commit.clone();
3743 let repo = active_repository.downgrade();
3744 move |_, window, cx| {
3745 CommitView::open(
3746 commit.sha.to_string(),
3747 repo.clone(),
3748 workspace.clone(),
3749 None,
3750 window,
3751 cx,
3752 );
3753 }
3754 })
3755 .hoverable_tooltip({
3756 let repo = active_repository.clone();
3757 move |window, cx| {
3758 GitPanelMessageTooltip::new(
3759 this.clone(),
3760 commit.sha.clone(),
3761 repo.clone(),
3762 window,
3763 cx,
3764 )
3765 .into()
3766 }
3767 }),
3768 )
3769 .when(commit.has_parent, |this| {
3770 let has_unstaged = self.has_unstaged_changes();
3771 this.child(
3772 panel_icon_button("undo", IconName::Undo)
3773 .icon_size(IconSize::XSmall)
3774 .icon_color(Color::Muted)
3775 .tooltip(move |_window, cx| {
3776 Tooltip::with_meta(
3777 "Uncommit",
3778 Some(&git::Uncommit),
3779 if has_unstaged {
3780 "git reset HEAD^ --soft"
3781 } else {
3782 "git reset HEAD^"
3783 },
3784 cx,
3785 )
3786 })
3787 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
3788 )
3789 }),
3790 )
3791 }
3792
3793 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
3794 h_flex().h_full().flex_grow().justify_center().child(
3795 v_flex()
3796 .gap_2()
3797 .child(h_flex().w_full().justify_around().child(
3798 if self.active_repository.is_some() {
3799 "No changes to commit"
3800 } else {
3801 "No Git repositories"
3802 },
3803 ))
3804 .children({
3805 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
3806 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
3807 h_flex().w_full().justify_around().child(
3808 panel_filled_button("Initialize Repository")
3809 .tooltip(Tooltip::for_action_title_in(
3810 "git init",
3811 &git::Init,
3812 &self.focus_handle,
3813 ))
3814 .on_click(move |_, _, cx| {
3815 cx.defer(move |cx| {
3816 cx.dispatch_action(&git::Init);
3817 })
3818 }),
3819 )
3820 })
3821 })
3822 .text_ui_sm(cx)
3823 .mx_auto()
3824 .text_color(Color::Placeholder.color(cx)),
3825 )
3826 }
3827
3828 fn render_buffer_header_controls(
3829 &self,
3830 entity: &Entity<Self>,
3831 file: &Arc<dyn File>,
3832 _: &Window,
3833 cx: &App,
3834 ) -> Option<AnyElement> {
3835 let repo = self.active_repository.as_ref()?.read(cx);
3836 let project_path = (file.worktree_id(cx), file.path().clone()).into();
3837 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
3838 let ix = self.entry_by_path(&repo_path, cx)?;
3839 let entry = self.entries.get(ix)?;
3840
3841 let is_staging_or_staged = repo
3842 .pending_ops_for_path(&repo_path)
3843 .map(|ops| ops.staging() || ops.staged())
3844 .or_else(|| {
3845 repo.status_for_path(&repo_path)
3846 .and_then(|status| status.status.staging().as_bool())
3847 })
3848 .or_else(|| {
3849 entry
3850 .status_entry()
3851 .and_then(|entry| entry.staging.as_bool())
3852 });
3853
3854 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
3855 .disabled(!self.has_write_access(cx))
3856 .fill()
3857 .elevation(ElevationIndex::Surface)
3858 .on_click({
3859 let entry = entry.clone();
3860 let git_panel = entity.downgrade();
3861 move |_, window, cx| {
3862 git_panel
3863 .update(cx, |this, cx| {
3864 this.toggle_staged_for_entry(&entry, window, cx);
3865 cx.stop_propagation();
3866 })
3867 .ok();
3868 }
3869 });
3870 Some(
3871 h_flex()
3872 .id("start-slot")
3873 .text_lg()
3874 .child(checkbox)
3875 .on_mouse_down(MouseButton::Left, |_, _, cx| {
3876 // prevent the list item active state triggering when toggling checkbox
3877 cx.stop_propagation();
3878 })
3879 .into_any_element(),
3880 )
3881 }
3882
3883 fn render_entries(
3884 &self,
3885 has_write_access: bool,
3886 window: &mut Window,
3887 cx: &mut Context<Self>,
3888 ) -> impl IntoElement {
3889 let entry_count = self.entries.len();
3890
3891 v_flex()
3892 .flex_1()
3893 .size_full()
3894 .overflow_hidden()
3895 .relative()
3896 .child(
3897 h_flex()
3898 .flex_1()
3899 .size_full()
3900 .relative()
3901 .overflow_hidden()
3902 .child(
3903 uniform_list(
3904 "entries",
3905 entry_count,
3906 cx.processor(move |this, range: Range<usize>, window, cx| {
3907 let mut items = Vec::with_capacity(range.end - range.start);
3908
3909 for ix in range {
3910 match &this.entries.get(ix) {
3911 Some(GitListEntry::Status(entry)) => {
3912 items.push(this.render_entry(
3913 ix,
3914 entry,
3915 has_write_access,
3916 window,
3917 cx,
3918 ));
3919 }
3920 Some(GitListEntry::Header(header)) => {
3921 items.push(this.render_list_header(
3922 ix,
3923 header,
3924 has_write_access,
3925 window,
3926 cx,
3927 ));
3928 }
3929 None => {}
3930 }
3931 }
3932
3933 items
3934 }),
3935 )
3936 .size_full()
3937 .flex_grow()
3938 .with_sizing_behavior(ListSizingBehavior::Auto)
3939 .with_horizontal_sizing_behavior(
3940 ListHorizontalSizingBehavior::Unconstrained,
3941 )
3942 .with_width_from_item(self.max_width_item_index)
3943 .track_scroll(self.scroll_handle.clone()),
3944 )
3945 .on_mouse_down(
3946 MouseButton::Right,
3947 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
3948 this.deploy_panel_context_menu(event.position, window, cx)
3949 }),
3950 )
3951 .custom_scrollbars(
3952 Scrollbars::for_settings::<GitPanelSettings>()
3953 .tracked_scroll_handle(self.scroll_handle.clone())
3954 .with_track_along(
3955 ScrollAxes::Horizontal,
3956 cx.theme().colors().panel_background,
3957 ),
3958 window,
3959 cx,
3960 ),
3961 )
3962 }
3963
3964 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
3965 Label::new(label.into()).color(color).single_line()
3966 }
3967
3968 fn list_item_height(&self) -> Rems {
3969 rems(1.75)
3970 }
3971
3972 fn render_list_header(
3973 &self,
3974 ix: usize,
3975 header: &GitHeaderEntry,
3976 _: bool,
3977 _: &Window,
3978 _: &Context<Self>,
3979 ) -> AnyElement {
3980 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
3981
3982 h_flex()
3983 .id(id)
3984 .h(self.list_item_height())
3985 .w_full()
3986 .items_end()
3987 .px(rems(0.75)) // ~12px
3988 .pb(rems(0.3125)) // ~ 5px
3989 .child(
3990 Label::new(header.title())
3991 .color(Color::Muted)
3992 .size(LabelSize::Small)
3993 .line_height_style(LineHeightStyle::UiLabel)
3994 .single_line(),
3995 )
3996 .into_any_element()
3997 }
3998
3999 pub fn load_commit_details(
4000 &self,
4001 sha: String,
4002 cx: &mut Context<Self>,
4003 ) -> Task<anyhow::Result<CommitDetails>> {
4004 let Some(repo) = self.active_repository.clone() else {
4005 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4006 };
4007 repo.update(cx, |repo, cx| {
4008 let show = repo.show(sha);
4009 cx.spawn(async move |_, _| show.await?)
4010 })
4011 }
4012
4013 fn deploy_entry_context_menu(
4014 &mut self,
4015 position: Point<Pixels>,
4016 ix: usize,
4017 window: &mut Window,
4018 cx: &mut Context<Self>,
4019 ) {
4020 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4021 return;
4022 };
4023 let stage_title = if entry.status.staging().is_fully_staged() {
4024 "Unstage File"
4025 } else {
4026 "Stage File"
4027 };
4028 let restore_title = if entry.status.is_created() {
4029 "Trash File"
4030 } else {
4031 "Restore File"
4032 };
4033 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4034 let mut context_menu = context_menu
4035 .context(self.focus_handle.clone())
4036 .action(stage_title, ToggleStaged.boxed_clone())
4037 .action(restore_title, git::RestoreFile::default().boxed_clone());
4038
4039 if entry.status.is_created() {
4040 context_menu =
4041 context_menu.action("Add to .gitignore", git::AddToGitignore.boxed_clone());
4042 }
4043
4044 context_menu
4045 .separator()
4046 .action("Open Diff", Confirm.boxed_clone())
4047 .action("Open File", SecondaryConfirm.boxed_clone())
4048 });
4049 self.selected_entry = Some(ix);
4050 self.set_context_menu(context_menu, position, window, cx);
4051 }
4052
4053 fn deploy_panel_context_menu(
4054 &mut self,
4055 position: Point<Pixels>,
4056 window: &mut Window,
4057 cx: &mut Context<Self>,
4058 ) {
4059 let context_menu = git_panel_context_menu(
4060 self.focus_handle.clone(),
4061 GitMenuState {
4062 has_tracked_changes: self.has_tracked_changes(),
4063 has_staged_changes: self.has_staged_changes(),
4064 has_unstaged_changes: self.has_unstaged_changes(),
4065 has_new_changes: self.new_count > 0,
4066 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4067 has_stash_items: self.stash_entries.entries.len() > 0,
4068 },
4069 window,
4070 cx,
4071 );
4072 self.set_context_menu(context_menu, position, window, cx);
4073 }
4074
4075 fn set_context_menu(
4076 &mut self,
4077 context_menu: Entity<ContextMenu>,
4078 position: Point<Pixels>,
4079 window: &Window,
4080 cx: &mut Context<Self>,
4081 ) {
4082 let subscription = cx.subscribe_in(
4083 &context_menu,
4084 window,
4085 |this, _, _: &DismissEvent, window, cx| {
4086 if this.context_menu.as_ref().is_some_and(|context_menu| {
4087 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4088 }) {
4089 cx.focus_self(window);
4090 }
4091 this.context_menu.take();
4092 cx.notify();
4093 },
4094 );
4095 self.context_menu = Some((context_menu, position, subscription));
4096 cx.notify();
4097 }
4098
4099 fn render_entry(
4100 &self,
4101 ix: usize,
4102 entry: &GitStatusEntry,
4103 has_write_access: bool,
4104 window: &Window,
4105 cx: &Context<Self>,
4106 ) -> AnyElement {
4107 let path_style = self.project.read(cx).path_style(cx);
4108 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
4109 let display_name = entry.display_name(path_style);
4110
4111 let selected = self.selected_entry == Some(ix);
4112 let marked = self.marked_entries.contains(&ix);
4113 let status_style = GitPanelSettings::get_global(cx).status_style;
4114 let status = entry.status;
4115
4116 let has_conflict = status.is_conflicted();
4117 let is_modified = status.is_modified();
4118 let is_deleted = status.is_deleted();
4119
4120 let label_color = if status_style == StatusStyle::LabelColor {
4121 if has_conflict {
4122 Color::VersionControlConflict
4123 } else if is_modified {
4124 Color::VersionControlModified
4125 } else if is_deleted {
4126 // We don't want a bunch of red labels in the list
4127 Color::Disabled
4128 } else {
4129 Color::VersionControlAdded
4130 }
4131 } else {
4132 Color::Default
4133 };
4134
4135 let path_color = if status.is_deleted() {
4136 Color::Disabled
4137 } else {
4138 Color::Muted
4139 };
4140
4141 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4142 let checkbox_wrapper_id: ElementId =
4143 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4144 let checkbox_id: ElementId =
4145 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4146
4147 let active_repo = self
4148 .project
4149 .read(cx)
4150 .active_repository(cx)
4151 .expect("active repository must be set");
4152 let repo = active_repo.read(cx);
4153 // Checking for current staged/unstaged file status is a chained operation:
4154 // 1. first, we check for any pending operation recorded in repository
4155 // 2. if there are no pending ops either running or finished, we then ask the repository
4156 // for the most up-to-date file status read from disk - we do this since `entry` arg to this function `render_entry`
4157 // is likely to be staled, and may lead to weird artifacts in the form of subsecond auto-uncheck/check on
4158 // the checkbox's state (or flickering) which is undesirable.
4159 // 3. finally, if there is no info about this `entry` in the repo, we fall back to whatever status is encoded
4160 // in `entry` arg.
4161 let is_staging_or_staged = repo
4162 .pending_ops_for_path(&entry.repo_path)
4163 .map(|ops| ops.staging() || ops.staged())
4164 .or_else(|| {
4165 repo.status_for_path(&entry.repo_path)
4166 .and_then(|status| status.status.staging().as_bool())
4167 })
4168 .or_else(|| entry.staging.as_bool());
4169 let mut is_staged: ToggleState = is_staging_or_staged.into();
4170 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4171 is_staged = ToggleState::Selected;
4172 }
4173
4174 let handle = cx.weak_entity();
4175
4176 let selected_bg_alpha = 0.08;
4177 let marked_bg_alpha = 0.12;
4178 let state_opacity_step = 0.04;
4179
4180 let base_bg = match (selected, marked) {
4181 (true, true) => cx
4182 .theme()
4183 .status()
4184 .info
4185 .alpha(selected_bg_alpha + marked_bg_alpha),
4186 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4187 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4188 _ => cx.theme().colors().ghost_element_background,
4189 };
4190
4191 let hover_bg = if selected {
4192 cx.theme()
4193 .status()
4194 .info
4195 .alpha(selected_bg_alpha + state_opacity_step)
4196 } else {
4197 cx.theme().colors().ghost_element_hover
4198 };
4199
4200 let active_bg = if selected {
4201 cx.theme()
4202 .status()
4203 .info
4204 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4205 } else {
4206 cx.theme().colors().ghost_element_active
4207 };
4208 h_flex()
4209 .id(id)
4210 .h(self.list_item_height())
4211 .w_full()
4212 .items_center()
4213 .border_1()
4214 .when(selected && self.focus_handle.is_focused(window), |el| {
4215 el.border_color(cx.theme().colors().border_focused)
4216 })
4217 .px(rems(0.75)) // ~12px
4218 .overflow_hidden()
4219 .flex_none()
4220 .gap_1p5()
4221 .bg(base_bg)
4222 .hover(|this| this.bg(hover_bg))
4223 .active(|this| this.bg(active_bg))
4224 .on_click({
4225 cx.listener(move |this, event: &ClickEvent, window, cx| {
4226 this.selected_entry = Some(ix);
4227 cx.notify();
4228 if event.modifiers().secondary() {
4229 this.open_file(&Default::default(), window, cx)
4230 } else {
4231 this.open_diff(&Default::default(), window, cx);
4232 this.focus_handle.focus(window);
4233 }
4234 })
4235 })
4236 .on_mouse_down(
4237 MouseButton::Right,
4238 move |event: &MouseDownEvent, window, cx| {
4239 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4240 if event.button != MouseButton::Right {
4241 return;
4242 }
4243
4244 let Some(this) = handle.upgrade() else {
4245 return;
4246 };
4247 this.update(cx, |this, cx| {
4248 this.deploy_entry_context_menu(event.position, ix, window, cx);
4249 });
4250 cx.stop_propagation();
4251 },
4252 )
4253 .child(
4254 div()
4255 .id(checkbox_wrapper_id)
4256 .flex_none()
4257 .occlude()
4258 .cursor_pointer()
4259 .child(
4260 Checkbox::new(checkbox_id, is_staged)
4261 .disabled(!has_write_access)
4262 .fill()
4263 .elevation(ElevationIndex::Surface)
4264 .on_click_ext({
4265 let entry = entry.clone();
4266 let this = cx.weak_entity();
4267 move |_, click, window, cx| {
4268 this.update(cx, |this, cx| {
4269 if !has_write_access {
4270 return;
4271 }
4272 if click.modifiers().shift {
4273 this.stage_bulk(ix, cx);
4274 } else {
4275 this.toggle_staged_for_entry(
4276 &GitListEntry::Status(entry.clone()),
4277 window,
4278 cx,
4279 );
4280 }
4281 cx.stop_propagation();
4282 })
4283 .ok();
4284 }
4285 })
4286 .tooltip(move |_window, cx| {
4287 // If is_staging_or_staged is None, this implies the file was partially staged, and so
4288 // we allow the user to stage it in full by displaying `Stage` in the tooltip.
4289 let action = if is_staging_or_staged.unwrap_or(false) {
4290 "Unstage"
4291 } else {
4292 "Stage"
4293 };
4294 let tooltip_name = action.to_string();
4295
4296 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
4297 }),
4298 ),
4299 )
4300 .child(git_status_icon(status))
4301 .child(
4302 h_flex()
4303 .items_center()
4304 .flex_1()
4305 .child(h_flex().items_center().flex_1().map(|this| {
4306 self.path_formatted(
4307 this,
4308 entry.parent_dir(path_style),
4309 path_color,
4310 display_name,
4311 label_color,
4312 path_style,
4313 git_path_style,
4314 status.is_deleted(),
4315 )
4316 })),
4317 )
4318 .into_any_element()
4319 }
4320
4321 fn path_formatted(
4322 &self,
4323 parent: Div,
4324 directory: Option<String>,
4325 path_color: Color,
4326 file_name: String,
4327 label_color: Color,
4328 path_style: PathStyle,
4329 git_path_style: GitPathStyle,
4330 strikethrough: bool,
4331 ) -> Div {
4332 parent
4333 .when(git_path_style == GitPathStyle::FileNameFirst, |this| {
4334 this.child(
4335 self.entry_label(
4336 match directory.as_ref().is_none_or(|d| d.is_empty()) {
4337 true => file_name.clone(),
4338 false => format!("{file_name} "),
4339 },
4340 label_color,
4341 )
4342 .when(strikethrough, Label::strikethrough),
4343 )
4344 })
4345 .when_some(directory, |this, dir| {
4346 match (
4347 !dir.is_empty(),
4348 git_path_style == GitPathStyle::FileNameFirst,
4349 ) {
4350 (true, true) => this.child(
4351 self.entry_label(dir, path_color)
4352 .when(strikethrough, Label::strikethrough),
4353 ),
4354 (true, false) => this.child(
4355 self.entry_label(format!("{dir}{}", path_style.separator()), path_color)
4356 .when(strikethrough, Label::strikethrough),
4357 ),
4358 _ => this,
4359 }
4360 })
4361 .when(git_path_style == GitPathStyle::FilePathFirst, |this| {
4362 this.child(
4363 self.entry_label(file_name, label_color)
4364 .when(strikethrough, Label::strikethrough),
4365 )
4366 })
4367 }
4368
4369 fn has_write_access(&self, cx: &App) -> bool {
4370 !self.project.read(cx).is_read_only(cx)
4371 }
4372
4373 pub fn amend_pending(&self) -> bool {
4374 self.amend_pending
4375 }
4376
4377 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
4378 if value && !self.amend_pending {
4379 let current_message = self.commit_message_buffer(cx).read(cx).text();
4380 self.original_commit_message = if current_message.trim().is_empty() {
4381 None
4382 } else {
4383 Some(current_message)
4384 };
4385 } else if !value && self.amend_pending {
4386 let message = self.original_commit_message.take().unwrap_or_default();
4387 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
4388 let start = buffer.anchor_before(0);
4389 let end = buffer.anchor_after(buffer.len());
4390 buffer.edit([(start..end, message)], None, cx);
4391 });
4392 }
4393
4394 self.amend_pending = value;
4395 self.serialize(cx);
4396 cx.notify();
4397 }
4398
4399 pub fn signoff_enabled(&self) -> bool {
4400 self.signoff_enabled
4401 }
4402
4403 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
4404 self.signoff_enabled = value;
4405 self.serialize(cx);
4406 cx.notify();
4407 }
4408
4409 pub fn toggle_signoff_enabled(
4410 &mut self,
4411 _: &Signoff,
4412 _window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) {
4415 self.set_signoff_enabled(!self.signoff_enabled, cx);
4416 }
4417
4418 pub async fn load(
4419 workspace: WeakEntity<Workspace>,
4420 mut cx: AsyncWindowContext,
4421 ) -> anyhow::Result<Entity<Self>> {
4422 let serialized_panel = match workspace
4423 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
4424 .ok()
4425 .flatten()
4426 {
4427 Some(serialization_key) => cx
4428 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
4429 .await
4430 .context("loading git panel")
4431 .log_err()
4432 .flatten()
4433 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
4434 .transpose()
4435 .log_err()
4436 .flatten(),
4437 None => None,
4438 };
4439
4440 workspace.update_in(&mut cx, |workspace, window, cx| {
4441 let panel = GitPanel::new(workspace, window, cx);
4442
4443 if let Some(serialized_panel) = serialized_panel {
4444 panel.update(cx, |panel, cx| {
4445 panel.width = serialized_panel.width;
4446 panel.amend_pending = serialized_panel.amend_pending;
4447 panel.signoff_enabled = serialized_panel.signoff_enabled;
4448 cx.notify();
4449 })
4450 }
4451
4452 panel
4453 })
4454 }
4455
4456 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
4457 let Some(op) = self.bulk_staging.as_ref() else {
4458 return;
4459 };
4460 let Some(mut anchor_index) = self.entry_by_path(&op.anchor, cx) else {
4461 return;
4462 };
4463 if let Some(entry) = self.entries.get(index)
4464 && let Some(entry) = entry.status_entry()
4465 {
4466 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
4467 }
4468 if index < anchor_index {
4469 std::mem::swap(&mut index, &mut anchor_index);
4470 }
4471 let entries = self
4472 .entries
4473 .get(anchor_index..=index)
4474 .unwrap_or_default()
4475 .iter()
4476 .filter_map(|entry| entry.status_entry().cloned())
4477 .collect::<Vec<_>>();
4478 self.change_file_stage(true, entries, cx);
4479 }
4480
4481 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
4482 let Some(repo) = self.active_repository.as_ref() else {
4483 return;
4484 };
4485 self.bulk_staging = Some(BulkStaging {
4486 repo_id: repo.read(cx).id,
4487 anchor: path,
4488 });
4489 }
4490
4491 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
4492 self.set_amend_pending(!self.amend_pending, cx);
4493 if self.amend_pending {
4494 self.load_last_commit_message_if_empty(cx);
4495 }
4496 }
4497}
4498
4499impl Render for GitPanel {
4500 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4501 let project = self.project.read(cx);
4502 let has_entries = !self.entries.is_empty();
4503 let room = self
4504 .workspace
4505 .upgrade()
4506 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
4507
4508 let has_write_access = self.has_write_access(cx);
4509
4510 let has_co_authors = room.is_some_and(|room| {
4511 self.load_local_committer(cx);
4512 let room = room.read(cx);
4513 room.remote_participants()
4514 .values()
4515 .any(|remote_participant| remote_participant.can_write())
4516 });
4517
4518 v_flex()
4519 .id("git_panel")
4520 .key_context(self.dispatch_context(window, cx))
4521 .track_focus(&self.focus_handle)
4522 .when(has_write_access && !project.is_read_only(cx), |this| {
4523 this.on_action(cx.listener(Self::toggle_staged_for_selected))
4524 .on_action(cx.listener(Self::stage_range))
4525 .on_action(cx.listener(GitPanel::commit))
4526 .on_action(cx.listener(GitPanel::amend))
4527 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
4528 .on_action(cx.listener(Self::stage_all))
4529 .on_action(cx.listener(Self::unstage_all))
4530 .on_action(cx.listener(Self::stage_selected))
4531 .on_action(cx.listener(Self::unstage_selected))
4532 .on_action(cx.listener(Self::restore_tracked_files))
4533 .on_action(cx.listener(Self::revert_selected))
4534 .on_action(cx.listener(Self::add_to_gitignore))
4535 .on_action(cx.listener(Self::clean_all))
4536 .on_action(cx.listener(Self::generate_commit_message_action))
4537 .on_action(cx.listener(Self::stash_all))
4538 .on_action(cx.listener(Self::stash_pop))
4539 })
4540 .on_action(cx.listener(Self::select_first))
4541 .on_action(cx.listener(Self::select_next))
4542 .on_action(cx.listener(Self::select_previous))
4543 .on_action(cx.listener(Self::select_last))
4544 .on_action(cx.listener(Self::close_panel))
4545 .on_action(cx.listener(Self::open_diff))
4546 .on_action(cx.listener(Self::open_file))
4547 .on_action(cx.listener(Self::focus_changes_list))
4548 .on_action(cx.listener(Self::focus_editor))
4549 .on_action(cx.listener(Self::expand_commit_editor))
4550 .when(has_write_access && has_co_authors, |git_panel| {
4551 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
4552 })
4553 .on_action(cx.listener(Self::toggle_sort_by_path))
4554 .size_full()
4555 .overflow_hidden()
4556 .bg(cx.theme().colors().panel_background)
4557 .child(
4558 v_flex()
4559 .size_full()
4560 .children(self.render_panel_header(window, cx))
4561 .map(|this| {
4562 if has_entries {
4563 this.child(self.render_entries(has_write_access, window, cx))
4564 } else {
4565 this.child(self.render_empty_state(cx).into_any_element())
4566 }
4567 })
4568 .children(self.render_footer(window, cx))
4569 .when(self.amend_pending, |this| {
4570 this.child(self.render_pending_amend(cx))
4571 })
4572 .when(!self.amend_pending, |this| {
4573 this.children(self.render_previous_commit(cx))
4574 })
4575 .into_any_element(),
4576 )
4577 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4578 deferred(
4579 anchored()
4580 .position(*position)
4581 .anchor(Corner::TopLeft)
4582 .child(menu.clone()),
4583 )
4584 .with_priority(1)
4585 }))
4586 }
4587}
4588
4589impl Focusable for GitPanel {
4590 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
4591 if self.entries.is_empty() {
4592 self.commit_editor.focus_handle(cx)
4593 } else {
4594 self.focus_handle.clone()
4595 }
4596 }
4597}
4598
4599impl EventEmitter<Event> for GitPanel {}
4600
4601impl EventEmitter<PanelEvent> for GitPanel {}
4602
4603pub(crate) struct GitPanelAddon {
4604 pub(crate) workspace: WeakEntity<Workspace>,
4605}
4606
4607impl editor::Addon for GitPanelAddon {
4608 fn to_any(&self) -> &dyn std::any::Any {
4609 self
4610 }
4611
4612 fn render_buffer_header_controls(
4613 &self,
4614 excerpt_info: &ExcerptInfo,
4615 window: &Window,
4616 cx: &App,
4617 ) -> Option<AnyElement> {
4618 let file = excerpt_info.buffer.file()?;
4619 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
4620
4621 git_panel
4622 .read(cx)
4623 .render_buffer_header_controls(&git_panel, file, window, cx)
4624 }
4625}
4626
4627impl Panel for GitPanel {
4628 fn persistent_name() -> &'static str {
4629 "GitPanel"
4630 }
4631
4632 fn panel_key() -> &'static str {
4633 GIT_PANEL_KEY
4634 }
4635
4636 fn position(&self, _: &Window, cx: &App) -> DockPosition {
4637 GitPanelSettings::get_global(cx).dock
4638 }
4639
4640 fn position_is_valid(&self, position: DockPosition) -> bool {
4641 matches!(position, DockPosition::Left | DockPosition::Right)
4642 }
4643
4644 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4645 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
4646 settings.git_panel.get_or_insert_default().dock = Some(position.into())
4647 });
4648 }
4649
4650 fn size(&self, _: &Window, cx: &App) -> Pixels {
4651 self.width
4652 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
4653 }
4654
4655 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
4656 self.width = size;
4657 self.serialize(cx);
4658 cx.notify();
4659 }
4660
4661 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
4662 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
4663 }
4664
4665 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
4666 Some("Git Panel")
4667 }
4668
4669 fn toggle_action(&self) -> Box<dyn Action> {
4670 Box::new(ToggleFocus)
4671 }
4672
4673 fn activation_priority(&self) -> u32 {
4674 2
4675 }
4676}
4677
4678impl PanelHeader for GitPanel {}
4679
4680struct GitPanelMessageTooltip {
4681 commit_tooltip: Option<Entity<CommitTooltip>>,
4682}
4683
4684impl GitPanelMessageTooltip {
4685 fn new(
4686 git_panel: Entity<GitPanel>,
4687 sha: SharedString,
4688 repository: Entity<Repository>,
4689 window: &mut Window,
4690 cx: &mut App,
4691 ) -> Entity<Self> {
4692 cx.new(|cx| {
4693 cx.spawn_in(window, async move |this, cx| {
4694 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
4695 (
4696 git_panel.load_commit_details(sha.to_string(), cx),
4697 git_panel.workspace.clone(),
4698 )
4699 })?;
4700 let details = details.await?;
4701
4702 let commit_details = crate::commit_tooltip::CommitDetails {
4703 sha: details.sha.clone(),
4704 author_name: details.author_name.clone(),
4705 author_email: details.author_email.clone(),
4706 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
4707 message: Some(ParsedCommitMessage {
4708 message: details.message,
4709 ..Default::default()
4710 }),
4711 };
4712
4713 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
4714 this.commit_tooltip = Some(cx.new(move |cx| {
4715 CommitTooltip::new(commit_details, repository, workspace, cx)
4716 }));
4717 cx.notify();
4718 })
4719 })
4720 .detach();
4721
4722 Self {
4723 commit_tooltip: None,
4724 }
4725 })
4726 }
4727}
4728
4729impl Render for GitPanelMessageTooltip {
4730 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4731 if let Some(commit_tooltip) = &self.commit_tooltip {
4732 commit_tooltip.clone().into_any_element()
4733 } else {
4734 gpui::Empty.into_any_element()
4735 }
4736 }
4737}
4738
4739#[derive(IntoElement, RegisterComponent)]
4740pub struct PanelRepoFooter {
4741 active_repository: SharedString,
4742 branch: Option<Branch>,
4743 head_commit: Option<CommitDetails>,
4744
4745 // Getting a GitPanel in previews will be difficult.
4746 //
4747 // For now just take an option here, and we won't bind handlers to buttons in previews.
4748 git_panel: Option<Entity<GitPanel>>,
4749}
4750
4751impl PanelRepoFooter {
4752 pub fn new(
4753 active_repository: SharedString,
4754 branch: Option<Branch>,
4755 head_commit: Option<CommitDetails>,
4756 git_panel: Option<Entity<GitPanel>>,
4757 ) -> Self {
4758 Self {
4759 active_repository,
4760 branch,
4761 head_commit,
4762 git_panel,
4763 }
4764 }
4765
4766 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
4767 Self {
4768 active_repository,
4769 branch,
4770 head_commit: None,
4771 git_panel: None,
4772 }
4773 }
4774}
4775
4776impl RenderOnce for PanelRepoFooter {
4777 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4778 let project = self
4779 .git_panel
4780 .as_ref()
4781 .map(|panel| panel.read(cx).project.clone());
4782
4783 let repo = self
4784 .git_panel
4785 .as_ref()
4786 .and_then(|panel| panel.read(cx).active_repository.clone());
4787
4788 let single_repo = project
4789 .as_ref()
4790 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
4791 .unwrap_or(true);
4792
4793 const MAX_BRANCH_LEN: usize = 16;
4794 const MAX_REPO_LEN: usize = 16;
4795 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
4796 const MAX_SHORT_SHA_LEN: usize = 8;
4797
4798 let branch_name = self
4799 .branch
4800 .as_ref()
4801 .map(|branch| branch.name().to_owned())
4802 .or_else(|| {
4803 self.head_commit.as_ref().map(|commit| {
4804 commit
4805 .sha
4806 .chars()
4807 .take(MAX_SHORT_SHA_LEN)
4808 .collect::<String>()
4809 })
4810 })
4811 .unwrap_or_else(|| " (no branch)".to_owned());
4812 let show_separator = self.branch.is_some() || self.head_commit.is_some();
4813
4814 let active_repo_name = self.active_repository.clone();
4815
4816 let branch_actual_len = branch_name.len();
4817 let repo_actual_len = active_repo_name.len();
4818
4819 // ideally, show the whole branch and repo names but
4820 // when we can't, use a budget to allocate space between the two
4821 let (repo_display_len, branch_display_len) =
4822 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
4823 (repo_actual_len, branch_actual_len)
4824 } else if branch_actual_len <= MAX_BRANCH_LEN {
4825 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
4826 (repo_space, branch_actual_len)
4827 } else if repo_actual_len <= MAX_REPO_LEN {
4828 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
4829 (repo_actual_len, branch_space)
4830 } else {
4831 (MAX_REPO_LEN, MAX_BRANCH_LEN)
4832 };
4833
4834 let truncated_repo_name = if repo_actual_len <= repo_display_len {
4835 active_repo_name.to_string()
4836 } else {
4837 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
4838 };
4839
4840 let truncated_branch_name = if branch_actual_len <= branch_display_len {
4841 branch_name
4842 } else {
4843 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
4844 };
4845
4846 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
4847 .size(ButtonSize::None)
4848 .label_size(LabelSize::Small)
4849 .color(Color::Muted);
4850
4851 let repo_selector = PopoverMenu::new("repository-switcher")
4852 .menu({
4853 let project = project;
4854 move |window, cx| {
4855 let project = project.clone()?;
4856 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
4857 }
4858 })
4859 .trigger_with_tooltip(
4860 repo_selector_trigger.disabled(single_repo).truncate(true),
4861 Tooltip::text("Switch Active Repository"),
4862 )
4863 .anchor(Corner::BottomLeft)
4864 .into_any_element();
4865
4866 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
4867 .size(ButtonSize::None)
4868 .label_size(LabelSize::Small)
4869 .truncate(true)
4870 .on_click(|_, window, cx| {
4871 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
4872 });
4873
4874 let branch_selector = PopoverMenu::new("popover-button")
4875 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
4876 .trigger_with_tooltip(
4877 branch_selector_button,
4878 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
4879 )
4880 .anchor(Corner::BottomLeft)
4881 .offset(gpui::Point {
4882 x: px(0.0),
4883 y: px(-2.0),
4884 });
4885
4886 h_flex()
4887 .h(px(36.))
4888 .w_full()
4889 .px_2()
4890 .justify_between()
4891 .gap_1()
4892 .child(
4893 h_flex()
4894 .flex_1()
4895 .overflow_hidden()
4896 .gap_px()
4897 .child(
4898 Icon::new(IconName::GitBranchAlt)
4899 .size(IconSize::Small)
4900 .color(if single_repo {
4901 Color::Disabled
4902 } else {
4903 Color::Muted
4904 }),
4905 )
4906 .child(repo_selector)
4907 .when(show_separator, |this| {
4908 this.child(
4909 div()
4910 .text_sm()
4911 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
4912 .child("/"),
4913 )
4914 })
4915 .child(branch_selector),
4916 )
4917 .children(if let Some(git_panel) = self.git_panel {
4918 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
4919 } else {
4920 None
4921 })
4922 }
4923}
4924
4925impl Component for PanelRepoFooter {
4926 fn scope() -> ComponentScope {
4927 ComponentScope::VersionControl
4928 }
4929
4930 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
4931 let unknown_upstream = None;
4932 let no_remote_upstream = Some(UpstreamTracking::Gone);
4933 let ahead_of_upstream = Some(
4934 UpstreamTrackingStatus {
4935 ahead: 2,
4936 behind: 0,
4937 }
4938 .into(),
4939 );
4940 let behind_upstream = Some(
4941 UpstreamTrackingStatus {
4942 ahead: 0,
4943 behind: 2,
4944 }
4945 .into(),
4946 );
4947 let ahead_and_behind_upstream = Some(
4948 UpstreamTrackingStatus {
4949 ahead: 3,
4950 behind: 1,
4951 }
4952 .into(),
4953 );
4954
4955 let not_ahead_or_behind_upstream = Some(
4956 UpstreamTrackingStatus {
4957 ahead: 0,
4958 behind: 0,
4959 }
4960 .into(),
4961 );
4962
4963 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
4964 Branch {
4965 is_head: true,
4966 ref_name: "some-branch".into(),
4967 upstream: upstream.map(|tracking| Upstream {
4968 ref_name: "origin/some-branch".into(),
4969 tracking,
4970 }),
4971 most_recent_commit: Some(CommitSummary {
4972 sha: "abc123".into(),
4973 subject: "Modify stuff".into(),
4974 commit_timestamp: 1710932954,
4975 author_name: "John Doe".into(),
4976 has_parent: true,
4977 }),
4978 }
4979 }
4980
4981 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
4982 Branch {
4983 is_head: true,
4984 ref_name: branch_name.to_string().into(),
4985 upstream: upstream.map(|tracking| Upstream {
4986 ref_name: format!("zed/{}", branch_name).into(),
4987 tracking,
4988 }),
4989 most_recent_commit: Some(CommitSummary {
4990 sha: "abc123".into(),
4991 subject: "Modify stuff".into(),
4992 commit_timestamp: 1710932954,
4993 author_name: "John Doe".into(),
4994 has_parent: true,
4995 }),
4996 }
4997 }
4998
4999 fn active_repository(id: usize) -> SharedString {
5000 format!("repo-{}", id).into()
5001 }
5002
5003 let example_width = px(340.);
5004 Some(
5005 v_flex()
5006 .gap_6()
5007 .w_full()
5008 .flex_none()
5009 .children(vec![
5010 example_group_with_title(
5011 "Action Button States",
5012 vec![
5013 single_example(
5014 "No Branch",
5015 div()
5016 .w(example_width)
5017 .overflow_hidden()
5018 .child(PanelRepoFooter::new_preview(active_repository(1), None))
5019 .into_any_element(),
5020 ),
5021 single_example(
5022 "Remote status unknown",
5023 div()
5024 .w(example_width)
5025 .overflow_hidden()
5026 .child(PanelRepoFooter::new_preview(
5027 active_repository(2),
5028 Some(branch(unknown_upstream)),
5029 ))
5030 .into_any_element(),
5031 ),
5032 single_example(
5033 "No Remote Upstream",
5034 div()
5035 .w(example_width)
5036 .overflow_hidden()
5037 .child(PanelRepoFooter::new_preview(
5038 active_repository(3),
5039 Some(branch(no_remote_upstream)),
5040 ))
5041 .into_any_element(),
5042 ),
5043 single_example(
5044 "Not Ahead or Behind",
5045 div()
5046 .w(example_width)
5047 .overflow_hidden()
5048 .child(PanelRepoFooter::new_preview(
5049 active_repository(4),
5050 Some(branch(not_ahead_or_behind_upstream)),
5051 ))
5052 .into_any_element(),
5053 ),
5054 single_example(
5055 "Behind remote",
5056 div()
5057 .w(example_width)
5058 .overflow_hidden()
5059 .child(PanelRepoFooter::new_preview(
5060 active_repository(5),
5061 Some(branch(behind_upstream)),
5062 ))
5063 .into_any_element(),
5064 ),
5065 single_example(
5066 "Ahead of remote",
5067 div()
5068 .w(example_width)
5069 .overflow_hidden()
5070 .child(PanelRepoFooter::new_preview(
5071 active_repository(6),
5072 Some(branch(ahead_of_upstream)),
5073 ))
5074 .into_any_element(),
5075 ),
5076 single_example(
5077 "Ahead and behind remote",
5078 div()
5079 .w(example_width)
5080 .overflow_hidden()
5081 .child(PanelRepoFooter::new_preview(
5082 active_repository(7),
5083 Some(branch(ahead_and_behind_upstream)),
5084 ))
5085 .into_any_element(),
5086 ),
5087 ],
5088 )
5089 .grow()
5090 .vertical(),
5091 ])
5092 .children(vec![
5093 example_group_with_title(
5094 "Labels",
5095 vec![
5096 single_example(
5097 "Short Branch & Repo",
5098 div()
5099 .w(example_width)
5100 .overflow_hidden()
5101 .child(PanelRepoFooter::new_preview(
5102 SharedString::from("zed"),
5103 Some(custom("main", behind_upstream)),
5104 ))
5105 .into_any_element(),
5106 ),
5107 single_example(
5108 "Long Branch",
5109 div()
5110 .w(example_width)
5111 .overflow_hidden()
5112 .child(PanelRepoFooter::new_preview(
5113 SharedString::from("zed"),
5114 Some(custom(
5115 "redesign-and-update-git-ui-list-entry-style",
5116 behind_upstream,
5117 )),
5118 ))
5119 .into_any_element(),
5120 ),
5121 single_example(
5122 "Long Repo",
5123 div()
5124 .w(example_width)
5125 .overflow_hidden()
5126 .child(PanelRepoFooter::new_preview(
5127 SharedString::from("zed-industries-community-examples"),
5128 Some(custom("gpui", ahead_of_upstream)),
5129 ))
5130 .into_any_element(),
5131 ),
5132 single_example(
5133 "Long Repo & Branch",
5134 div()
5135 .w(example_width)
5136 .overflow_hidden()
5137 .child(PanelRepoFooter::new_preview(
5138 SharedString::from("zed-industries-community-examples"),
5139 Some(custom(
5140 "redesign-and-update-git-ui-list-entry-style",
5141 behind_upstream,
5142 )),
5143 ))
5144 .into_any_element(),
5145 ),
5146 single_example(
5147 "Uppercase Repo",
5148 div()
5149 .w(example_width)
5150 .overflow_hidden()
5151 .child(PanelRepoFooter::new_preview(
5152 SharedString::from("LICENSES"),
5153 Some(custom("main", ahead_of_upstream)),
5154 ))
5155 .into_any_element(),
5156 ),
5157 single_example(
5158 "Uppercase Branch",
5159 div()
5160 .w(example_width)
5161 .overflow_hidden()
5162 .child(PanelRepoFooter::new_preview(
5163 SharedString::from("zed"),
5164 Some(custom("update-README", behind_upstream)),
5165 ))
5166 .into_any_element(),
5167 ),
5168 ],
5169 )
5170 .grow()
5171 .vertical(),
5172 ])
5173 .into_any_element(),
5174 )
5175 }
5176}
5177
5178#[cfg(test)]
5179mod tests {
5180 use git::{
5181 repository::repo_path,
5182 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
5183 };
5184 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
5185 use indoc::indoc;
5186 use project::FakeFs;
5187 use serde_json::json;
5188 use settings::SettingsStore;
5189 use theme::LoadThemes;
5190 use util::path;
5191 use util::rel_path::rel_path;
5192
5193 use super::*;
5194
5195 fn init_test(cx: &mut gpui::TestAppContext) {
5196 zlog::init_test();
5197
5198 cx.update(|cx| {
5199 let settings_store = SettingsStore::test(cx);
5200 cx.set_global(settings_store);
5201 theme::init(LoadThemes::JustBase, cx);
5202 editor::init(cx);
5203 crate::init(cx);
5204 });
5205 }
5206
5207 #[gpui::test]
5208 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5209 init_test(cx);
5210 let fs = FakeFs::new(cx.background_executor.clone());
5211 fs.insert_tree(
5212 "/root",
5213 json!({
5214 "zed": {
5215 ".git": {},
5216 "crates": {
5217 "gpui": {
5218 "gpui.rs": "fn main() {}"
5219 },
5220 "util": {
5221 "util.rs": "fn do_it() {}"
5222 }
5223 }
5224 },
5225 }),
5226 )
5227 .await;
5228
5229 fs.set_status_for_repo(
5230 Path::new(path!("/root/zed/.git")),
5231 &[
5232 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
5233 ("crates/util/util.rs", StatusCode::Modified.worktree()),
5234 ],
5235 );
5236
5237 let project =
5238 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
5239 let workspace =
5240 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5241 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5242
5243 cx.read(|cx| {
5244 project
5245 .read(cx)
5246 .worktrees(cx)
5247 .next()
5248 .unwrap()
5249 .read(cx)
5250 .as_local()
5251 .unwrap()
5252 .scan_complete()
5253 })
5254 .await;
5255
5256 cx.executor().run_until_parked();
5257
5258 let panel = workspace.update(cx, GitPanel::new).unwrap();
5259
5260 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5261 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5262 });
5263 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5264 handle.await;
5265
5266 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5267 pretty_assertions::assert_eq!(
5268 entries,
5269 [
5270 GitListEntry::Header(GitHeaderEntry {
5271 header: Section::Tracked
5272 }),
5273 GitListEntry::Status(GitStatusEntry {
5274 repo_path: repo_path("crates/gpui/gpui.rs"),
5275 status: StatusCode::Modified.worktree(),
5276 staging: StageStatus::Unstaged,
5277 }),
5278 GitListEntry::Status(GitStatusEntry {
5279 repo_path: repo_path("crates/util/util.rs"),
5280 status: StatusCode::Modified.worktree(),
5281 staging: StageStatus::Unstaged,
5282 },),
5283 ],
5284 );
5285
5286 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5287 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5288 });
5289 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5290 handle.await;
5291 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5292 pretty_assertions::assert_eq!(
5293 entries,
5294 [
5295 GitListEntry::Header(GitHeaderEntry {
5296 header: Section::Tracked
5297 }),
5298 GitListEntry::Status(GitStatusEntry {
5299 repo_path: repo_path("crates/gpui/gpui.rs"),
5300 status: StatusCode::Modified.worktree(),
5301 staging: StageStatus::Unstaged,
5302 }),
5303 GitListEntry::Status(GitStatusEntry {
5304 repo_path: repo_path("crates/util/util.rs"),
5305 status: StatusCode::Modified.worktree(),
5306 staging: StageStatus::Unstaged,
5307 },),
5308 ],
5309 );
5310 }
5311
5312 #[gpui::test]
5313 async fn test_bulk_staging(cx: &mut TestAppContext) {
5314 use GitListEntry::*;
5315
5316 init_test(cx);
5317 let fs = FakeFs::new(cx.background_executor.clone());
5318 fs.insert_tree(
5319 "/root",
5320 json!({
5321 "project": {
5322 ".git": {},
5323 "src": {
5324 "main.rs": "fn main() {}",
5325 "lib.rs": "pub fn hello() {}",
5326 "utils.rs": "pub fn util() {}"
5327 },
5328 "tests": {
5329 "test.rs": "fn test() {}"
5330 },
5331 "new_file.txt": "new content",
5332 "another_new.rs": "// new file",
5333 "conflict.txt": "conflicted content"
5334 }
5335 }),
5336 )
5337 .await;
5338
5339 fs.set_status_for_repo(
5340 Path::new(path!("/root/project/.git")),
5341 &[
5342 ("src/main.rs", StatusCode::Modified.worktree()),
5343 ("src/lib.rs", StatusCode::Modified.worktree()),
5344 ("tests/test.rs", StatusCode::Modified.worktree()),
5345 ("new_file.txt", FileStatus::Untracked),
5346 ("another_new.rs", FileStatus::Untracked),
5347 ("src/utils.rs", FileStatus::Untracked),
5348 (
5349 "conflict.txt",
5350 UnmergedStatus {
5351 first_head: UnmergedStatusCode::Updated,
5352 second_head: UnmergedStatusCode::Updated,
5353 }
5354 .into(),
5355 ),
5356 ],
5357 );
5358
5359 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5360 let workspace =
5361 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5362 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5363
5364 cx.read(|cx| {
5365 project
5366 .read(cx)
5367 .worktrees(cx)
5368 .next()
5369 .unwrap()
5370 .read(cx)
5371 .as_local()
5372 .unwrap()
5373 .scan_complete()
5374 })
5375 .await;
5376
5377 cx.executor().run_until_parked();
5378
5379 let panel = workspace.update(cx, GitPanel::new).unwrap();
5380
5381 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5382 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5383 });
5384 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5385 handle.await;
5386
5387 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5388 #[rustfmt::skip]
5389 pretty_assertions::assert_matches!(
5390 entries.as_slice(),
5391 &[
5392 Header(GitHeaderEntry { header: Section::Conflict }),
5393 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5394 Header(GitHeaderEntry { header: Section::Tracked }),
5395 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5396 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5397 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5398 Header(GitHeaderEntry { header: Section::New }),
5399 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5400 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5401 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5402 ],
5403 );
5404
5405 let second_status_entry = entries[3].clone();
5406 panel.update_in(cx, |panel, window, cx| {
5407 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5408 });
5409
5410 panel.update_in(cx, |panel, window, cx| {
5411 panel.selected_entry = Some(7);
5412 panel.stage_range(&git::StageRange, window, cx);
5413 });
5414
5415 cx.read(|cx| {
5416 project
5417 .read(cx)
5418 .worktrees(cx)
5419 .next()
5420 .unwrap()
5421 .read(cx)
5422 .as_local()
5423 .unwrap()
5424 .scan_complete()
5425 })
5426 .await;
5427
5428 cx.executor().run_until_parked();
5429
5430 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5431 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5432 });
5433 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5434 handle.await;
5435
5436 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5437 #[rustfmt::skip]
5438 pretty_assertions::assert_matches!(
5439 entries.as_slice(),
5440 &[
5441 Header(GitHeaderEntry { header: Section::Conflict }),
5442 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5443 Header(GitHeaderEntry { header: Section::Tracked }),
5444 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5445 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5446 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5447 Header(GitHeaderEntry { header: Section::New }),
5448 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5449 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5450 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5451 ],
5452 );
5453
5454 let third_status_entry = entries[4].clone();
5455 panel.update_in(cx, |panel, window, cx| {
5456 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5457 });
5458
5459 panel.update_in(cx, |panel, window, cx| {
5460 panel.selected_entry = Some(9);
5461 panel.stage_range(&git::StageRange, window, cx);
5462 });
5463
5464 cx.read(|cx| {
5465 project
5466 .read(cx)
5467 .worktrees(cx)
5468 .next()
5469 .unwrap()
5470 .read(cx)
5471 .as_local()
5472 .unwrap()
5473 .scan_complete()
5474 })
5475 .await;
5476
5477 cx.executor().run_until_parked();
5478
5479 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5480 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5481 });
5482 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5483 handle.await;
5484
5485 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5486 #[rustfmt::skip]
5487 pretty_assertions::assert_matches!(
5488 entries.as_slice(),
5489 &[
5490 Header(GitHeaderEntry { header: Section::Conflict }),
5491 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5492 Header(GitHeaderEntry { header: Section::Tracked }),
5493 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5494 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5495 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5496 Header(GitHeaderEntry { header: Section::New }),
5497 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5498 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5499 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
5500 ],
5501 );
5502 }
5503
5504 #[gpui::test]
5505 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
5506 use GitListEntry::*;
5507
5508 init_test(cx);
5509 let fs = FakeFs::new(cx.background_executor.clone());
5510 fs.insert_tree(
5511 "/root",
5512 json!({
5513 "project": {
5514 ".git": {},
5515 "src": {
5516 "main.rs": "fn main() {}",
5517 "lib.rs": "pub fn hello() {}",
5518 "utils.rs": "pub fn util() {}"
5519 },
5520 "tests": {
5521 "test.rs": "fn test() {}"
5522 },
5523 "new_file.txt": "new content",
5524 "another_new.rs": "// new file",
5525 "conflict.txt": "conflicted content"
5526 }
5527 }),
5528 )
5529 .await;
5530
5531 fs.set_status_for_repo(
5532 Path::new(path!("/root/project/.git")),
5533 &[
5534 ("src/main.rs", StatusCode::Modified.worktree()),
5535 ("src/lib.rs", StatusCode::Modified.worktree()),
5536 ("tests/test.rs", StatusCode::Modified.worktree()),
5537 ("new_file.txt", FileStatus::Untracked),
5538 ("another_new.rs", FileStatus::Untracked),
5539 ("src/utils.rs", FileStatus::Untracked),
5540 (
5541 "conflict.txt",
5542 UnmergedStatus {
5543 first_head: UnmergedStatusCode::Updated,
5544 second_head: UnmergedStatusCode::Updated,
5545 }
5546 .into(),
5547 ),
5548 ],
5549 );
5550
5551 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5552 let workspace =
5553 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5554 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5555
5556 cx.read(|cx| {
5557 project
5558 .read(cx)
5559 .worktrees(cx)
5560 .next()
5561 .unwrap()
5562 .read(cx)
5563 .as_local()
5564 .unwrap()
5565 .scan_complete()
5566 })
5567 .await;
5568
5569 cx.executor().run_until_parked();
5570
5571 let panel = workspace.update(cx, GitPanel::new).unwrap();
5572
5573 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5574 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5575 });
5576 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5577 handle.await;
5578
5579 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5580 #[rustfmt::skip]
5581 pretty_assertions::assert_matches!(
5582 entries.as_slice(),
5583 &[
5584 Header(GitHeaderEntry { header: Section::Conflict }),
5585 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5586 Header(GitHeaderEntry { header: Section::Tracked }),
5587 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5588 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5589 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5590 Header(GitHeaderEntry { header: Section::New }),
5591 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5592 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5593 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
5594 ],
5595 );
5596
5597 assert_entry_paths(
5598 &entries,
5599 &[
5600 None,
5601 Some("conflict.txt"),
5602 None,
5603 Some("src/lib.rs"),
5604 Some("src/main.rs"),
5605 Some("tests/test.rs"),
5606 None,
5607 Some("another_new.rs"),
5608 Some("new_file.txt"),
5609 Some("src/utils.rs"),
5610 ],
5611 );
5612
5613 let second_status_entry = entries[3].clone();
5614 panel.update_in(cx, |panel, window, cx| {
5615 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
5616 });
5617
5618 cx.update(|_window, cx| {
5619 SettingsStore::update_global(cx, |store, cx| {
5620 store.update_user_settings(cx, |settings| {
5621 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5622 })
5623 });
5624 });
5625
5626 panel.update_in(cx, |panel, window, cx| {
5627 panel.selected_entry = Some(7);
5628 panel.stage_range(&git::StageRange, window, cx);
5629 });
5630
5631 cx.read(|cx| {
5632 project
5633 .read(cx)
5634 .worktrees(cx)
5635 .next()
5636 .unwrap()
5637 .read(cx)
5638 .as_local()
5639 .unwrap()
5640 .scan_complete()
5641 })
5642 .await;
5643
5644 cx.executor().run_until_parked();
5645
5646 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5647 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5648 });
5649 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5650 handle.await;
5651
5652 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5653 #[rustfmt::skip]
5654 pretty_assertions::assert_matches!(
5655 entries.as_slice(),
5656 &[
5657 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5658 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5659 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5660 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5661 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5662 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5663 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5664 ],
5665 );
5666
5667 assert_entry_paths(
5668 &entries,
5669 &[
5670 Some("another_new.rs"),
5671 Some("conflict.txt"),
5672 Some("new_file.txt"),
5673 Some("src/lib.rs"),
5674 Some("src/main.rs"),
5675 Some("src/utils.rs"),
5676 Some("tests/test.rs"),
5677 ],
5678 );
5679
5680 let third_status_entry = entries[4].clone();
5681 panel.update_in(cx, |panel, window, cx| {
5682 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
5683 });
5684
5685 panel.update_in(cx, |panel, window, cx| {
5686 panel.selected_entry = Some(9);
5687 panel.stage_range(&git::StageRange, window, cx);
5688 });
5689
5690 cx.read(|cx| {
5691 project
5692 .read(cx)
5693 .worktrees(cx)
5694 .next()
5695 .unwrap()
5696 .read(cx)
5697 .as_local()
5698 .unwrap()
5699 .scan_complete()
5700 })
5701 .await;
5702
5703 cx.executor().run_until_parked();
5704
5705 let handle = cx.update_window_entity(&panel, |panel, _, _| {
5706 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5707 });
5708 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
5709 handle.await;
5710
5711 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
5712 #[rustfmt::skip]
5713 pretty_assertions::assert_matches!(
5714 entries.as_slice(),
5715 &[
5716 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5717 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
5718 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5719 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5720 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
5721 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
5722 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
5723 ],
5724 );
5725
5726 assert_entry_paths(
5727 &entries,
5728 &[
5729 Some("another_new.rs"),
5730 Some("conflict.txt"),
5731 Some("new_file.txt"),
5732 Some("src/lib.rs"),
5733 Some("src/main.rs"),
5734 Some("src/utils.rs"),
5735 Some("tests/test.rs"),
5736 ],
5737 );
5738 }
5739
5740 #[gpui::test]
5741 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
5742 init_test(cx);
5743 let fs = FakeFs::new(cx.background_executor.clone());
5744 fs.insert_tree(
5745 "/root",
5746 json!({
5747 "project": {
5748 ".git": {},
5749 "src": {
5750 "main.rs": "fn main() {}"
5751 }
5752 }
5753 }),
5754 )
5755 .await;
5756
5757 fs.set_status_for_repo(
5758 Path::new(path!("/root/project/.git")),
5759 &[("src/main.rs", StatusCode::Modified.worktree())],
5760 );
5761
5762 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
5763 let workspace =
5764 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5765 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5766
5767 let panel = workspace.update(cx, GitPanel::new).unwrap();
5768
5769 // Test: User has commit message, enables amend (saves message), then disables (restores message)
5770 panel.update(cx, |panel, cx| {
5771 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5772 let start = buffer.anchor_before(0);
5773 let end = buffer.anchor_after(buffer.len());
5774 buffer.edit([(start..end, "Initial commit message")], None, cx);
5775 });
5776
5777 panel.set_amend_pending(true, cx);
5778 assert!(panel.original_commit_message.is_some());
5779
5780 panel.set_amend_pending(false, cx);
5781 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5782 assert_eq!(current_message, "Initial commit message");
5783 assert!(panel.original_commit_message.is_none());
5784 });
5785
5786 // Test: User has empty commit message, enables amend, then disables (clears message)
5787 panel.update(cx, |panel, cx| {
5788 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5789 let start = buffer.anchor_before(0);
5790 let end = buffer.anchor_after(buffer.len());
5791 buffer.edit([(start..end, "")], None, cx);
5792 });
5793
5794 panel.set_amend_pending(true, cx);
5795 assert!(panel.original_commit_message.is_none());
5796
5797 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
5798 let start = buffer.anchor_before(0);
5799 let end = buffer.anchor_after(buffer.len());
5800 buffer.edit([(start..end, "Previous commit message")], None, cx);
5801 });
5802
5803 panel.set_amend_pending(false, cx);
5804 let current_message = panel.commit_message_buffer(cx).read(cx).text();
5805 assert_eq!(current_message, "");
5806 });
5807 }
5808
5809 #[gpui::test]
5810 async fn test_open_diff(cx: &mut TestAppContext) {
5811 init_test(cx);
5812
5813 let fs = FakeFs::new(cx.background_executor.clone());
5814 fs.insert_tree(
5815 path!("/project"),
5816 json!({
5817 ".git": {},
5818 "tracked": "tracked\n",
5819 "untracked": "\n",
5820 }),
5821 )
5822 .await;
5823
5824 fs.set_head_and_index_for_repo(
5825 path!("/project/.git").as_ref(),
5826 &[("tracked", "old tracked\n".into())],
5827 );
5828
5829 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
5830 let workspace =
5831 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
5832 let cx = &mut VisualTestContext::from_window(*workspace, cx);
5833 let panel = workspace.update(cx, GitPanel::new).unwrap();
5834
5835 // Enable the `sort_by_path` setting and wait for entries to be updated,
5836 // as there should no longer be separators between Tracked and Untracked
5837 // files.
5838 cx.update(|_window, cx| {
5839 SettingsStore::update_global(cx, |store, cx| {
5840 store.update_user_settings(cx, |settings| {
5841 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
5842 })
5843 });
5844 });
5845
5846 cx.update_window_entity(&panel, |panel, _, _| {
5847 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
5848 })
5849 .await;
5850
5851 // Confirm that `Open Diff` still works for the untracked file, updating
5852 // the Project Diff's active path.
5853 panel.update_in(cx, |panel, window, cx| {
5854 panel.selected_entry = Some(1);
5855 panel.open_diff(&Confirm, window, cx);
5856 });
5857 cx.run_until_parked();
5858
5859 let _ = workspace.update(cx, |workspace, _window, cx| {
5860 let active_path = workspace
5861 .item_of_type::<ProjectDiff>(cx)
5862 .expect("ProjectDiff should exist")
5863 .read(cx)
5864 .active_path(cx)
5865 .expect("active_path should exist");
5866
5867 assert_eq!(active_path.path, rel_path("untracked").into_arc());
5868 });
5869 }
5870
5871 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
5872 assert_eq!(entries.len(), expected_paths.len());
5873 for (entry, expected_path) in entries.iter().zip(expected_paths) {
5874 assert_eq!(
5875 entry.status_entry().map(|status| status
5876 .repo_path
5877 .as_ref()
5878 .as_std_path()
5879 .to_string_lossy()
5880 .to_string()),
5881 expected_path.map(|s| s.to_string())
5882 );
5883 }
5884 }
5885
5886 #[test]
5887 fn test_compress_diff_no_truncation() {
5888 let diff = indoc! {"
5889 --- a/file.txt
5890 +++ b/file.txt
5891 @@ -1,2 +1,2 @@
5892 -old
5893 +new
5894 "};
5895 let result = GitPanel::compress_commit_diff(diff, 1000);
5896 assert_eq!(result, diff);
5897 }
5898
5899 #[test]
5900 fn test_compress_diff_truncate_long_lines() {
5901 let long_line = "a".repeat(300);
5902 let diff = indoc::formatdoc! {"
5903 --- a/file.txt
5904 +++ b/file.txt
5905 @@ -1,2 +1,3 @@
5906 context
5907 +{}
5908 more context
5909 ", long_line};
5910 let result = GitPanel::compress_commit_diff(&diff, 100);
5911 assert!(result.contains("...[truncated]"));
5912 assert!(result.len() < diff.len());
5913 }
5914
5915 #[test]
5916 fn test_compress_diff_truncate_hunks() {
5917 let diff = indoc! {"
5918 --- a/file.txt
5919 +++ b/file.txt
5920 @@ -1,2 +1,2 @@
5921 context
5922 -old1
5923 +new1
5924 @@ -5,2 +5,2 @@
5925 context 2
5926 -old2
5927 +new2
5928 @@ -10,2 +10,2 @@
5929 context 3
5930 -old3
5931 +new3
5932 "};
5933 let result = GitPanel::compress_commit_diff(diff, 100);
5934 let expected = indoc! {"
5935 --- a/file.txt
5936 +++ b/file.txt
5937 @@ -1,2 +1,2 @@
5938 context
5939 -old1
5940 +new1
5941 [...skipped 2 hunks...]
5942 "};
5943 assert_eq!(result, expected);
5944 }
5945}