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