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 });
3602 workspace.toggle_status_toast(status_toast, cx)
3603 });
3604 }
3605
3606 pub fn can_commit(&self) -> bool {
3607 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
3608 }
3609
3610 pub fn can_stage_all(&self) -> bool {
3611 self.has_unstaged_changes()
3612 }
3613
3614 pub fn can_unstage_all(&self) -> bool {
3615 self.has_staged_changes()
3616 }
3617
3618 fn status_width_estimate(
3619 tree_view: bool,
3620 entry: &GitStatusEntry,
3621 path_style: PathStyle,
3622 depth: usize,
3623 ) -> usize {
3624 if tree_view {
3625 Self::item_width_estimate(0, entry.display_name(path_style).len(), depth)
3626 } else {
3627 Self::item_width_estimate(
3628 entry.parent_dir(path_style).map(|s| s.len()).unwrap_or(0),
3629 entry.display_name(path_style).len(),
3630 0,
3631 )
3632 }
3633 }
3634
3635 fn width_estimate_for_list_entry(
3636 &self,
3637 tree_view: bool,
3638 entry: &GitListEntry,
3639 path_style: PathStyle,
3640 ) -> Option<usize> {
3641 match entry {
3642 GitListEntry::Status(status) => Some(Self::status_width_estimate(
3643 tree_view, status, path_style, 0,
3644 )),
3645 GitListEntry::TreeStatus(status) => Some(Self::status_width_estimate(
3646 tree_view,
3647 &status.entry,
3648 path_style,
3649 status.depth,
3650 )),
3651 GitListEntry::Directory(dir) => {
3652 Some(Self::item_width_estimate(0, dir.name.len(), dir.depth))
3653 }
3654 GitListEntry::Header(_) => None,
3655 }
3656 }
3657
3658 fn item_width_estimate(path: usize, file_name: usize, depth: usize) -> usize {
3659 path + file_name + depth * 2
3660 }
3661
3662 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3663 let focus_handle = self.focus_handle.clone();
3664 let has_tracked_changes = self.has_tracked_changes();
3665 let has_staged_changes = self.has_staged_changes();
3666 let has_unstaged_changes = self.has_unstaged_changes();
3667 let has_new_changes = self.new_count > 0;
3668 let has_stash_items = self.stash_entries.entries.len() > 0;
3669
3670 PopoverMenu::new(id.into())
3671 .trigger(
3672 IconButton::new("overflow-menu-trigger", IconName::Ellipsis)
3673 .icon_size(IconSize::Small)
3674 .icon_color(Color::Muted),
3675 )
3676 .menu(move |window, cx| {
3677 Some(git_panel_context_menu(
3678 focus_handle.clone(),
3679 GitMenuState {
3680 has_tracked_changes,
3681 has_staged_changes,
3682 has_unstaged_changes,
3683 has_new_changes,
3684 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
3685 has_stash_items,
3686 tree_view: GitPanelSettings::get_global(cx).tree_view,
3687 },
3688 window,
3689 cx,
3690 ))
3691 })
3692 .anchor(Corner::TopRight)
3693 }
3694
3695 pub(crate) fn render_generate_commit_message_button(
3696 &self,
3697 cx: &Context<Self>,
3698 ) -> Option<AnyElement> {
3699 if !agent_settings::AgentSettings::get_global(cx).enabled(cx)
3700 || LanguageModelRegistry::read_global(cx)
3701 .commit_message_model()
3702 .is_none()
3703 {
3704 return None;
3705 }
3706
3707 if self.generate_commit_message_task.is_some() {
3708 return Some(
3709 h_flex()
3710 .gap_1()
3711 .child(
3712 Icon::new(IconName::ArrowCircle)
3713 .size(IconSize::XSmall)
3714 .color(Color::Info)
3715 .with_rotate_animation(2),
3716 )
3717 .child(
3718 Label::new("Generating Commit...")
3719 .size(LabelSize::Small)
3720 .color(Color::Muted),
3721 )
3722 .into_any_element(),
3723 );
3724 }
3725
3726 let can_commit = self.can_commit();
3727 let editor_focus_handle = self.commit_editor.focus_handle(cx);
3728 Some(
3729 IconButton::new("generate-commit-message", IconName::AiEdit)
3730 .shape(ui::IconButtonShape::Square)
3731 .icon_color(Color::Muted)
3732 .tooltip(move |_window, cx| {
3733 if can_commit {
3734 Tooltip::for_action_in(
3735 "Generate Commit Message",
3736 &git::GenerateCommitMessage,
3737 &editor_focus_handle,
3738 cx,
3739 )
3740 } else {
3741 Tooltip::simple("No changes to commit", cx)
3742 }
3743 })
3744 .disabled(!can_commit)
3745 .on_click(cx.listener(move |this, _event, _window, cx| {
3746 this.generate_commit_message(cx);
3747 }))
3748 .into_any_element(),
3749 )
3750 }
3751
3752 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
3753 let potential_co_authors = self.potential_co_authors(cx);
3754
3755 let (tooltip_label, icon) = if self.add_coauthors {
3756 ("Remove co-authored-by", IconName::Person)
3757 } else {
3758 ("Add co-authored-by", IconName::UserCheck)
3759 };
3760
3761 if potential_co_authors.is_empty() {
3762 None
3763 } else {
3764 Some(
3765 IconButton::new("co-authors", icon)
3766 .shape(ui::IconButtonShape::Square)
3767 .icon_color(Color::Disabled)
3768 .selected_icon_color(Color::Selected)
3769 .toggle_state(self.add_coauthors)
3770 .tooltip(move |_, cx| {
3771 let title = format!(
3772 "{}:{}{}",
3773 tooltip_label,
3774 if potential_co_authors.len() == 1 {
3775 ""
3776 } else {
3777 "\n"
3778 },
3779 potential_co_authors
3780 .iter()
3781 .map(|(name, email)| format!(" {} <{}>", name, email))
3782 .join("\n")
3783 );
3784 Tooltip::simple(title, cx)
3785 })
3786 .on_click(cx.listener(|this, _, _, cx| {
3787 this.add_coauthors = !this.add_coauthors;
3788 cx.notify();
3789 }))
3790 .into_any_element(),
3791 )
3792 }
3793 }
3794
3795 fn render_git_commit_menu(
3796 &self,
3797 id: impl Into<ElementId>,
3798 keybinding_target: Option<FocusHandle>,
3799 cx: &mut Context<Self>,
3800 ) -> impl IntoElement {
3801 PopoverMenu::new(id.into())
3802 .trigger(
3803 ui::ButtonLike::new_rounded_right("commit-split-button-right")
3804 .layer(ui::ElevationIndex::ModalSurface)
3805 .size(ButtonSize::None)
3806 .child(
3807 h_flex()
3808 .px_1()
3809 .h_full()
3810 .justify_center()
3811 .border_l_1()
3812 .border_color(cx.theme().colors().border)
3813 .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
3814 ),
3815 )
3816 .menu({
3817 let git_panel = cx.entity();
3818 let has_previous_commit = self.head_commit(cx).is_some();
3819 let amend = self.amend_pending();
3820 let signoff = self.signoff_enabled;
3821
3822 move |window, cx| {
3823 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3824 context_menu
3825 .when_some(keybinding_target.clone(), |el, keybinding_target| {
3826 el.context(keybinding_target)
3827 })
3828 .when(has_previous_commit, |this| {
3829 this.toggleable_entry(
3830 "Amend",
3831 amend,
3832 IconPosition::Start,
3833 Some(Box::new(Amend)),
3834 {
3835 let git_panel = git_panel.downgrade();
3836 move |_, cx| {
3837 git_panel
3838 .update(cx, |git_panel, cx| {
3839 git_panel.toggle_amend_pending(cx);
3840 })
3841 .ok();
3842 }
3843 },
3844 )
3845 })
3846 .toggleable_entry(
3847 "Signoff",
3848 signoff,
3849 IconPosition::Start,
3850 Some(Box::new(Signoff)),
3851 move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
3852 )
3853 }))
3854 }
3855 })
3856 .anchor(Corner::TopRight)
3857 }
3858
3859 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
3860 if self.has_unstaged_conflicts() {
3861 (false, "You must resolve conflicts before committing")
3862 } else if !self.has_staged_changes() && !self.has_tracked_changes() && !self.amend_pending {
3863 (false, "No changes to commit")
3864 } else if self.pending_commit.is_some() {
3865 (false, "Commit in progress")
3866 } else if !self.has_commit_message(cx) {
3867 (false, "No commit message")
3868 } else if !self.has_write_access(cx) {
3869 (false, "You do not have write access to this project")
3870 } else {
3871 (true, self.commit_button_title())
3872 }
3873 }
3874
3875 pub fn commit_button_title(&self) -> &'static str {
3876 if self.amend_pending {
3877 if self.has_staged_changes() {
3878 "Amend"
3879 } else if self.has_tracked_changes() {
3880 "Amend Tracked"
3881 } else {
3882 "Amend"
3883 }
3884 } else if self.has_staged_changes() {
3885 "Commit"
3886 } else {
3887 "Commit Tracked"
3888 }
3889 }
3890
3891 fn expand_commit_editor(
3892 &mut self,
3893 _: &git::ExpandCommitEditor,
3894 window: &mut Window,
3895 cx: &mut Context<Self>,
3896 ) {
3897 let workspace = self.workspace.clone();
3898 window.defer(cx, move |window, cx| {
3899 workspace
3900 .update(cx, |workspace, cx| {
3901 CommitModal::toggle(workspace, None, window, cx)
3902 })
3903 .ok();
3904 })
3905 }
3906
3907 fn render_panel_header(
3908 &self,
3909 window: &mut Window,
3910 cx: &mut Context<Self>,
3911 ) -> Option<impl IntoElement> {
3912 self.active_repository.as_ref()?;
3913
3914 let (text, action, stage, tooltip) =
3915 if self.total_staged_count() == self.entry_count && self.entry_count > 0 {
3916 ("Unstage All", UnstageAll.boxed_clone(), false, "git reset")
3917 } else {
3918 ("Stage All", StageAll.boxed_clone(), true, "git add --all")
3919 };
3920
3921 let change_string = match self.changes_count {
3922 0 => "No Changes".to_string(),
3923 1 => "1 Change".to_string(),
3924 count => format!("{} Changes", count),
3925 };
3926
3927 Some(
3928 self.panel_header_container(window, cx)
3929 .px_2()
3930 .justify_between()
3931 .child(
3932 panel_button(change_string)
3933 .color(Color::Muted)
3934 .tooltip(Tooltip::for_action_title_in(
3935 "Open Diff",
3936 &Diff,
3937 &self.focus_handle,
3938 ))
3939 .on_click(|_, _, cx| {
3940 cx.defer(|cx| {
3941 cx.dispatch_action(&Diff);
3942 })
3943 }),
3944 )
3945 .child(
3946 h_flex()
3947 .gap_1()
3948 .child(self.render_overflow_menu("overflow_menu"))
3949 .child(
3950 panel_filled_button(text)
3951 .tooltip(Tooltip::for_action_title_in(
3952 tooltip,
3953 action.as_ref(),
3954 &self.focus_handle,
3955 ))
3956 .disabled(self.entry_count == 0)
3957 .on_click({
3958 let git_panel = cx.weak_entity();
3959 move |_, _, cx| {
3960 git_panel
3961 .update(cx, |git_panel, cx| {
3962 git_panel.change_all_files_stage(stage, cx);
3963 })
3964 .ok();
3965 }
3966 }),
3967 ),
3968 ),
3969 )
3970 }
3971
3972 pub(crate) fn render_remote_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
3973 let branch = self.active_repository.as_ref()?.read(cx).branch.clone();
3974 if !self.can_push_and_pull(cx) {
3975 return None;
3976 }
3977 Some(
3978 h_flex()
3979 .gap_1()
3980 .flex_shrink_0()
3981 .when_some(branch, |this, branch| {
3982 let focus_handle = Some(self.focus_handle(cx));
3983
3984 this.children(render_remote_button(
3985 "remote-button",
3986 &branch,
3987 focus_handle,
3988 true,
3989 ))
3990 })
3991 .into_any_element(),
3992 )
3993 }
3994
3995 pub fn render_footer(
3996 &self,
3997 window: &mut Window,
3998 cx: &mut Context<Self>,
3999 ) -> Option<impl IntoElement> {
4000 let active_repository = self.active_repository.clone()?;
4001 let panel_editor_style = panel_editor_style(true, window, cx);
4002 let enable_coauthors = self.render_co_authors(cx);
4003
4004 let editor_focus_handle = self.commit_editor.focus_handle(cx);
4005 let expand_tooltip_focus_handle = editor_focus_handle;
4006
4007 let branch = active_repository.read(cx).branch.clone();
4008 let head_commit = active_repository.read(cx).head_commit.clone();
4009
4010 let footer_size = px(32.);
4011 let gap = px(9.0);
4012 let max_height = panel_editor_style
4013 .text
4014 .line_height_in_pixels(window.rem_size())
4015 * MAX_PANEL_EDITOR_LINES
4016 + gap;
4017
4018 let git_panel = cx.entity();
4019 let display_name = SharedString::from(Arc::from(
4020 active_repository
4021 .read(cx)
4022 .display_name()
4023 .trim_end_matches("/"),
4024 ));
4025 let editor_is_long = self.commit_editor.update(cx, |editor, cx| {
4026 editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32
4027 });
4028
4029 let footer = v_flex()
4030 .child(PanelRepoFooter::new(
4031 display_name,
4032 branch,
4033 head_commit,
4034 Some(git_panel),
4035 ))
4036 .child(
4037 panel_editor_container(window, cx)
4038 .id("commit-editor-container")
4039 .relative()
4040 .w_full()
4041 .h(max_height + footer_size)
4042 .border_t_1()
4043 .border_color(cx.theme().colors().border)
4044 .cursor_text()
4045 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
4046 window.focus(&this.commit_editor.focus_handle(cx));
4047 }))
4048 .child(
4049 h_flex()
4050 .id("commit-footer")
4051 .border_t_1()
4052 .when(editor_is_long, |el| {
4053 el.border_color(cx.theme().colors().border_variant)
4054 })
4055 .absolute()
4056 .bottom_0()
4057 .left_0()
4058 .w_full()
4059 .px_2()
4060 .h(footer_size)
4061 .flex_none()
4062 .justify_between()
4063 .child(
4064 self.render_generate_commit_message_button(cx)
4065 .unwrap_or_else(|| div().into_any_element()),
4066 )
4067 .child(
4068 h_flex()
4069 .gap_0p5()
4070 .children(enable_coauthors)
4071 .child(self.render_commit_button(cx)),
4072 ),
4073 )
4074 .child(
4075 div()
4076 .pr_2p5()
4077 .on_action(|&editor::actions::MoveUp, _, cx| {
4078 cx.stop_propagation();
4079 })
4080 .on_action(|&editor::actions::MoveDown, _, cx| {
4081 cx.stop_propagation();
4082 })
4083 .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
4084 )
4085 .child(
4086 h_flex()
4087 .absolute()
4088 .top_2()
4089 .right_2()
4090 .opacity(0.5)
4091 .hover(|this| this.opacity(1.0))
4092 .child(
4093 panel_icon_button("expand-commit-editor", IconName::Maximize)
4094 .icon_size(IconSize::Small)
4095 .size(ui::ButtonSize::Default)
4096 .tooltip(move |_window, cx| {
4097 Tooltip::for_action_in(
4098 "Open Commit Modal",
4099 &git::ExpandCommitEditor,
4100 &expand_tooltip_focus_handle,
4101 cx,
4102 )
4103 })
4104 .on_click(cx.listener({
4105 move |_, _, window, cx| {
4106 window.dispatch_action(
4107 git::ExpandCommitEditor.boxed_clone(),
4108 cx,
4109 )
4110 }
4111 })),
4112 ),
4113 ),
4114 );
4115
4116 Some(footer)
4117 }
4118
4119 fn render_commit_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
4120 let (can_commit, tooltip) = self.configure_commit_button(cx);
4121 let title = self.commit_button_title();
4122 let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
4123 let amend = self.amend_pending();
4124 let signoff = self.signoff_enabled;
4125
4126 let label_color = if self.pending_commit.is_some() {
4127 Color::Disabled
4128 } else {
4129 Color::Default
4130 };
4131
4132 div()
4133 .id("commit-wrapper")
4134 .on_hover(cx.listener(move |this, hovered, _, cx| {
4135 this.show_placeholders =
4136 *hovered && !this.has_staged_changes() && !this.has_unstaged_conflicts();
4137 cx.notify()
4138 }))
4139 .child(SplitButton::new(
4140 ButtonLike::new_rounded_left(ElementId::Name(
4141 format!("split-button-left-{}", title).into(),
4142 ))
4143 .layer(ElevationIndex::ModalSurface)
4144 .size(ButtonSize::Compact)
4145 .child(
4146 Label::new(title)
4147 .size(LabelSize::Small)
4148 .color(label_color)
4149 .mr_0p5(),
4150 )
4151 .on_click({
4152 let git_panel = cx.weak_entity();
4153 move |_, window, cx| {
4154 telemetry::event!("Git Committed", source = "Git Panel");
4155 git_panel
4156 .update(cx, |git_panel, cx| {
4157 git_panel.commit_changes(
4158 CommitOptions { amend, signoff },
4159 window,
4160 cx,
4161 );
4162 })
4163 .ok();
4164 }
4165 })
4166 .disabled(!can_commit || self.modal_open)
4167 .tooltip({
4168 let handle = commit_tooltip_focus_handle.clone();
4169 move |_window, cx| {
4170 if can_commit {
4171 Tooltip::with_meta_in(
4172 tooltip,
4173 Some(if amend { &git::Amend } else { &git::Commit }),
4174 format!(
4175 "git commit{}{}",
4176 if amend { " --amend" } else { "" },
4177 if signoff { " --signoff" } else { "" }
4178 ),
4179 &handle.clone(),
4180 cx,
4181 )
4182 } else {
4183 Tooltip::simple(tooltip, cx)
4184 }
4185 }
4186 }),
4187 self.render_git_commit_menu(
4188 ElementId::Name(format!("split-button-right-{}", title).into()),
4189 Some(commit_tooltip_focus_handle),
4190 cx,
4191 )
4192 .into_any_element(),
4193 ))
4194 }
4195
4196 fn render_pending_amend(&self, cx: &mut Context<Self>) -> impl IntoElement {
4197 h_flex()
4198 .py_1p5()
4199 .px_2()
4200 .gap_1p5()
4201 .justify_between()
4202 .border_t_1()
4203 .border_color(cx.theme().colors().border.opacity(0.8))
4204 .child(
4205 div()
4206 .flex_grow()
4207 .overflow_hidden()
4208 .max_w(relative(0.85))
4209 .child(
4210 Label::new("This will update your most recent commit.")
4211 .size(LabelSize::Small)
4212 .truncate(),
4213 ),
4214 )
4215 .child(
4216 panel_button("Cancel")
4217 .size(ButtonSize::Default)
4218 .on_click(cx.listener(|this, _, _, cx| this.set_amend_pending(false, cx))),
4219 )
4220 }
4221
4222 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
4223 let active_repository = self.active_repository.as_ref()?;
4224 let branch = active_repository.read(cx).branch.as_ref()?;
4225 let commit = branch.most_recent_commit.as_ref()?.clone();
4226 let workspace = self.workspace.clone();
4227 let this = cx.entity();
4228
4229 Some(
4230 h_flex()
4231 .py_1p5()
4232 .px_2()
4233 .gap_1p5()
4234 .justify_between()
4235 .border_t_1()
4236 .border_color(cx.theme().colors().border.opacity(0.8))
4237 .child(
4238 div()
4239 .cursor_pointer()
4240 .overflow_hidden()
4241 .line_clamp(1)
4242 .child(
4243 Label::new(commit.subject.clone())
4244 .size(LabelSize::Small)
4245 .truncate(),
4246 )
4247 .id("commit-msg-hover")
4248 .on_click({
4249 let commit = commit.clone();
4250 let repo = active_repository.downgrade();
4251 move |_, window, cx| {
4252 CommitView::open(
4253 commit.sha.to_string(),
4254 repo.clone(),
4255 workspace.clone(),
4256 None,
4257 None,
4258 window,
4259 cx,
4260 );
4261 }
4262 })
4263 .hoverable_tooltip({
4264 let repo = active_repository.clone();
4265 move |window, cx| {
4266 GitPanelMessageTooltip::new(
4267 this.clone(),
4268 commit.sha.clone(),
4269 repo.clone(),
4270 window,
4271 cx,
4272 )
4273 .into()
4274 }
4275 }),
4276 )
4277 .when(commit.has_parent, |this| {
4278 let has_unstaged = self.has_unstaged_changes();
4279 this.child(
4280 panel_icon_button("undo", IconName::Undo)
4281 .icon_size(IconSize::XSmall)
4282 .icon_color(Color::Muted)
4283 .tooltip(move |_window, cx| {
4284 Tooltip::with_meta(
4285 "Uncommit",
4286 Some(&git::Uncommit),
4287 if has_unstaged {
4288 "git reset HEAD^ --soft"
4289 } else {
4290 "git reset HEAD^"
4291 },
4292 cx,
4293 )
4294 })
4295 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
4296 )
4297 }),
4298 )
4299 }
4300
4301 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
4302 h_flex().h_full().flex_grow().justify_center().child(
4303 v_flex()
4304 .gap_2()
4305 .child(h_flex().w_full().justify_around().child(
4306 if self.active_repository.is_some() {
4307 "No changes to commit"
4308 } else {
4309 "No Git repositories"
4310 },
4311 ))
4312 .children({
4313 let worktree_count = self.project.read(cx).visible_worktrees(cx).count();
4314 (worktree_count > 0 && self.active_repository.is_none()).then(|| {
4315 h_flex().w_full().justify_around().child(
4316 panel_filled_button("Initialize Repository")
4317 .tooltip(Tooltip::for_action_title_in(
4318 "git init",
4319 &git::Init,
4320 &self.focus_handle,
4321 ))
4322 .on_click(move |_, _, cx| {
4323 cx.defer(move |cx| {
4324 cx.dispatch_action(&git::Init);
4325 })
4326 }),
4327 )
4328 })
4329 })
4330 .text_ui_sm(cx)
4331 .mx_auto()
4332 .text_color(Color::Placeholder.color(cx)),
4333 )
4334 }
4335
4336 fn render_buffer_header_controls(
4337 &self,
4338 entity: &Entity<Self>,
4339 file: &Arc<dyn File>,
4340 _: &Window,
4341 cx: &App,
4342 ) -> Option<AnyElement> {
4343 let repo = self.active_repository.as_ref()?.read(cx);
4344 let project_path = (file.worktree_id(cx), file.path().clone()).into();
4345 let repo_path = repo.project_path_to_repo_path(&project_path, cx)?;
4346 let ix = self.entry_by_path(&repo_path)?;
4347 let entry = self.entries.get(ix)?;
4348
4349 let is_staging_or_staged = repo
4350 .pending_ops_for_path(&repo_path)
4351 .map(|ops| ops.staging() || ops.staged())
4352 .or_else(|| {
4353 repo.status_for_path(&repo_path)
4354 .and_then(|status| status.status.staging().as_bool())
4355 })
4356 .or_else(|| {
4357 entry
4358 .status_entry()
4359 .and_then(|entry| entry.staging.as_bool())
4360 });
4361
4362 let checkbox = Checkbox::new("stage-file", is_staging_or_staged.into())
4363 .disabled(!self.has_write_access(cx))
4364 .fill()
4365 .elevation(ElevationIndex::Surface)
4366 .on_click({
4367 let entry = entry.clone();
4368 let git_panel = entity.downgrade();
4369 move |_, window, cx| {
4370 git_panel
4371 .update(cx, |this, cx| {
4372 this.toggle_staged_for_entry(&entry, window, cx);
4373 cx.stop_propagation();
4374 })
4375 .ok();
4376 }
4377 });
4378 Some(
4379 h_flex()
4380 .id("start-slot")
4381 .text_lg()
4382 .child(checkbox)
4383 .on_mouse_down(MouseButton::Left, |_, _, cx| {
4384 // prevent the list item active state triggering when toggling checkbox
4385 cx.stop_propagation();
4386 })
4387 .into_any_element(),
4388 )
4389 }
4390
4391 fn render_entries(
4392 &self,
4393 has_write_access: bool,
4394 window: &mut Window,
4395 cx: &mut Context<Self>,
4396 ) -> impl IntoElement {
4397 let (is_tree_view, entry_count) = match &self.view_mode {
4398 GitPanelViewMode::Tree(state) => (true, state.logical_indices.len()),
4399 GitPanelViewMode::Flat => (false, self.entries.len()),
4400 };
4401
4402 v_flex()
4403 .flex_1()
4404 .size_full()
4405 .overflow_hidden()
4406 .relative()
4407 .child(
4408 h_flex()
4409 .flex_1()
4410 .size_full()
4411 .relative()
4412 .overflow_hidden()
4413 .child(
4414 uniform_list(
4415 "entries",
4416 entry_count,
4417 cx.processor(move |this, range: Range<usize>, window, cx| {
4418 let mut items = Vec::with_capacity(range.end - range.start);
4419
4420 for ix in range.into_iter().map(|ix| match &this.view_mode {
4421 GitPanelViewMode::Tree(state) => state.logical_indices[ix],
4422 GitPanelViewMode::Flat => ix,
4423 }) {
4424 match &this.entries.get(ix) {
4425 Some(GitListEntry::Status(entry)) => {
4426 items.push(this.render_status_entry(
4427 ix,
4428 entry,
4429 0,
4430 has_write_access,
4431 window,
4432 cx,
4433 ));
4434 }
4435 Some(GitListEntry::TreeStatus(entry)) => {
4436 items.push(this.render_status_entry(
4437 ix,
4438 &entry.entry,
4439 entry.depth,
4440 has_write_access,
4441 window,
4442 cx,
4443 ));
4444 }
4445 Some(GitListEntry::Directory(entry)) => {
4446 items.push(this.render_directory_entry(
4447 ix,
4448 entry,
4449 has_write_access,
4450 window,
4451 cx,
4452 ));
4453 }
4454 Some(GitListEntry::Header(header)) => {
4455 items.push(this.render_list_header(
4456 ix,
4457 header,
4458 has_write_access,
4459 window,
4460 cx,
4461 ));
4462 }
4463 None => {}
4464 }
4465 }
4466
4467 items
4468 }),
4469 )
4470 .when(is_tree_view, |list| {
4471 let indent_size = px(TREE_INDENT);
4472 list.with_decoration(
4473 ui::indent_guides(indent_size, IndentGuideColors::panel(cx))
4474 .with_compute_indents_fn(
4475 cx.entity(),
4476 |this, range, _window, _cx| {
4477 range
4478 .map(|ix| match this.entries.get(ix) {
4479 Some(GitListEntry::Directory(dir)) => dir.depth,
4480 Some(GitListEntry::TreeStatus(status)) => {
4481 status.depth
4482 }
4483 _ => 0,
4484 })
4485 .collect()
4486 },
4487 )
4488 .with_render_fn(cx.entity(), |_, params, _, _| {
4489 let left_offset = px(TREE_INDENT_GUIDE_OFFSET);
4490 let indent_size = params.indent_size;
4491 let item_height = params.item_height;
4492
4493 params
4494 .indent_guides
4495 .into_iter()
4496 .map(|layout| {
4497 let bounds = Bounds::new(
4498 point(
4499 layout.offset.x * indent_size + left_offset,
4500 layout.offset.y * item_height,
4501 ),
4502 size(px(1.), layout.length * item_height),
4503 );
4504 RenderedIndentGuide {
4505 bounds,
4506 layout,
4507 is_active: false,
4508 hitbox: None,
4509 }
4510 })
4511 .collect()
4512 }),
4513 )
4514 })
4515 .size_full()
4516 .flex_grow()
4517 .with_sizing_behavior(ListSizingBehavior::Auto)
4518 .with_horizontal_sizing_behavior(
4519 ListHorizontalSizingBehavior::Unconstrained,
4520 )
4521 .with_width_from_item(self.max_width_item_index)
4522 .track_scroll(&self.scroll_handle),
4523 )
4524 .on_mouse_down(
4525 MouseButton::Right,
4526 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
4527 this.deploy_panel_context_menu(event.position, window, cx)
4528 }),
4529 )
4530 .custom_scrollbars(
4531 Scrollbars::for_settings::<GitPanelSettings>()
4532 .tracked_scroll_handle(&self.scroll_handle)
4533 .with_track_along(
4534 ScrollAxes::Horizontal,
4535 cx.theme().colors().panel_background,
4536 ),
4537 window,
4538 cx,
4539 ),
4540 )
4541 }
4542
4543 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
4544 Label::new(label.into()).color(color).single_line()
4545 }
4546
4547 fn list_item_height(&self) -> Rems {
4548 rems(1.75)
4549 }
4550
4551 fn render_list_header(
4552 &self,
4553 ix: usize,
4554 header: &GitHeaderEntry,
4555 _: bool,
4556 _: &Window,
4557 _: &Context<Self>,
4558 ) -> AnyElement {
4559 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
4560
4561 h_flex()
4562 .id(id)
4563 .h(self.list_item_height())
4564 .w_full()
4565 .items_end()
4566 .px(rems(0.75)) // ~12px
4567 .pb(rems(0.3125)) // ~ 5px
4568 .child(
4569 Label::new(header.title())
4570 .color(Color::Muted)
4571 .size(LabelSize::Small)
4572 .line_height_style(LineHeightStyle::UiLabel)
4573 .single_line(),
4574 )
4575 .into_any_element()
4576 }
4577
4578 pub fn load_commit_details(
4579 &self,
4580 sha: String,
4581 cx: &mut Context<Self>,
4582 ) -> Task<anyhow::Result<CommitDetails>> {
4583 let Some(repo) = self.active_repository.clone() else {
4584 return Task::ready(Err(anyhow::anyhow!("no active repo")));
4585 };
4586 repo.update(cx, |repo, cx| {
4587 let show = repo.show(sha);
4588 cx.spawn(async move |_, _| show.await?)
4589 })
4590 }
4591
4592 fn deploy_entry_context_menu(
4593 &mut self,
4594 position: Point<Pixels>,
4595 ix: usize,
4596 window: &mut Window,
4597 cx: &mut Context<Self>,
4598 ) {
4599 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
4600 return;
4601 };
4602 let stage_title = if entry.status.staging().is_fully_staged() {
4603 "Unstage File"
4604 } else {
4605 "Stage File"
4606 };
4607 let restore_title = if entry.status.is_created() {
4608 "Trash File"
4609 } else {
4610 "Restore File"
4611 };
4612 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
4613 let is_created = entry.status.is_created();
4614 context_menu
4615 .context(self.focus_handle.clone())
4616 .action(stage_title, ToggleStaged.boxed_clone())
4617 .action(restore_title, git::RestoreFile::default().boxed_clone())
4618 .action_disabled_when(
4619 !is_created,
4620 "Add to .gitignore",
4621 git::AddToGitignore.boxed_clone(),
4622 )
4623 .separator()
4624 .action("Open Diff", Confirm.boxed_clone())
4625 .action("Open File", SecondaryConfirm.boxed_clone())
4626 .separator()
4627 .action_disabled_when(is_created, "View File History", Box::new(git::FileHistory))
4628 });
4629 self.selected_entry = Some(ix);
4630 self.set_context_menu(context_menu, position, window, cx);
4631 }
4632
4633 fn deploy_panel_context_menu(
4634 &mut self,
4635 position: Point<Pixels>,
4636 window: &mut Window,
4637 cx: &mut Context<Self>,
4638 ) {
4639 let context_menu = git_panel_context_menu(
4640 self.focus_handle.clone(),
4641 GitMenuState {
4642 has_tracked_changes: self.has_tracked_changes(),
4643 has_staged_changes: self.has_staged_changes(),
4644 has_unstaged_changes: self.has_unstaged_changes(),
4645 has_new_changes: self.new_count > 0,
4646 sort_by_path: GitPanelSettings::get_global(cx).sort_by_path,
4647 has_stash_items: self.stash_entries.entries.len() > 0,
4648 tree_view: GitPanelSettings::get_global(cx).tree_view,
4649 },
4650 window,
4651 cx,
4652 );
4653 self.set_context_menu(context_menu, position, window, cx);
4654 }
4655
4656 fn set_context_menu(
4657 &mut self,
4658 context_menu: Entity<ContextMenu>,
4659 position: Point<Pixels>,
4660 window: &Window,
4661 cx: &mut Context<Self>,
4662 ) {
4663 let subscription = cx.subscribe_in(
4664 &context_menu,
4665 window,
4666 |this, _, _: &DismissEvent, window, cx| {
4667 if this.context_menu.as_ref().is_some_and(|context_menu| {
4668 context_menu.0.focus_handle(cx).contains_focused(window, cx)
4669 }) {
4670 cx.focus_self(window);
4671 }
4672 this.context_menu.take();
4673 cx.notify();
4674 },
4675 );
4676 self.context_menu = Some((context_menu, position, subscription));
4677 cx.notify();
4678 }
4679
4680 fn render_status_entry(
4681 &self,
4682 ix: usize,
4683 entry: &GitStatusEntry,
4684 depth: usize,
4685 has_write_access: bool,
4686 window: &Window,
4687 cx: &Context<Self>,
4688 ) -> AnyElement {
4689 let tree_view = GitPanelSettings::get_global(cx).tree_view;
4690 let path_style = self.project.read(cx).path_style(cx);
4691 let git_path_style = ProjectSettings::get_global(cx).git.path_style;
4692 let display_name = entry.display_name(path_style);
4693
4694 let selected = self.selected_entry == Some(ix);
4695 let marked = self.marked_entries.contains(&ix);
4696 let status_style = GitPanelSettings::get_global(cx).status_style;
4697 let status = entry.status;
4698
4699 let has_conflict = status.is_conflicted();
4700 let is_modified = status.is_modified();
4701 let is_deleted = status.is_deleted();
4702
4703 let label_color = if status_style == StatusStyle::LabelColor {
4704 if has_conflict {
4705 Color::VersionControlConflict
4706 } else if is_modified {
4707 Color::VersionControlModified
4708 } else if is_deleted {
4709 // We don't want a bunch of red labels in the list
4710 Color::Disabled
4711 } else {
4712 Color::VersionControlAdded
4713 }
4714 } else {
4715 Color::Default
4716 };
4717
4718 let path_color = if status.is_deleted() {
4719 Color::Disabled
4720 } else {
4721 Color::Muted
4722 };
4723
4724 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
4725 let checkbox_wrapper_id: ElementId =
4726 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
4727 let checkbox_id: ElementId =
4728 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
4729
4730 let active_repo = self
4731 .project
4732 .read(cx)
4733 .active_repository(cx)
4734 .expect("active repository must be set");
4735 let repo = active_repo.read(cx);
4736 let is_staging_or_staged = self.is_entry_staged(entry, &repo);
4737 let mut is_staged: ToggleState = is_staging_or_staged.into();
4738 if self.show_placeholders && !self.has_staged_changes() && !entry.status.is_created() {
4739 is_staged = ToggleState::Selected;
4740 }
4741
4742 let handle = cx.weak_entity();
4743
4744 let selected_bg_alpha = 0.08;
4745 let marked_bg_alpha = 0.12;
4746 let state_opacity_step = 0.04;
4747
4748 let base_bg = match (selected, marked) {
4749 (true, true) => cx
4750 .theme()
4751 .status()
4752 .info
4753 .alpha(selected_bg_alpha + marked_bg_alpha),
4754 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
4755 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
4756 _ => cx.theme().colors().ghost_element_background,
4757 };
4758
4759 let hover_bg = if selected {
4760 cx.theme()
4761 .status()
4762 .info
4763 .alpha(selected_bg_alpha + state_opacity_step)
4764 } else {
4765 cx.theme().colors().ghost_element_hover
4766 };
4767
4768 let active_bg = if selected {
4769 cx.theme()
4770 .status()
4771 .info
4772 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4773 } else {
4774 cx.theme().colors().ghost_element_active
4775 };
4776
4777 let mut name_row = h_flex()
4778 .items_center()
4779 .gap_1()
4780 .flex_1()
4781 .pl(if tree_view {
4782 px(depth as f32 * TREE_INDENT)
4783 } else {
4784 px(0.)
4785 })
4786 .child(git_status_icon(status));
4787
4788 name_row = if tree_view {
4789 name_row.child(
4790 self.entry_label(display_name, label_color)
4791 .when(status.is_deleted(), Label::strikethrough)
4792 .truncate(),
4793 )
4794 } else {
4795 name_row.child(h_flex().items_center().flex_1().map(|this| {
4796 self.path_formatted(
4797 this,
4798 entry.parent_dir(path_style),
4799 path_color,
4800 display_name,
4801 label_color,
4802 path_style,
4803 git_path_style,
4804 status.is_deleted(),
4805 )
4806 }))
4807 };
4808
4809 h_flex()
4810 .id(id)
4811 .h(self.list_item_height())
4812 .w_full()
4813 .items_center()
4814 .border_1()
4815 .when(selected && self.focus_handle.is_focused(window), |el| {
4816 el.border_color(cx.theme().colors().panel_focused_border)
4817 })
4818 .px(rems(0.75)) // ~12px
4819 .overflow_hidden()
4820 .flex_none()
4821 .gap_1p5()
4822 .bg(base_bg)
4823 .hover(|this| this.bg(hover_bg))
4824 .active(|this| this.bg(active_bg))
4825 .on_click({
4826 cx.listener(move |this, event: &ClickEvent, window, cx| {
4827 this.selected_entry = Some(ix);
4828 cx.notify();
4829 if event.modifiers().secondary() {
4830 this.open_file(&Default::default(), window, cx)
4831 } else {
4832 this.open_diff(&Default::default(), window, cx);
4833 this.focus_handle.focus(window);
4834 }
4835 })
4836 })
4837 .on_mouse_down(
4838 MouseButton::Right,
4839 move |event: &MouseDownEvent, window, cx| {
4840 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
4841 if event.button != MouseButton::Right {
4842 return;
4843 }
4844
4845 let Some(this) = handle.upgrade() else {
4846 return;
4847 };
4848 this.update(cx, |this, cx| {
4849 this.deploy_entry_context_menu(event.position, ix, window, cx);
4850 });
4851 cx.stop_propagation();
4852 },
4853 )
4854 .child(name_row)
4855 .child(
4856 div()
4857 .id(checkbox_wrapper_id)
4858 .flex_none()
4859 .occlude()
4860 .cursor_pointer()
4861 .child(
4862 Checkbox::new(checkbox_id, is_staged)
4863 .disabled(!has_write_access)
4864 .fill()
4865 .elevation(ElevationIndex::Surface)
4866 .on_click_ext({
4867 let entry = entry.clone();
4868 let this = cx.weak_entity();
4869 move |_, click, window, cx| {
4870 this.update(cx, |this, cx| {
4871 if !has_write_access {
4872 return;
4873 }
4874 if click.modifiers().shift {
4875 this.stage_bulk(ix, cx);
4876 } else {
4877 let list_entry =
4878 if GitPanelSettings::get_global(cx).tree_view {
4879 GitListEntry::TreeStatus(GitTreeStatusEntry {
4880 entry: entry.clone(),
4881 depth,
4882 })
4883 } else {
4884 GitListEntry::Status(entry.clone())
4885 };
4886 this.toggle_staged_for_entry(&list_entry, window, cx);
4887 }
4888 cx.stop_propagation();
4889 })
4890 .ok();
4891 }
4892 })
4893 .tooltip(move |_window, cx| {
4894 // If is_staging_or_staged is None, this implies the file was partially staged, and so
4895 // we allow the user to stage it in full by displaying `Stage` in the tooltip.
4896 let action = if is_staging_or_staged {
4897 "Unstage"
4898 } else {
4899 "Stage"
4900 };
4901 let tooltip_name = action.to_string();
4902
4903 Tooltip::for_action(tooltip_name, &ToggleStaged, cx)
4904 }),
4905 ),
4906 )
4907 .into_any_element()
4908 }
4909
4910 fn render_directory_entry(
4911 &self,
4912 ix: usize,
4913 entry: &GitTreeDirEntry,
4914 has_write_access: bool,
4915 window: &Window,
4916 cx: &Context<Self>,
4917 ) -> AnyElement {
4918 // TODO: Have not yet plugin the self.marked_entries. Not sure when and why we need that
4919 let selected = self.selected_entry == Some(ix);
4920 let label_color = Color::Muted;
4921
4922 let id: ElementId = ElementId::Name(format!("dir_{}_{}", entry.name, ix).into());
4923 let checkbox_id: ElementId =
4924 ElementId::Name(format!("dir_checkbox_{}_{}", entry.name, ix).into());
4925 let checkbox_wrapper_id: ElementId =
4926 ElementId::Name(format!("dir_checkbox_wrapper_{}_{}", entry.name, ix).into());
4927
4928 let selected_bg_alpha = 0.08;
4929 let state_opacity_step = 0.04;
4930
4931 let base_bg = if selected {
4932 cx.theme().status().info.alpha(selected_bg_alpha)
4933 } else {
4934 cx.theme().colors().ghost_element_background
4935 };
4936
4937 let hover_bg = if selected {
4938 cx.theme()
4939 .status()
4940 .info
4941 .alpha(selected_bg_alpha + state_opacity_step)
4942 } else {
4943 cx.theme().colors().ghost_element_hover
4944 };
4945
4946 let active_bg = if selected {
4947 cx.theme()
4948 .status()
4949 .info
4950 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
4951 } else {
4952 cx.theme().colors().ghost_element_active
4953 };
4954 let folder_icon = if entry.expanded {
4955 IconName::FolderOpen
4956 } else {
4957 IconName::Folder
4958 };
4959 let staged_state = entry.staged_state;
4960
4961 let name_row = h_flex()
4962 .items_center()
4963 .gap_1()
4964 .flex_1()
4965 .pl(px(entry.depth as f32 * TREE_INDENT))
4966 .child(
4967 Icon::new(folder_icon)
4968 .size(IconSize::Small)
4969 .color(Color::Muted),
4970 )
4971 .child(self.entry_label(entry.name.clone(), label_color).truncate());
4972
4973 h_flex()
4974 .id(id)
4975 .h(self.list_item_height())
4976 .w_full()
4977 .items_center()
4978 .border_1()
4979 .when(selected && self.focus_handle.is_focused(window), |el| {
4980 el.border_color(cx.theme().colors().panel_focused_border)
4981 })
4982 .px(rems(0.75))
4983 .overflow_hidden()
4984 .flex_none()
4985 .gap_1p5()
4986 .bg(base_bg)
4987 .hover(|this| this.bg(hover_bg))
4988 .active(|this| this.bg(active_bg))
4989 .on_click({
4990 let key = entry.key.clone();
4991 cx.listener(move |this, _event: &ClickEvent, window, cx| {
4992 this.selected_entry = Some(ix);
4993 this.toggle_directory(&key, window, cx);
4994 })
4995 })
4996 .child(name_row)
4997 .child(
4998 div()
4999 .id(checkbox_wrapper_id)
5000 .flex_none()
5001 .occlude()
5002 .cursor_pointer()
5003 .child(
5004 Checkbox::new(checkbox_id, staged_state)
5005 .disabled(!has_write_access)
5006 .fill()
5007 .elevation(ElevationIndex::Surface)
5008 .on_click({
5009 let entry = entry.clone();
5010 let this = cx.weak_entity();
5011 move |_, window, cx| {
5012 this.update(cx, |this, cx| {
5013 if !has_write_access {
5014 return;
5015 }
5016 this.toggle_staged_for_entry(
5017 &GitListEntry::Directory(entry.clone()),
5018 window,
5019 cx,
5020 );
5021 cx.stop_propagation();
5022 })
5023 .ok();
5024 }
5025 })
5026 .tooltip(move |_window, cx| {
5027 let action = if staged_state.selected() {
5028 "Unstage"
5029 } else {
5030 "Stage"
5031 };
5032 Tooltip::simple(format!("{action} folder"), cx)
5033 }),
5034 ),
5035 )
5036 .into_any_element()
5037 }
5038
5039 fn path_formatted(
5040 &self,
5041 parent: Div,
5042 directory: Option<String>,
5043 path_color: Color,
5044 file_name: String,
5045 label_color: Color,
5046 path_style: PathStyle,
5047 git_path_style: GitPathStyle,
5048 strikethrough: bool,
5049 ) -> Div {
5050 parent
5051 .when(git_path_style == GitPathStyle::FileNameFirst, |this| {
5052 this.child(
5053 self.entry_label(
5054 match directory.as_ref().is_none_or(|d| d.is_empty()) {
5055 true => file_name.clone(),
5056 false => format!("{file_name} "),
5057 },
5058 label_color,
5059 )
5060 .when(strikethrough, Label::strikethrough),
5061 )
5062 })
5063 .when_some(directory, |this, dir| {
5064 match (
5065 !dir.is_empty(),
5066 git_path_style == GitPathStyle::FileNameFirst,
5067 ) {
5068 (true, true) => this.child(
5069 self.entry_label(dir, path_color)
5070 .when(strikethrough, Label::strikethrough),
5071 ),
5072 (true, false) => this.child(
5073 self.entry_label(
5074 format!("{dir}{}", path_style.primary_separator()),
5075 path_color,
5076 )
5077 .when(strikethrough, Label::strikethrough),
5078 ),
5079 _ => this,
5080 }
5081 })
5082 .when(git_path_style == GitPathStyle::FilePathFirst, |this| {
5083 this.child(
5084 self.entry_label(file_name, label_color)
5085 .when(strikethrough, Label::strikethrough),
5086 )
5087 })
5088 }
5089
5090 fn has_write_access(&self, cx: &App) -> bool {
5091 !self.project.read(cx).is_read_only(cx)
5092 }
5093
5094 pub fn amend_pending(&self) -> bool {
5095 self.amend_pending
5096 }
5097
5098 /// Sets the pending amend state, ensuring that the original commit message
5099 /// is either saved, when `value` is `true` and there's no pending amend, or
5100 /// restored, when `value` is `false` and there's a pending amend.
5101 pub fn set_amend_pending(&mut self, value: bool, cx: &mut Context<Self>) {
5102 if value && !self.amend_pending {
5103 let current_message = self.commit_message_buffer(cx).read(cx).text();
5104 self.original_commit_message = if current_message.trim().is_empty() {
5105 None
5106 } else {
5107 Some(current_message)
5108 };
5109 } else if !value && self.amend_pending {
5110 let message = self.original_commit_message.take().unwrap_or_default();
5111 self.commit_message_buffer(cx).update(cx, |buffer, cx| {
5112 let start = buffer.anchor_before(0);
5113 let end = buffer.anchor_after(buffer.len());
5114 buffer.edit([(start..end, message)], None, cx);
5115 });
5116 }
5117
5118 self.amend_pending = value;
5119 self.serialize(cx);
5120 cx.notify();
5121 }
5122
5123 pub fn signoff_enabled(&self) -> bool {
5124 self.signoff_enabled
5125 }
5126
5127 pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
5128 self.signoff_enabled = value;
5129 self.serialize(cx);
5130 cx.notify();
5131 }
5132
5133 pub fn toggle_signoff_enabled(
5134 &mut self,
5135 _: &Signoff,
5136 _window: &mut Window,
5137 cx: &mut Context<Self>,
5138 ) {
5139 self.set_signoff_enabled(!self.signoff_enabled, cx);
5140 }
5141
5142 pub async fn load(
5143 workspace: WeakEntity<Workspace>,
5144 mut cx: AsyncWindowContext,
5145 ) -> anyhow::Result<Entity<Self>> {
5146 let serialized_panel = match workspace
5147 .read_with(&cx, |workspace, _| Self::serialization_key(workspace))
5148 .ok()
5149 .flatten()
5150 {
5151 Some(serialization_key) => cx
5152 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
5153 .await
5154 .context("loading git panel")
5155 .log_err()
5156 .flatten()
5157 .map(|panel| serde_json::from_str::<SerializedGitPanel>(&panel))
5158 .transpose()
5159 .log_err()
5160 .flatten(),
5161 None => None,
5162 };
5163
5164 workspace.update_in(&mut cx, |workspace, window, cx| {
5165 let panel = GitPanel::new(workspace, window, cx);
5166
5167 if let Some(serialized_panel) = serialized_panel {
5168 panel.update(cx, |panel, cx| {
5169 panel.width = serialized_panel.width;
5170 panel.amend_pending = serialized_panel.amend_pending;
5171 panel.signoff_enabled = serialized_panel.signoff_enabled;
5172 cx.notify();
5173 })
5174 }
5175
5176 panel
5177 })
5178 }
5179
5180 fn stage_bulk(&mut self, mut index: usize, cx: &mut Context<'_, Self>) {
5181 let Some(op) = self.bulk_staging.as_ref() else {
5182 return;
5183 };
5184 let Some(mut anchor_index) = self.entry_by_path(&op.anchor) else {
5185 return;
5186 };
5187 if let Some(entry) = self.entries.get(index)
5188 && let Some(entry) = entry.status_entry()
5189 {
5190 self.set_bulk_staging_anchor(entry.repo_path.clone(), cx);
5191 }
5192 if index < anchor_index {
5193 std::mem::swap(&mut index, &mut anchor_index);
5194 }
5195 let entries = self
5196 .entries
5197 .get(anchor_index..=index)
5198 .unwrap_or_default()
5199 .iter()
5200 .filter_map(|entry| entry.status_entry().cloned())
5201 .collect::<Vec<_>>();
5202 self.change_file_stage(true, entries, cx);
5203 }
5204
5205 fn set_bulk_staging_anchor(&mut self, path: RepoPath, cx: &mut Context<'_, GitPanel>) {
5206 let Some(repo) = self.active_repository.as_ref() else {
5207 return;
5208 };
5209 self.bulk_staging = Some(BulkStaging {
5210 repo_id: repo.read(cx).id,
5211 anchor: path,
5212 });
5213 }
5214
5215 pub(crate) fn toggle_amend_pending(&mut self, cx: &mut Context<Self>) {
5216 self.set_amend_pending(!self.amend_pending, cx);
5217 if self.amend_pending {
5218 self.load_last_commit_message(cx);
5219 }
5220 }
5221}
5222
5223impl Render for GitPanel {
5224 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5225 let project = self.project.read(cx);
5226 let has_entries = !self.entries.is_empty();
5227 let room = self
5228 .workspace
5229 .upgrade()
5230 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
5231
5232 let has_write_access = self.has_write_access(cx);
5233
5234 let has_co_authors = room.is_some_and(|room| {
5235 self.load_local_committer(cx);
5236 let room = room.read(cx);
5237 room.remote_participants()
5238 .values()
5239 .any(|remote_participant| remote_participant.can_write())
5240 });
5241
5242 v_flex()
5243 .id("git_panel")
5244 .key_context(self.dispatch_context(window, cx))
5245 .track_focus(&self.focus_handle)
5246 .when(has_write_access && !project.is_read_only(cx), |this| {
5247 this.on_action(cx.listener(Self::toggle_staged_for_selected))
5248 .on_action(cx.listener(Self::stage_range))
5249 .on_action(cx.listener(GitPanel::on_commit))
5250 .on_action(cx.listener(GitPanel::on_amend))
5251 .on_action(cx.listener(GitPanel::toggle_signoff_enabled))
5252 .on_action(cx.listener(Self::stage_all))
5253 .on_action(cx.listener(Self::unstage_all))
5254 .on_action(cx.listener(Self::stage_selected))
5255 .on_action(cx.listener(Self::unstage_selected))
5256 .on_action(cx.listener(Self::restore_tracked_files))
5257 .on_action(cx.listener(Self::revert_selected))
5258 .on_action(cx.listener(Self::add_to_gitignore))
5259 .on_action(cx.listener(Self::clean_all))
5260 .on_action(cx.listener(Self::generate_commit_message_action))
5261 .on_action(cx.listener(Self::stash_all))
5262 .on_action(cx.listener(Self::stash_pop))
5263 })
5264 .on_action(cx.listener(Self::select_first))
5265 .on_action(cx.listener(Self::select_next))
5266 .on_action(cx.listener(Self::select_previous))
5267 .on_action(cx.listener(Self::select_last))
5268 .on_action(cx.listener(Self::close_panel))
5269 .on_action(cx.listener(Self::open_diff))
5270 .on_action(cx.listener(Self::open_file))
5271 .on_action(cx.listener(Self::file_history))
5272 .on_action(cx.listener(Self::focus_changes_list))
5273 .on_action(cx.listener(Self::focus_editor))
5274 .on_action(cx.listener(Self::expand_commit_editor))
5275 .when(has_write_access && has_co_authors, |git_panel| {
5276 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
5277 })
5278 .on_action(cx.listener(Self::toggle_sort_by_path))
5279 .on_action(cx.listener(Self::toggle_tree_view))
5280 .size_full()
5281 .overflow_hidden()
5282 .bg(cx.theme().colors().panel_background)
5283 .child(
5284 v_flex()
5285 .size_full()
5286 .children(self.render_panel_header(window, cx))
5287 .map(|this| {
5288 if has_entries {
5289 this.child(self.render_entries(has_write_access, window, cx))
5290 } else {
5291 this.child(self.render_empty_state(cx).into_any_element())
5292 }
5293 })
5294 .children(self.render_footer(window, cx))
5295 .when(self.amend_pending, |this| {
5296 this.child(self.render_pending_amend(cx))
5297 })
5298 .when(!self.amend_pending, |this| {
5299 this.children(self.render_previous_commit(cx))
5300 })
5301 .into_any_element(),
5302 )
5303 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
5304 deferred(
5305 anchored()
5306 .position(*position)
5307 .anchor(Corner::TopLeft)
5308 .child(menu.clone()),
5309 )
5310 .with_priority(1)
5311 }))
5312 }
5313}
5314
5315impl Focusable for GitPanel {
5316 fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
5317 if self.entries.is_empty() {
5318 self.commit_editor.focus_handle(cx)
5319 } else {
5320 self.focus_handle.clone()
5321 }
5322 }
5323}
5324
5325impl EventEmitter<Event> for GitPanel {}
5326
5327impl EventEmitter<PanelEvent> for GitPanel {}
5328
5329pub(crate) struct GitPanelAddon {
5330 pub(crate) workspace: WeakEntity<Workspace>,
5331}
5332
5333impl editor::Addon for GitPanelAddon {
5334 fn to_any(&self) -> &dyn std::any::Any {
5335 self
5336 }
5337
5338 fn render_buffer_header_controls(
5339 &self,
5340 excerpt_info: &ExcerptInfo,
5341 window: &Window,
5342 cx: &App,
5343 ) -> Option<AnyElement> {
5344 let file = excerpt_info.buffer.file()?;
5345 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
5346
5347 git_panel
5348 .read(cx)
5349 .render_buffer_header_controls(&git_panel, file, window, cx)
5350 }
5351}
5352
5353impl Panel for GitPanel {
5354 fn persistent_name() -> &'static str {
5355 "GitPanel"
5356 }
5357
5358 fn panel_key() -> &'static str {
5359 GIT_PANEL_KEY
5360 }
5361
5362 fn position(&self, _: &Window, cx: &App) -> DockPosition {
5363 GitPanelSettings::get_global(cx).dock
5364 }
5365
5366 fn position_is_valid(&self, position: DockPosition) -> bool {
5367 matches!(position, DockPosition::Left | DockPosition::Right)
5368 }
5369
5370 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
5371 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
5372 settings.git_panel.get_or_insert_default().dock = Some(position.into())
5373 });
5374 }
5375
5376 fn size(&self, _: &Window, cx: &App) -> Pixels {
5377 self.width
5378 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
5379 }
5380
5381 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
5382 self.width = size;
5383 self.serialize(cx);
5384 cx.notify();
5385 }
5386
5387 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
5388 Some(ui::IconName::GitBranchAlt).filter(|_| GitPanelSettings::get_global(cx).button)
5389 }
5390
5391 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
5392 Some("Git Panel")
5393 }
5394
5395 fn toggle_action(&self) -> Box<dyn Action> {
5396 Box::new(ToggleFocus)
5397 }
5398
5399 fn activation_priority(&self) -> u32 {
5400 2
5401 }
5402}
5403
5404impl PanelHeader for GitPanel {}
5405
5406struct GitPanelMessageTooltip {
5407 commit_tooltip: Option<Entity<CommitTooltip>>,
5408}
5409
5410impl GitPanelMessageTooltip {
5411 fn new(
5412 git_panel: Entity<GitPanel>,
5413 sha: SharedString,
5414 repository: Entity<Repository>,
5415 window: &mut Window,
5416 cx: &mut App,
5417 ) -> Entity<Self> {
5418 cx.new(|cx| {
5419 cx.spawn_in(window, async move |this, cx| {
5420 let (details, workspace) = git_panel.update(cx, |git_panel, cx| {
5421 (
5422 git_panel.load_commit_details(sha.to_string(), cx),
5423 git_panel.workspace.clone(),
5424 )
5425 })?;
5426 let details = details.await?;
5427
5428 let commit_details = crate::commit_tooltip::CommitDetails {
5429 sha: details.sha.clone(),
5430 author_name: details.author_name.clone(),
5431 author_email: details.author_email.clone(),
5432 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
5433 message: Some(ParsedCommitMessage {
5434 message: details.message,
5435 ..Default::default()
5436 }),
5437 };
5438
5439 this.update(cx, |this: &mut GitPanelMessageTooltip, cx| {
5440 this.commit_tooltip = Some(cx.new(move |cx| {
5441 CommitTooltip::new(commit_details, repository, workspace, cx)
5442 }));
5443 cx.notify();
5444 })
5445 })
5446 .detach();
5447
5448 Self {
5449 commit_tooltip: None,
5450 }
5451 })
5452 }
5453}
5454
5455impl Render for GitPanelMessageTooltip {
5456 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5457 if let Some(commit_tooltip) = &self.commit_tooltip {
5458 commit_tooltip.clone().into_any_element()
5459 } else {
5460 gpui::Empty.into_any_element()
5461 }
5462 }
5463}
5464
5465#[derive(IntoElement, RegisterComponent)]
5466pub struct PanelRepoFooter {
5467 active_repository: SharedString,
5468 branch: Option<Branch>,
5469 head_commit: Option<CommitDetails>,
5470
5471 // Getting a GitPanel in previews will be difficult.
5472 //
5473 // For now just take an option here, and we won't bind handlers to buttons in previews.
5474 git_panel: Option<Entity<GitPanel>>,
5475}
5476
5477impl PanelRepoFooter {
5478 pub fn new(
5479 active_repository: SharedString,
5480 branch: Option<Branch>,
5481 head_commit: Option<CommitDetails>,
5482 git_panel: Option<Entity<GitPanel>>,
5483 ) -> Self {
5484 Self {
5485 active_repository,
5486 branch,
5487 head_commit,
5488 git_panel,
5489 }
5490 }
5491
5492 pub fn new_preview(active_repository: SharedString, branch: Option<Branch>) -> Self {
5493 Self {
5494 active_repository,
5495 branch,
5496 head_commit: None,
5497 git_panel: None,
5498 }
5499 }
5500}
5501
5502impl RenderOnce for PanelRepoFooter {
5503 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
5504 let project = self
5505 .git_panel
5506 .as_ref()
5507 .map(|panel| panel.read(cx).project.clone());
5508
5509 let repo = self
5510 .git_panel
5511 .as_ref()
5512 .and_then(|panel| panel.read(cx).active_repository.clone());
5513
5514 let single_repo = project
5515 .as_ref()
5516 .map(|project| project.read(cx).git_store().read(cx).repositories().len() == 1)
5517 .unwrap_or(true);
5518
5519 const MAX_BRANCH_LEN: usize = 16;
5520 const MAX_REPO_LEN: usize = 16;
5521 const LABEL_CHARACTER_BUDGET: usize = MAX_BRANCH_LEN + MAX_REPO_LEN;
5522 const MAX_SHORT_SHA_LEN: usize = 8;
5523 let branch_name = self
5524 .branch
5525 .as_ref()
5526 .map(|branch| branch.name().to_owned())
5527 .or_else(|| {
5528 self.head_commit.as_ref().map(|commit| {
5529 commit
5530 .sha
5531 .chars()
5532 .take(MAX_SHORT_SHA_LEN)
5533 .collect::<String>()
5534 })
5535 })
5536 .unwrap_or_else(|| " (no branch)".to_owned());
5537 let show_separator = self.branch.is_some() || self.head_commit.is_some();
5538
5539 let active_repo_name = self.active_repository.clone();
5540
5541 let branch_actual_len = branch_name.len();
5542 let repo_actual_len = active_repo_name.len();
5543
5544 // ideally, show the whole branch and repo names but
5545 // when we can't, use a budget to allocate space between the two
5546 let (repo_display_len, branch_display_len) =
5547 if branch_actual_len + repo_actual_len <= LABEL_CHARACTER_BUDGET {
5548 (repo_actual_len, branch_actual_len)
5549 } else if branch_actual_len <= MAX_BRANCH_LEN {
5550 let repo_space = (LABEL_CHARACTER_BUDGET - branch_actual_len).min(MAX_REPO_LEN);
5551 (repo_space, branch_actual_len)
5552 } else if repo_actual_len <= MAX_REPO_LEN {
5553 let branch_space = (LABEL_CHARACTER_BUDGET - repo_actual_len).min(MAX_BRANCH_LEN);
5554 (repo_actual_len, branch_space)
5555 } else {
5556 (MAX_REPO_LEN, MAX_BRANCH_LEN)
5557 };
5558
5559 let truncated_repo_name = if repo_actual_len <= repo_display_len {
5560 active_repo_name.to_string()
5561 } else {
5562 util::truncate_and_trailoff(active_repo_name.trim_ascii(), repo_display_len)
5563 };
5564
5565 let truncated_branch_name = if branch_actual_len <= branch_display_len {
5566 branch_name
5567 } else {
5568 util::truncate_and_trailoff(branch_name.trim_ascii(), branch_display_len)
5569 };
5570
5571 let repo_selector_trigger = Button::new("repo-selector", truncated_repo_name)
5572 .size(ButtonSize::None)
5573 .label_size(LabelSize::Small)
5574 .color(Color::Muted);
5575
5576 let repo_selector = PopoverMenu::new("repository-switcher")
5577 .menu({
5578 let project = project;
5579 move |window, cx| {
5580 let project = project.clone()?;
5581 Some(cx.new(|cx| RepositorySelector::new(project, rems(16.), window, cx)))
5582 }
5583 })
5584 .trigger_with_tooltip(
5585 repo_selector_trigger.disabled(single_repo).truncate(true),
5586 Tooltip::text("Switch Active Repository"),
5587 )
5588 .anchor(Corner::BottomLeft)
5589 .into_any_element();
5590
5591 let branch_selector_button = Button::new("branch-selector", truncated_branch_name)
5592 .size(ButtonSize::None)
5593 .label_size(LabelSize::Small)
5594 .truncate(true)
5595 .on_click(|_, window, cx| {
5596 window.dispatch_action(zed_actions::git::Switch.boxed_clone(), cx);
5597 });
5598
5599 let branch_selector = PopoverMenu::new("popover-button")
5600 .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
5601 .trigger_with_tooltip(
5602 branch_selector_button,
5603 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Switch),
5604 )
5605 .anchor(Corner::BottomLeft)
5606 .offset(gpui::Point {
5607 x: px(0.0),
5608 y: px(-2.0),
5609 });
5610
5611 h_flex()
5612 .h(px(36.))
5613 .w_full()
5614 .px_2()
5615 .justify_between()
5616 .gap_1()
5617 .child(
5618 h_flex()
5619 .flex_1()
5620 .overflow_hidden()
5621 .gap_px()
5622 .child(
5623 Icon::new(IconName::GitBranchAlt)
5624 .size(IconSize::Small)
5625 .color(if single_repo {
5626 Color::Disabled
5627 } else {
5628 Color::Muted
5629 }),
5630 )
5631 .child(repo_selector)
5632 .when(show_separator, |this| {
5633 this.child(
5634 div()
5635 .text_sm()
5636 .text_color(cx.theme().colors().icon_muted.opacity(0.5))
5637 .child("/"),
5638 )
5639 })
5640 .child(branch_selector),
5641 )
5642 .children(if let Some(git_panel) = self.git_panel {
5643 git_panel.update(cx, |git_panel, cx| git_panel.render_remote_button(cx))
5644 } else {
5645 None
5646 })
5647 }
5648}
5649
5650impl Component for PanelRepoFooter {
5651 fn scope() -> ComponentScope {
5652 ComponentScope::VersionControl
5653 }
5654
5655 fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
5656 let unknown_upstream = None;
5657 let no_remote_upstream = Some(UpstreamTracking::Gone);
5658 let ahead_of_upstream = Some(
5659 UpstreamTrackingStatus {
5660 ahead: 2,
5661 behind: 0,
5662 }
5663 .into(),
5664 );
5665 let behind_upstream = Some(
5666 UpstreamTrackingStatus {
5667 ahead: 0,
5668 behind: 2,
5669 }
5670 .into(),
5671 );
5672 let ahead_and_behind_upstream = Some(
5673 UpstreamTrackingStatus {
5674 ahead: 3,
5675 behind: 1,
5676 }
5677 .into(),
5678 );
5679
5680 let not_ahead_or_behind_upstream = Some(
5681 UpstreamTrackingStatus {
5682 ahead: 0,
5683 behind: 0,
5684 }
5685 .into(),
5686 );
5687
5688 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
5689 Branch {
5690 is_head: true,
5691 ref_name: "some-branch".into(),
5692 upstream: upstream.map(|tracking| Upstream {
5693 ref_name: "origin/some-branch".into(),
5694 tracking,
5695 }),
5696 most_recent_commit: Some(CommitSummary {
5697 sha: "abc123".into(),
5698 subject: "Modify stuff".into(),
5699 commit_timestamp: 1710932954,
5700 author_name: "John Doe".into(),
5701 has_parent: true,
5702 }),
5703 }
5704 }
5705
5706 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
5707 Branch {
5708 is_head: true,
5709 ref_name: branch_name.to_string().into(),
5710 upstream: upstream.map(|tracking| Upstream {
5711 ref_name: format!("zed/{}", branch_name).into(),
5712 tracking,
5713 }),
5714 most_recent_commit: Some(CommitSummary {
5715 sha: "abc123".into(),
5716 subject: "Modify stuff".into(),
5717 commit_timestamp: 1710932954,
5718 author_name: "John Doe".into(),
5719 has_parent: true,
5720 }),
5721 }
5722 }
5723
5724 fn active_repository(id: usize) -> SharedString {
5725 format!("repo-{}", id).into()
5726 }
5727
5728 let example_width = px(340.);
5729 Some(
5730 v_flex()
5731 .gap_6()
5732 .w_full()
5733 .flex_none()
5734 .children(vec![
5735 example_group_with_title(
5736 "Action Button States",
5737 vec![
5738 single_example(
5739 "No Branch",
5740 div()
5741 .w(example_width)
5742 .overflow_hidden()
5743 .child(PanelRepoFooter::new_preview(active_repository(1), None))
5744 .into_any_element(),
5745 ),
5746 single_example(
5747 "Remote status unknown",
5748 div()
5749 .w(example_width)
5750 .overflow_hidden()
5751 .child(PanelRepoFooter::new_preview(
5752 active_repository(2),
5753 Some(branch(unknown_upstream)),
5754 ))
5755 .into_any_element(),
5756 ),
5757 single_example(
5758 "No Remote Upstream",
5759 div()
5760 .w(example_width)
5761 .overflow_hidden()
5762 .child(PanelRepoFooter::new_preview(
5763 active_repository(3),
5764 Some(branch(no_remote_upstream)),
5765 ))
5766 .into_any_element(),
5767 ),
5768 single_example(
5769 "Not Ahead or Behind",
5770 div()
5771 .w(example_width)
5772 .overflow_hidden()
5773 .child(PanelRepoFooter::new_preview(
5774 active_repository(4),
5775 Some(branch(not_ahead_or_behind_upstream)),
5776 ))
5777 .into_any_element(),
5778 ),
5779 single_example(
5780 "Behind remote",
5781 div()
5782 .w(example_width)
5783 .overflow_hidden()
5784 .child(PanelRepoFooter::new_preview(
5785 active_repository(5),
5786 Some(branch(behind_upstream)),
5787 ))
5788 .into_any_element(),
5789 ),
5790 single_example(
5791 "Ahead of remote",
5792 div()
5793 .w(example_width)
5794 .overflow_hidden()
5795 .child(PanelRepoFooter::new_preview(
5796 active_repository(6),
5797 Some(branch(ahead_of_upstream)),
5798 ))
5799 .into_any_element(),
5800 ),
5801 single_example(
5802 "Ahead and behind remote",
5803 div()
5804 .w(example_width)
5805 .overflow_hidden()
5806 .child(PanelRepoFooter::new_preview(
5807 active_repository(7),
5808 Some(branch(ahead_and_behind_upstream)),
5809 ))
5810 .into_any_element(),
5811 ),
5812 ],
5813 )
5814 .grow()
5815 .vertical(),
5816 ])
5817 .children(vec![
5818 example_group_with_title(
5819 "Labels",
5820 vec![
5821 single_example(
5822 "Short Branch & Repo",
5823 div()
5824 .w(example_width)
5825 .overflow_hidden()
5826 .child(PanelRepoFooter::new_preview(
5827 SharedString::from("zed"),
5828 Some(custom("main", behind_upstream)),
5829 ))
5830 .into_any_element(),
5831 ),
5832 single_example(
5833 "Long Branch",
5834 div()
5835 .w(example_width)
5836 .overflow_hidden()
5837 .child(PanelRepoFooter::new_preview(
5838 SharedString::from("zed"),
5839 Some(custom(
5840 "redesign-and-update-git-ui-list-entry-style",
5841 behind_upstream,
5842 )),
5843 ))
5844 .into_any_element(),
5845 ),
5846 single_example(
5847 "Long Repo",
5848 div()
5849 .w(example_width)
5850 .overflow_hidden()
5851 .child(PanelRepoFooter::new_preview(
5852 SharedString::from("zed-industries-community-examples"),
5853 Some(custom("gpui", ahead_of_upstream)),
5854 ))
5855 .into_any_element(),
5856 ),
5857 single_example(
5858 "Long Repo & Branch",
5859 div()
5860 .w(example_width)
5861 .overflow_hidden()
5862 .child(PanelRepoFooter::new_preview(
5863 SharedString::from("zed-industries-community-examples"),
5864 Some(custom(
5865 "redesign-and-update-git-ui-list-entry-style",
5866 behind_upstream,
5867 )),
5868 ))
5869 .into_any_element(),
5870 ),
5871 single_example(
5872 "Uppercase Repo",
5873 div()
5874 .w(example_width)
5875 .overflow_hidden()
5876 .child(PanelRepoFooter::new_preview(
5877 SharedString::from("LICENSES"),
5878 Some(custom("main", ahead_of_upstream)),
5879 ))
5880 .into_any_element(),
5881 ),
5882 single_example(
5883 "Uppercase Branch",
5884 div()
5885 .w(example_width)
5886 .overflow_hidden()
5887 .child(PanelRepoFooter::new_preview(
5888 SharedString::from("zed"),
5889 Some(custom("update-README", behind_upstream)),
5890 ))
5891 .into_any_element(),
5892 ),
5893 ],
5894 )
5895 .grow()
5896 .vertical(),
5897 ])
5898 .into_any_element(),
5899 )
5900 }
5901}
5902
5903fn open_output(
5904 operation: impl Into<SharedString>,
5905 workspace: &mut Workspace,
5906 output: &str,
5907 window: &mut Window,
5908 cx: &mut Context<Workspace>,
5909) {
5910 let operation = operation.into();
5911 let buffer = cx.new(|cx| Buffer::local(output, cx));
5912 buffer.update(cx, |buffer, cx| {
5913 buffer.set_capability(language::Capability::ReadOnly, cx);
5914 });
5915 let editor = cx.new(|cx| {
5916 let mut editor = Editor::for_buffer(buffer, None, window, cx);
5917 editor.buffer().update(cx, |buffer, cx| {
5918 buffer.set_title(format!("Output from git {operation}"), cx);
5919 });
5920 editor.set_read_only(true);
5921 editor
5922 });
5923
5924 workspace.add_item_to_center(Box::new(editor), window, cx);
5925}
5926
5927pub(crate) fn show_error_toast(
5928 workspace: Entity<Workspace>,
5929 action: impl Into<SharedString>,
5930 e: anyhow::Error,
5931 cx: &mut App,
5932) {
5933 let action = action.into();
5934 let message = e.to_string().trim().to_string();
5935 if message
5936 .matches(git::repository::REMOTE_CANCELLED_BY_USER)
5937 .next()
5938 .is_some()
5939 { // Hide the cancelled by user message
5940 } else {
5941 workspace.update(cx, |workspace, cx| {
5942 let workspace_weak = cx.weak_entity();
5943 let toast = StatusToast::new(format!("git {} failed", action), cx, |this, _cx| {
5944 this.icon(ToastIcon::new(IconName::XCircle).color(Color::Error))
5945 .action("View Log", move |window, cx| {
5946 let message = message.clone();
5947 let action = action.clone();
5948 workspace_weak
5949 .update(cx, move |workspace, cx| {
5950 open_output(action, workspace, &message, window, cx)
5951 })
5952 .ok();
5953 })
5954 });
5955 workspace.toggle_status_toast(toast, cx)
5956 });
5957 }
5958}
5959
5960#[cfg(test)]
5961mod tests {
5962 use git::{
5963 repository::repo_path,
5964 status::{StatusCode, UnmergedStatus, UnmergedStatusCode},
5965 };
5966 use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
5967 use indoc::indoc;
5968 use project::FakeFs;
5969 use serde_json::json;
5970 use settings::SettingsStore;
5971 use theme::LoadThemes;
5972 use util::path;
5973 use util::rel_path::rel_path;
5974
5975 use super::*;
5976
5977 fn init_test(cx: &mut gpui::TestAppContext) {
5978 zlog::init_test();
5979
5980 cx.update(|cx| {
5981 let settings_store = SettingsStore::test(cx);
5982 cx.set_global(settings_store);
5983 theme::init(LoadThemes::JustBase, cx);
5984 editor::init(cx);
5985 crate::init(cx);
5986 });
5987 }
5988
5989 #[gpui::test]
5990 async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
5991 init_test(cx);
5992 let fs = FakeFs::new(cx.background_executor.clone());
5993 fs.insert_tree(
5994 "/root",
5995 json!({
5996 "zed": {
5997 ".git": {},
5998 "crates": {
5999 "gpui": {
6000 "gpui.rs": "fn main() {}"
6001 },
6002 "util": {
6003 "util.rs": "fn do_it() {}"
6004 }
6005 }
6006 },
6007 }),
6008 )
6009 .await;
6010
6011 fs.set_status_for_repo(
6012 Path::new(path!("/root/zed/.git")),
6013 &[
6014 ("crates/gpui/gpui.rs", StatusCode::Modified.worktree()),
6015 ("crates/util/util.rs", StatusCode::Modified.worktree()),
6016 ],
6017 );
6018
6019 let project =
6020 Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
6021 let workspace =
6022 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6023 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6024
6025 cx.read(|cx| {
6026 project
6027 .read(cx)
6028 .worktrees(cx)
6029 .next()
6030 .unwrap()
6031 .read(cx)
6032 .as_local()
6033 .unwrap()
6034 .scan_complete()
6035 })
6036 .await;
6037
6038 cx.executor().run_until_parked();
6039
6040 let panel = workspace.update(cx, GitPanel::new).unwrap();
6041
6042 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6043 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6044 });
6045 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6046 handle.await;
6047
6048 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6049 pretty_assertions::assert_eq!(
6050 entries,
6051 [
6052 GitListEntry::Header(GitHeaderEntry {
6053 header: Section::Tracked
6054 }),
6055 GitListEntry::Status(GitStatusEntry {
6056 repo_path: repo_path("crates/gpui/gpui.rs"),
6057 status: StatusCode::Modified.worktree(),
6058 staging: StageStatus::Unstaged,
6059 }),
6060 GitListEntry::Status(GitStatusEntry {
6061 repo_path: repo_path("crates/util/util.rs"),
6062 status: StatusCode::Modified.worktree(),
6063 staging: StageStatus::Unstaged,
6064 },),
6065 ],
6066 );
6067
6068 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6069 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6070 });
6071 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6072 handle.await;
6073 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6074 pretty_assertions::assert_eq!(
6075 entries,
6076 [
6077 GitListEntry::Header(GitHeaderEntry {
6078 header: Section::Tracked
6079 }),
6080 GitListEntry::Status(GitStatusEntry {
6081 repo_path: repo_path("crates/gpui/gpui.rs"),
6082 status: StatusCode::Modified.worktree(),
6083 staging: StageStatus::Unstaged,
6084 }),
6085 GitListEntry::Status(GitStatusEntry {
6086 repo_path: repo_path("crates/util/util.rs"),
6087 status: StatusCode::Modified.worktree(),
6088 staging: StageStatus::Unstaged,
6089 },),
6090 ],
6091 );
6092 }
6093
6094 #[gpui::test]
6095 async fn test_bulk_staging(cx: &mut TestAppContext) {
6096 use GitListEntry::*;
6097
6098 init_test(cx);
6099 let fs = FakeFs::new(cx.background_executor.clone());
6100 fs.insert_tree(
6101 "/root",
6102 json!({
6103 "project": {
6104 ".git": {},
6105 "src": {
6106 "main.rs": "fn main() {}",
6107 "lib.rs": "pub fn hello() {}",
6108 "utils.rs": "pub fn util() {}"
6109 },
6110 "tests": {
6111 "test.rs": "fn test() {}"
6112 },
6113 "new_file.txt": "new content",
6114 "another_new.rs": "// new file",
6115 "conflict.txt": "conflicted content"
6116 }
6117 }),
6118 )
6119 .await;
6120
6121 fs.set_status_for_repo(
6122 Path::new(path!("/root/project/.git")),
6123 &[
6124 ("src/main.rs", StatusCode::Modified.worktree()),
6125 ("src/lib.rs", StatusCode::Modified.worktree()),
6126 ("tests/test.rs", StatusCode::Modified.worktree()),
6127 ("new_file.txt", FileStatus::Untracked),
6128 ("another_new.rs", FileStatus::Untracked),
6129 ("src/utils.rs", FileStatus::Untracked),
6130 (
6131 "conflict.txt",
6132 UnmergedStatus {
6133 first_head: UnmergedStatusCode::Updated,
6134 second_head: UnmergedStatusCode::Updated,
6135 }
6136 .into(),
6137 ),
6138 ],
6139 );
6140
6141 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6142 let workspace =
6143 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6144 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6145
6146 cx.read(|cx| {
6147 project
6148 .read(cx)
6149 .worktrees(cx)
6150 .next()
6151 .unwrap()
6152 .read(cx)
6153 .as_local()
6154 .unwrap()
6155 .scan_complete()
6156 })
6157 .await;
6158
6159 cx.executor().run_until_parked();
6160
6161 let panel = workspace.update(cx, GitPanel::new).unwrap();
6162
6163 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6164 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6165 });
6166 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6167 handle.await;
6168
6169 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6170 #[rustfmt::skip]
6171 pretty_assertions::assert_matches!(
6172 entries.as_slice(),
6173 &[
6174 Header(GitHeaderEntry { header: Section::Conflict }),
6175 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6176 Header(GitHeaderEntry { header: Section::Tracked }),
6177 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6178 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6179 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6180 Header(GitHeaderEntry { header: Section::New }),
6181 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6182 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6183 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6184 ],
6185 );
6186
6187 let second_status_entry = entries[3].clone();
6188 panel.update_in(cx, |panel, window, cx| {
6189 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6190 });
6191
6192 panel.update_in(cx, |panel, window, cx| {
6193 panel.selected_entry = Some(7);
6194 panel.stage_range(&git::StageRange, window, cx);
6195 });
6196
6197 cx.read(|cx| {
6198 project
6199 .read(cx)
6200 .worktrees(cx)
6201 .next()
6202 .unwrap()
6203 .read(cx)
6204 .as_local()
6205 .unwrap()
6206 .scan_complete()
6207 })
6208 .await;
6209
6210 cx.executor().run_until_parked();
6211
6212 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6213 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6214 });
6215 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6216 handle.await;
6217
6218 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6219 #[rustfmt::skip]
6220 pretty_assertions::assert_matches!(
6221 entries.as_slice(),
6222 &[
6223 Header(GitHeaderEntry { header: Section::Conflict }),
6224 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6225 Header(GitHeaderEntry { header: Section::Tracked }),
6226 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6227 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6228 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6229 Header(GitHeaderEntry { header: Section::New }),
6230 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6231 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6232 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6233 ],
6234 );
6235
6236 let third_status_entry = entries[4].clone();
6237 panel.update_in(cx, |panel, window, cx| {
6238 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6239 });
6240
6241 panel.update_in(cx, |panel, window, cx| {
6242 panel.selected_entry = Some(9);
6243 panel.stage_range(&git::StageRange, window, cx);
6244 });
6245
6246 cx.read(|cx| {
6247 project
6248 .read(cx)
6249 .worktrees(cx)
6250 .next()
6251 .unwrap()
6252 .read(cx)
6253 .as_local()
6254 .unwrap()
6255 .scan_complete()
6256 })
6257 .await;
6258
6259 cx.executor().run_until_parked();
6260
6261 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6262 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6263 });
6264 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6265 handle.await;
6266
6267 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6268 #[rustfmt::skip]
6269 pretty_assertions::assert_matches!(
6270 entries.as_slice(),
6271 &[
6272 Header(GitHeaderEntry { header: Section::Conflict }),
6273 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6274 Header(GitHeaderEntry { header: Section::Tracked }),
6275 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6276 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6277 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6278 Header(GitHeaderEntry { header: Section::New }),
6279 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6280 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6281 Status(GitStatusEntry { staging: StageStatus::Staged, .. }),
6282 ],
6283 );
6284 }
6285
6286 #[gpui::test]
6287 async fn test_bulk_staging_with_sort_by_paths(cx: &mut TestAppContext) {
6288 use GitListEntry::*;
6289
6290 init_test(cx);
6291 let fs = FakeFs::new(cx.background_executor.clone());
6292 fs.insert_tree(
6293 "/root",
6294 json!({
6295 "project": {
6296 ".git": {},
6297 "src": {
6298 "main.rs": "fn main() {}",
6299 "lib.rs": "pub fn hello() {}",
6300 "utils.rs": "pub fn util() {}"
6301 },
6302 "tests": {
6303 "test.rs": "fn test() {}"
6304 },
6305 "new_file.txt": "new content",
6306 "another_new.rs": "// new file",
6307 "conflict.txt": "conflicted content"
6308 }
6309 }),
6310 )
6311 .await;
6312
6313 fs.set_status_for_repo(
6314 Path::new(path!("/root/project/.git")),
6315 &[
6316 ("src/main.rs", StatusCode::Modified.worktree()),
6317 ("src/lib.rs", StatusCode::Modified.worktree()),
6318 ("tests/test.rs", StatusCode::Modified.worktree()),
6319 ("new_file.txt", FileStatus::Untracked),
6320 ("another_new.rs", FileStatus::Untracked),
6321 ("src/utils.rs", FileStatus::Untracked),
6322 (
6323 "conflict.txt",
6324 UnmergedStatus {
6325 first_head: UnmergedStatusCode::Updated,
6326 second_head: UnmergedStatusCode::Updated,
6327 }
6328 .into(),
6329 ),
6330 ],
6331 );
6332
6333 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6334 let workspace =
6335 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6336 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6337
6338 cx.read(|cx| {
6339 project
6340 .read(cx)
6341 .worktrees(cx)
6342 .next()
6343 .unwrap()
6344 .read(cx)
6345 .as_local()
6346 .unwrap()
6347 .scan_complete()
6348 })
6349 .await;
6350
6351 cx.executor().run_until_parked();
6352
6353 let panel = workspace.update(cx, GitPanel::new).unwrap();
6354
6355 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6356 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6357 });
6358 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6359 handle.await;
6360
6361 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6362 #[rustfmt::skip]
6363 pretty_assertions::assert_matches!(
6364 entries.as_slice(),
6365 &[
6366 Header(GitHeaderEntry { header: Section::Conflict }),
6367 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6368 Header(GitHeaderEntry { header: Section::Tracked }),
6369 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6370 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6371 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6372 Header(GitHeaderEntry { header: Section::New }),
6373 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6374 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6375 Status(GitStatusEntry { staging: StageStatus::Unstaged, .. }),
6376 ],
6377 );
6378
6379 assert_entry_paths(
6380 &entries,
6381 &[
6382 None,
6383 Some("conflict.txt"),
6384 None,
6385 Some("src/lib.rs"),
6386 Some("src/main.rs"),
6387 Some("tests/test.rs"),
6388 None,
6389 Some("another_new.rs"),
6390 Some("new_file.txt"),
6391 Some("src/utils.rs"),
6392 ],
6393 );
6394
6395 let second_status_entry = entries[3].clone();
6396 panel.update_in(cx, |panel, window, cx| {
6397 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6398 });
6399
6400 cx.update(|_window, cx| {
6401 SettingsStore::update_global(cx, |store, cx| {
6402 store.update_user_settings(cx, |settings| {
6403 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6404 })
6405 });
6406 });
6407
6408 panel.update_in(cx, |panel, window, cx| {
6409 panel.selected_entry = Some(7);
6410 panel.stage_range(&git::StageRange, window, cx);
6411 });
6412
6413 cx.read(|cx| {
6414 project
6415 .read(cx)
6416 .worktrees(cx)
6417 .next()
6418 .unwrap()
6419 .read(cx)
6420 .as_local()
6421 .unwrap()
6422 .scan_complete()
6423 })
6424 .await;
6425
6426 cx.executor().run_until_parked();
6427
6428 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6429 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6430 });
6431 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6432 handle.await;
6433
6434 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6435 #[rustfmt::skip]
6436 pretty_assertions::assert_matches!(
6437 entries.as_slice(),
6438 &[
6439 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6440 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6441 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6442 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6443 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6444 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6445 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6446 ],
6447 );
6448
6449 assert_entry_paths(
6450 &entries,
6451 &[
6452 Some("another_new.rs"),
6453 Some("conflict.txt"),
6454 Some("new_file.txt"),
6455 Some("src/lib.rs"),
6456 Some("src/main.rs"),
6457 Some("src/utils.rs"),
6458 Some("tests/test.rs"),
6459 ],
6460 );
6461
6462 let third_status_entry = entries[4].clone();
6463 panel.update_in(cx, |panel, window, cx| {
6464 panel.toggle_staged_for_entry(&third_status_entry, window, cx);
6465 });
6466
6467 panel.update_in(cx, |panel, window, cx| {
6468 panel.selected_entry = Some(9);
6469 panel.stage_range(&git::StageRange, window, cx);
6470 });
6471
6472 cx.read(|cx| {
6473 project
6474 .read(cx)
6475 .worktrees(cx)
6476 .next()
6477 .unwrap()
6478 .read(cx)
6479 .as_local()
6480 .unwrap()
6481 .scan_complete()
6482 })
6483 .await;
6484
6485 cx.executor().run_until_parked();
6486
6487 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6488 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6489 });
6490 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6491 handle.await;
6492
6493 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6494 #[rustfmt::skip]
6495 pretty_assertions::assert_matches!(
6496 entries.as_slice(),
6497 &[
6498 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6499 Status(GitStatusEntry { status: FileStatus::Unmerged(..), staging: StageStatus::Unstaged, .. }),
6500 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6501 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6502 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Staged, .. }),
6503 Status(GitStatusEntry { status: FileStatus::Untracked, staging: StageStatus::Unstaged, .. }),
6504 Status(GitStatusEntry { status: FileStatus::Tracked(..), staging: StageStatus::Unstaged, .. }),
6505 ],
6506 );
6507
6508 assert_entry_paths(
6509 &entries,
6510 &[
6511 Some("another_new.rs"),
6512 Some("conflict.txt"),
6513 Some("new_file.txt"),
6514 Some("src/lib.rs"),
6515 Some("src/main.rs"),
6516 Some("src/utils.rs"),
6517 Some("tests/test.rs"),
6518 ],
6519 );
6520 }
6521
6522 #[gpui::test]
6523 async fn test_amend_commit_message_handling(cx: &mut TestAppContext) {
6524 init_test(cx);
6525 let fs = FakeFs::new(cx.background_executor.clone());
6526 fs.insert_tree(
6527 "/root",
6528 json!({
6529 "project": {
6530 ".git": {},
6531 "src": {
6532 "main.rs": "fn main() {}"
6533 }
6534 }
6535 }),
6536 )
6537 .await;
6538
6539 fs.set_status_for_repo(
6540 Path::new(path!("/root/project/.git")),
6541 &[("src/main.rs", StatusCode::Modified.worktree())],
6542 );
6543
6544 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6545 let workspace =
6546 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6547 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6548
6549 let panel = workspace.update(cx, GitPanel::new).unwrap();
6550
6551 // Test: User has commit message, enables amend (saves message), then disables (restores message)
6552 panel.update(cx, |panel, cx| {
6553 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6554 let start = buffer.anchor_before(0);
6555 let end = buffer.anchor_after(buffer.len());
6556 buffer.edit([(start..end, "Initial commit message")], None, cx);
6557 });
6558
6559 panel.set_amend_pending(true, cx);
6560 assert!(panel.original_commit_message.is_some());
6561
6562 panel.set_amend_pending(false, cx);
6563 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6564 assert_eq!(current_message, "Initial commit message");
6565 assert!(panel.original_commit_message.is_none());
6566 });
6567
6568 // Test: User has empty commit message, enables amend, then disables (clears message)
6569 panel.update(cx, |panel, cx| {
6570 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6571 let start = buffer.anchor_before(0);
6572 let end = buffer.anchor_after(buffer.len());
6573 buffer.edit([(start..end, "")], None, cx);
6574 });
6575
6576 panel.set_amend_pending(true, cx);
6577 assert!(panel.original_commit_message.is_none());
6578
6579 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6580 let start = buffer.anchor_before(0);
6581 let end = buffer.anchor_after(buffer.len());
6582 buffer.edit([(start..end, "Previous commit message")], None, cx);
6583 });
6584
6585 panel.set_amend_pending(false, cx);
6586 let current_message = panel.commit_message_buffer(cx).read(cx).text();
6587 assert_eq!(current_message, "");
6588 });
6589 }
6590
6591 #[gpui::test]
6592 async fn test_amend(cx: &mut TestAppContext) {
6593 init_test(cx);
6594 let fs = FakeFs::new(cx.background_executor.clone());
6595 fs.insert_tree(
6596 "/root",
6597 json!({
6598 "project": {
6599 ".git": {},
6600 "src": {
6601 "main.rs": "fn main() {}"
6602 }
6603 }
6604 }),
6605 )
6606 .await;
6607
6608 fs.set_status_for_repo(
6609 Path::new(path!("/root/project/.git")),
6610 &[("src/main.rs", StatusCode::Modified.worktree())],
6611 );
6612
6613 let project = Project::test(fs.clone(), [Path::new(path!("/root/project"))], cx).await;
6614 let workspace =
6615 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6616 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6617
6618 // Wait for the project scanning to finish so that `head_commit(cx)` is
6619 // actually set, otherwise no head commit would be available from which
6620 // to fetch the latest commit message from.
6621 cx.executor().run_until_parked();
6622
6623 let panel = workspace.update(cx, GitPanel::new).unwrap();
6624 panel.read_with(cx, |panel, cx| {
6625 assert!(panel.active_repository.is_some());
6626 assert!(panel.head_commit(cx).is_some());
6627 });
6628
6629 panel.update_in(cx, |panel, window, cx| {
6630 // Update the commit editor's message to ensure that its contents
6631 // are later restored, after amending is finished.
6632 panel.commit_message_buffer(cx).update(cx, |buffer, cx| {
6633 buffer.set_text("refactor: update main.rs", cx);
6634 });
6635
6636 // Start amending the previous commit.
6637 panel.focus_editor(&Default::default(), window, cx);
6638 panel.on_amend(&Amend, window, cx);
6639 });
6640
6641 // Since `GitPanel.amend` attempts to fetch the latest commit message in
6642 // a background task, we need to wait for it to complete before being
6643 // able to assert that the commit message editor's state has been
6644 // updated.
6645 cx.run_until_parked();
6646
6647 panel.update_in(cx, |panel, window, cx| {
6648 assert_eq!(
6649 panel.commit_message_buffer(cx).read(cx).text(),
6650 "initial commit"
6651 );
6652 assert_eq!(
6653 panel.original_commit_message,
6654 Some("refactor: update main.rs".to_string())
6655 );
6656
6657 // Finish amending the previous commit.
6658 panel.focus_editor(&Default::default(), window, cx);
6659 panel.on_amend(&Amend, window, cx);
6660 });
6661
6662 // Since the actual commit logic is run in a background task, we need to
6663 // await its completion to actually ensure that the commit message
6664 // editor's contents are set to the original message and haven't been
6665 // cleared.
6666 cx.run_until_parked();
6667
6668 panel.update_in(cx, |panel, _window, cx| {
6669 // After amending, the commit editor's message should be restored to
6670 // the original message.
6671 assert_eq!(
6672 panel.commit_message_buffer(cx).read(cx).text(),
6673 "refactor: update main.rs"
6674 );
6675 assert!(panel.original_commit_message.is_none());
6676 });
6677 }
6678
6679 #[gpui::test]
6680 async fn test_open_diff(cx: &mut TestAppContext) {
6681 init_test(cx);
6682
6683 let fs = FakeFs::new(cx.background_executor.clone());
6684 fs.insert_tree(
6685 path!("/project"),
6686 json!({
6687 ".git": {},
6688 "tracked": "tracked\n",
6689 "untracked": "\n",
6690 }),
6691 )
6692 .await;
6693
6694 fs.set_head_and_index_for_repo(
6695 path!("/project/.git").as_ref(),
6696 &[("tracked", "old tracked\n".into())],
6697 );
6698
6699 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
6700 let workspace =
6701 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6702 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6703 let panel = workspace.update(cx, GitPanel::new).unwrap();
6704
6705 // Enable the `sort_by_path` setting and wait for entries to be updated,
6706 // as there should no longer be separators between Tracked and Untracked
6707 // files.
6708 cx.update(|_window, cx| {
6709 SettingsStore::update_global(cx, |store, cx| {
6710 store.update_user_settings(cx, |settings| {
6711 settings.git_panel.get_or_insert_default().sort_by_path = Some(true);
6712 })
6713 });
6714 });
6715
6716 cx.update_window_entity(&panel, |panel, _, _| {
6717 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6718 })
6719 .await;
6720
6721 // Confirm that `Open Diff` still works for the untracked file, updating
6722 // the Project Diff's active path.
6723 panel.update_in(cx, |panel, window, cx| {
6724 panel.selected_entry = Some(1);
6725 panel.open_diff(&Confirm, window, cx);
6726 });
6727 cx.run_until_parked();
6728
6729 let _ = workspace.update(cx, |workspace, _window, cx| {
6730 let active_path = workspace
6731 .item_of_type::<ProjectDiff>(cx)
6732 .expect("ProjectDiff should exist")
6733 .read(cx)
6734 .active_path(cx)
6735 .expect("active_path should exist");
6736
6737 assert_eq!(active_path.path, rel_path("untracked").into_arc());
6738 });
6739 }
6740
6741 fn assert_entry_paths(entries: &[GitListEntry], expected_paths: &[Option<&str>]) {
6742 assert_eq!(entries.len(), expected_paths.len());
6743 for (entry, expected_path) in entries.iter().zip(expected_paths) {
6744 assert_eq!(
6745 entry.status_entry().map(|status| status
6746 .repo_path
6747 .as_ref()
6748 .as_std_path()
6749 .to_string_lossy()
6750 .to_string()),
6751 expected_path.map(|s| s.to_string())
6752 );
6753 }
6754 }
6755
6756 #[test]
6757 fn test_compress_diff_no_truncation() {
6758 let diff = indoc! {"
6759 --- a/file.txt
6760 +++ b/file.txt
6761 @@ -1,2 +1,2 @@
6762 -old
6763 +new
6764 "};
6765 let result = GitPanel::compress_commit_diff(diff, 1000);
6766 assert_eq!(result, diff);
6767 }
6768
6769 #[test]
6770 fn test_compress_diff_truncate_long_lines() {
6771 let long_line = "🦀".repeat(300);
6772 let diff = indoc::formatdoc! {"
6773 --- a/file.txt
6774 +++ b/file.txt
6775 @@ -1,2 +1,3 @@
6776 context
6777 +{}
6778 more context
6779 ", long_line};
6780 let result = GitPanel::compress_commit_diff(&diff, 100);
6781 assert!(result.contains("...[truncated]"));
6782 assert!(result.len() < diff.len());
6783 }
6784
6785 #[test]
6786 fn test_compress_diff_truncate_hunks() {
6787 let diff = indoc! {"
6788 --- a/file.txt
6789 +++ b/file.txt
6790 @@ -1,2 +1,2 @@
6791 context
6792 -old1
6793 +new1
6794 @@ -5,2 +5,2 @@
6795 context 2
6796 -old2
6797 +new2
6798 @@ -10,2 +10,2 @@
6799 context 3
6800 -old3
6801 +new3
6802 "};
6803 let result = GitPanel::compress_commit_diff(diff, 100);
6804 let expected = indoc! {"
6805 --- a/file.txt
6806 +++ b/file.txt
6807 @@ -1,2 +1,2 @@
6808 context
6809 -old1
6810 +new1
6811 [...skipped 2 hunks...]
6812 "};
6813 assert_eq!(result, expected);
6814 }
6815
6816 #[gpui::test]
6817 async fn test_suggest_commit_message(cx: &mut TestAppContext) {
6818 init_test(cx);
6819
6820 let fs = FakeFs::new(cx.background_executor.clone());
6821 fs.insert_tree(
6822 path!("/project"),
6823 json!({
6824 ".git": {},
6825 "tracked": "tracked\n",
6826 "untracked": "\n",
6827 }),
6828 )
6829 .await;
6830
6831 fs.set_head_and_index_for_repo(
6832 path!("/project/.git").as_ref(),
6833 &[("tracked", "old tracked\n".into())],
6834 );
6835
6836 let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
6837 let workspace =
6838 cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
6839 let cx = &mut VisualTestContext::from_window(*workspace, cx);
6840 let panel = workspace.update(cx, GitPanel::new).unwrap();
6841
6842 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6843 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6844 });
6845 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6846 handle.await;
6847
6848 let entries = panel.read_with(cx, |panel, _| panel.entries.clone());
6849
6850 // GitPanel
6851 // - Tracked:
6852 // - [] tracked
6853 // - Untracked
6854 // - [] untracked
6855 //
6856 // The commit message should now read:
6857 // "Update tracked"
6858 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6859 assert_eq!(message, Some("Update tracked".to_string()));
6860
6861 let first_status_entry = entries[1].clone();
6862 panel.update_in(cx, |panel, window, cx| {
6863 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
6864 });
6865
6866 cx.read(|cx| {
6867 project
6868 .read(cx)
6869 .worktrees(cx)
6870 .next()
6871 .unwrap()
6872 .read(cx)
6873 .as_local()
6874 .unwrap()
6875 .scan_complete()
6876 })
6877 .await;
6878
6879 cx.executor().run_until_parked();
6880
6881 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6882 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6883 });
6884 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6885 handle.await;
6886
6887 // GitPanel
6888 // - Tracked:
6889 // - [x] tracked
6890 // - Untracked
6891 // - [] untracked
6892 //
6893 // The commit message should still read:
6894 // "Update tracked"
6895 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6896 assert_eq!(message, Some("Update tracked".to_string()));
6897
6898 let second_status_entry = entries[3].clone();
6899 panel.update_in(cx, |panel, window, cx| {
6900 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6901 });
6902
6903 cx.read(|cx| {
6904 project
6905 .read(cx)
6906 .worktrees(cx)
6907 .next()
6908 .unwrap()
6909 .read(cx)
6910 .as_local()
6911 .unwrap()
6912 .scan_complete()
6913 })
6914 .await;
6915
6916 cx.executor().run_until_parked();
6917
6918 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6919 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6920 });
6921 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6922 handle.await;
6923
6924 // GitPanel
6925 // - Tracked:
6926 // - [x] tracked
6927 // - Untracked
6928 // - [x] untracked
6929 //
6930 // The commit message should now read:
6931 // "Enter commit message"
6932 // (which means we should see None returned).
6933 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6934 assert!(message.is_none());
6935
6936 panel.update_in(cx, |panel, window, cx| {
6937 panel.toggle_staged_for_entry(&first_status_entry, window, cx);
6938 });
6939
6940 cx.read(|cx| {
6941 project
6942 .read(cx)
6943 .worktrees(cx)
6944 .next()
6945 .unwrap()
6946 .read(cx)
6947 .as_local()
6948 .unwrap()
6949 .scan_complete()
6950 })
6951 .await;
6952
6953 cx.executor().run_until_parked();
6954
6955 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6956 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6957 });
6958 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6959 handle.await;
6960
6961 // GitPanel
6962 // - Tracked:
6963 // - [] tracked
6964 // - Untracked
6965 // - [x] untracked
6966 //
6967 // The commit message should now read:
6968 // "Update untracked"
6969 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
6970 assert_eq!(message, Some("Create untracked".to_string()));
6971
6972 panel.update_in(cx, |panel, window, cx| {
6973 panel.toggle_staged_for_entry(&second_status_entry, window, cx);
6974 });
6975
6976 cx.read(|cx| {
6977 project
6978 .read(cx)
6979 .worktrees(cx)
6980 .next()
6981 .unwrap()
6982 .read(cx)
6983 .as_local()
6984 .unwrap()
6985 .scan_complete()
6986 })
6987 .await;
6988
6989 cx.executor().run_until_parked();
6990
6991 let handle = cx.update_window_entity(&panel, |panel, _, _| {
6992 std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
6993 });
6994 cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
6995 handle.await;
6996
6997 // GitPanel
6998 // - Tracked:
6999 // - [] tracked
7000 // - Untracked
7001 // - [] untracked
7002 //
7003 // The commit message should now read:
7004 // "Update tracked"
7005 let message = panel.update(cx, |panel, cx| panel.suggest_commit_message(cx));
7006 assert_eq!(message, Some("Update tracked".to_string()));
7007 }
7008}