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