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