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