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