Skip to main content

grit_lib/porcelain/
stash.rs

1//! Stash option and result types plus the Git-compatible stash engine.
2//!
3//! The library builds Git-compatible stash commits (W/I/U parents), updates
4//! `refs/stash` and its reflog, and applies entries onto the worktree and index.
5//! The operations are reached through
6//! [`RepositoryStash`](crate::repo_handles::RepositoryStash) (`repo.stash()`); apply and
7//! pop report the paths left conflicted, with their kinds, in a [`StashApplyOutcome`] (a pop keeps the entry
8//! when there are any).
9//!
10//! Flattening and worktree helpers ([`FlatTreeEntry`], [`flatten_tree_full`],
11//! [`add_stage_entry`], [`worktree_bytes_for_index_mode`],
12//! [`write_regular_file_replacing_symlink`], [`remove_empty_dirs`]) are shared
13//! building blocks for apply and for embedders that manipulate stash trees.
14
15use crate::error::RefError;
16use crate::worktree::WorktreeError;
17use std::collections::{BTreeMap, BTreeSet, HashSet};
18use std::fs;
19use std::io;
20use std::path::Path;
21
22use crate::diff::{
23    build_file_diffs, diff_index_to_tree, diff_index_to_worktree_with_options, diff_trees,
24    sort_entries_by_path, zero_oid, DiffDetail, DiffEntry, DiffIndexToWorktreeOptions, DiffOptions,
25    DiffStat, DiffStatus, FileStat,
26};
27use crate::error::{ApplyError, Error, Result};
28use crate::index::{
29    index_file_mtime, Index, IndexEntry, IndexLock, MODE_GITLINK, MODE_SYMLINK, MODE_TREE,
30};
31use crate::objects::FileMode;
32use crate::porcelain::stash_error::{CorruptStashReason, StashError, StashPushValidationError};
33use crate::worktree::{map_worktree_io, WorktreePathOperation};
34// `MODE_EXECUTABLE` only drives the Unix executable-bit application below.
35use crate::apply::{apply_patch_to_index, IndexApplyOptions};
36use crate::check_ref_format::{RefName, RefNameRef};
37use crate::diff::HunkId;
38use crate::ident::Signature;
39#[cfg(unix)]
40use crate::index::MODE_EXECUTABLE;
41use crate::merge_file::MergeFavor;
42use crate::merge_trees::{
43    merge_trees_three_way, DirectoryRenameMode, TreeMergeConflictPresentation,
44    WhitespaceMergeOptions,
45};
46use crate::objects::{parse_tree, CommitData, ObjectId, ObjectKind};
47use crate::odb::Odb;
48use crate::operation::{conflicts_from_index, Conflict};
49use crate::pathspec::{has_glob_chars, pathspec_is_exclude};
50use crate::porcelain::add::restricted_index_paths_for_pathspecs;
51use crate::porcelain::branch_error::BranchError;
52use crate::porcelain::checkout::is_eligible_for_parallel_checkout;
53use crate::porcelain::checkout::smudge_bytes_for_worktree_path;
54use crate::porcelain::checkout::{
55    checkout_between_trees_locked, checkout_tree_changes_into_deferred_journal, CheckoutIndexWrite,
56    CheckoutJournal,
57};
58use crate::porcelain::clean::{is_nested_git_worktree, path_in_nested_git_worktree};
59use crate::porcelain::commit::write_commit_object;
60use crate::porcelain::hunk_select::{
61    resolve_unstaged_selection, reverse_apply_patches_to_worktree, HunkSelection,
62    ResolvedSelection, WorktreeReverseApplyOptions,
63};
64use crate::porcelain::index_from_tree::{
65    index_from_tree_with_seeded_stats, index_from_tree_with_seeded_worktree_stats,
66    index_from_tree_with_worktree_stats,
67};
68use crate::porcelain::pathspec_match::{
69    diff_entry_path_mode, index_stage0_mode_or_regular, pathspec_entries_from_paths,
70    positive_pathspec_matches_any_path, positive_spec_matches_any_entries, PathspecMatchEntry,
71    RepositoryPathspecFilter, REGULAR_FILE_MODE,
72};
73use crate::porcelain::restore::{restore_paths_with_lock, RestoreOptions, RestoreSource};
74use crate::porcelain::status::{
75    collect_untracked_and_ignored_inner, IgnoredMode, UntrackedCacheMissAction, UntrackedScan,
76};
77use crate::porcelain::switch::{switch_repository, SwitchMode, SwitchOptions};
78use crate::progress::{
79    poll_cancel, CancelToken, NullProgress, ProgressPhase, ProgressScope, ProgressSink,
80};
81
82fn poll_stash(scope: &mut ProgressScope<'_>) -> crate::error::Result<()> {
83    scope.poll()
84}
85use crate::reflog::{delete_reflog_entries_rechain_on_store, read_reflog_on_store};
86use crate::refs::{append_reflog_on_store, delete_ref_on_store, update_direct_ref_on_store};
87use crate::repo::Repository;
88use crate::repo_relpath::{
89    as_utf8_for_matching, storage_bytes, storage_string, stored_directory_marker_parent,
90    stored_path_is_directory_marker, worktree_abs,
91};
92use crate::state::{resolve_head_for_repository, HeadState};
93use crate::worktree_rules::WorktreeRules;
94use crate::write_tree::{is_empty_tree_oid, write_tree_update_index, WriteTreeFlags};
95
96fn corrupt_stash_commit(oid: ObjectId) -> StashError {
97    StashError::corrupt_stash(oid, CorruptStashReason::InsufficientParents)
98}
99
100fn stash_worktree_io(
101    path: &str,
102    operation: WorktreePathOperation,
103    source: io::Error,
104) -> crate::error::Error {
105    map_worktree_io(path, operation, source)
106}
107
108/// A single blob entry from a recursively flattened tree.
109#[derive(Clone)]
110pub struct FlatTreeEntry {
111    /// Repository-relative path using `/` separators (UTF-8 when valid; non-UTF-8 and literal
112    /// `grit+pathhex:` names use the same reversible encoding as the index).
113    pub path: String,
114    /// Git tree entry mode (file, symlink, gitlink, …).
115    pub mode: u32,
116    /// Blob or subtree object id for this path.
117    pub oid: ObjectId,
118}
119
120/// Recursively flatten a tree into (path, mode, oid) entries.
121pub fn flatten_tree_full(
122    odb: &Odb,
123    tree_oid: &ObjectId,
124    prefix: &str,
125    protect: crate::path_validate::ProtectOptions,
126) -> Result<Vec<FlatTreeEntry>> {
127    let obj = odb.read(tree_oid)?;
128    let entries = parse_tree(&obj.data)?;
129    let mut result = Vec::new();
130    for entry in entries {
131        let full_path = crate::repo_relpath::format_path_stored(prefix, &entry.name);
132        crate::path_population::validate_tree_walk_entry(
133            prefix.as_bytes(),
134            &entry.name,
135            entry.mode,
136            protect,
137        )?;
138        if entry.mode == 0o40000 {
139            let sub = flatten_tree_full(odb, &entry.oid, &full_path, protect)?;
140            result.extend(sub);
141        } else {
142            result.push(FlatTreeEntry {
143                path: full_path,
144                mode: entry.mode,
145                oid: entry.oid,
146            });
147        }
148    }
149    Ok(result)
150}
151
152pub(crate) fn flatten_tree_full_for_repo(
153    repo: &Repository,
154    tree_oid: &ObjectId,
155    prefix: &str,
156) -> Result<Vec<FlatTreeEntry>> {
157    let protect = crate::path_validate::ProtectOptions::from_config(&*repo.config().snapshot()?);
158    flatten_tree_full(repo.odb(), tree_oid, prefix, protect)
159}
160
161/// Lookup a path in a lexicographically sorted [`flatten_tree_full`] slice.
162pub fn flat_tree_lookup<'a>(entries: &'a [FlatTreeEntry], path: &str) -> Option<&'a FlatTreeEntry> {
163    entries
164        .binary_search_by(|e| e.path.as_str().cmp(path))
165        .ok()
166        .map(|i| &entries[i])
167}
168
169/// Blob entry from a recursively flattened tree, with raw Git path bytes.
170struct RawFlatTreeEntry {
171    path: Vec<u8>,
172    mode: u32,
173    oid: ObjectId,
174}
175
176fn flatten_tree_full_raw(
177    odb: &Odb,
178    tree_oid: &ObjectId,
179    prefix: &[u8],
180    protect: crate::path_validate::ProtectOptions,
181) -> Result<Vec<RawFlatTreeEntry>> {
182    let obj = odb.read(tree_oid)?;
183    let entries = parse_tree(&obj.data)?;
184    let mut result = Vec::new();
185    for entry in entries {
186        let full_path = if prefix.is_empty() {
187            entry.name.clone()
188        } else {
189            crate::repo_relpath::join_rel(prefix, &entry.name)
190        };
191        crate::path_population::validate_tree_walk_entry(prefix, &entry.name, entry.mode, protect)?;
192        if entry.mode == 0o40000 {
193            let sub = flatten_tree_full_raw(odb, &entry.oid, &full_path, protect)?;
194            result.extend(sub);
195        } else {
196            result.push(RawFlatTreeEntry {
197                path: full_path,
198                mode: entry.mode,
199                oid: entry.oid,
200            });
201        }
202    }
203    Ok(result)
204}
205
206fn flatten_tree_full_raw_for_repo(
207    repo: &Repository,
208    tree_oid: &ObjectId,
209) -> Result<Vec<RawFlatTreeEntry>> {
210    let protect = crate::path_validate::ProtectOptions::from_config(&*repo.config().snapshot()?);
211    flatten_tree_full_raw(repo.odb(), tree_oid, b"", protect)
212}
213
214fn raw_flat_tree_lookup<'a>(
215    entries: &'a [RawFlatTreeEntry],
216    path: &[u8],
217) -> Option<&'a RawFlatTreeEntry> {
218    entries
219        .binary_search_by(|e| e.path.as_slice().cmp(path))
220        .ok()
221        .map(|i| &entries[i])
222}
223
224/// Changed tree leaves retain raw Git path bytes, independently of diff's string encoding.
225#[derive(Clone)]
226struct StashTreeEntry {
227    path: Vec<u8>,
228    mode: u32,
229    oid: ObjectId,
230}
231
232impl StashTreeEntry {
233    fn lookup<'a>(entries: &'a [Self], path: &[u8]) -> Option<&'a Self> {
234        entries
235            .binary_search_by(|e| e.path.as_slice().cmp(path))
236            .ok()
237            .map(|i| &entries[i])
238    }
239}
240
241/// Metadata is retained only for changed leaves; identical subtree OIDs are skipped.
242struct StashTreeDelta {
243    base: Vec<StashTreeEntry>,
244    changes: Vec<(Vec<u8>, Option<StashTreeEntry>)>,
245}
246
247impl StashTreeDelta {
248    fn read(repo: &Repository, base: &ObjectId, other: &ObjectId) -> Result<Self> {
249        let protect =
250            crate::path_validate::ProtectOptions::from_config(&*repo.config().snapshot()?);
251        let mut before = Vec::new();
252        let mut changes = Vec::new();
253        for change in diff_trees(repo.odb(), Some(base), Some(other), "")? {
254            let entry = |path: String, mode: FileMode, oid| -> Result<StashTreeEntry> {
255                let path = crate::repo_relpath::storage_bytes(&path).into_owned();
256                let mode = mode.bits();
257                crate::path_population::validate_worktree_path(&path, mode, protect)?;
258                Ok(StashTreeEntry { path, mode, oid })
259            };
260            if let Some(path) = &change.old_path {
261                before.push(entry(path.clone(), change.old_mode, change.old_oid)?);
262            }
263            let after = change
264                .new_path
265                .map(|path| entry(path, change.new_mode, change.new_oid))
266                .transpose()?;
267            if let Some(path) = after.as_ref().map(|e| e.path.clone()).or_else(|| {
268                change
269                    .old_path
270                    .map(|path| crate::repo_relpath::storage_bytes(&path).into_owned())
271            }) {
272                changes.push((path, after));
273            }
274        }
275        before.sort_by(|a, b| a.path.cmp(&b.path));
276        changes.sort_by(|a, b| a.0.cmp(&b.0));
277        Ok(Self {
278            base: before,
279            changes,
280        })
281    }
282}
283
284/// The file at `path` in `tree`; a directory in HEAD is not a file at this path.
285fn stash_tree_entry_at_path(
286    repo: &Repository,
287    tree: ObjectId,
288    path: &[u8],
289) -> Result<Option<StashTreeEntry>> {
290    Ok(repo
291        .odb()
292        .tree_entry_at_path(&tree, path)?
293        .filter(|entry| entry.mode != MODE_TREE)
294        .map(|entry| StashTreeEntry {
295            path: path.to_owned(),
296            mode: entry.mode,
297            oid: entry.oid,
298        }))
299}
300
301fn load_stash_index(repo: &Repository) -> Result<Index> {
302    match repo.load_index() {
303        Ok(index) => Ok(index),
304        Err(e)
305            if e.path_io()
306                .is_some_and(|path_io| path_io.source.kind() == io::ErrorKind::NotFound) =>
307        {
308            Ok(Index::new())
309        }
310        Err(e) => Err(e),
311    }
312}
313
314/// Push a conflict (non-zero) stage entry for `path` into `index`.
315pub fn add_stage_entry(index: &mut Index, path: &[u8], oid: &ObjectId, mode: u32, stage: u16) {
316    let name_len = path.len().min(0xFFF) as u16;
317    let flags = (stage << 12) | name_len;
318    index.push_entry_unsorted(IndexEntry {
319        ctime_sec: 0,
320        ctime_nsec: 0,
321        mtime_sec: 0,
322        mtime_nsec: 0,
323        dev: 0,
324        ino: 0,
325        mode,
326        uid: 0,
327        gid: 0,
328        size: 0,
329        oid: *oid,
330        flags,
331        flags_extended: None,
332        path: path.to_vec(),
333        base_index_pos: 0,
334    });
335}
336
337/// Read the worktree bytes for `path`, honoring a symlink index mode (returns
338/// the link target rather than following it).
339pub fn worktree_bytes_for_index_mode(path: &Path, mode: u32) -> io::Result<Vec<u8>> {
340    crate::diff::read_worktree_bytes_for_mode(path, mode)
341}
342
343/// Write a regular file at `path`, first removing any pre-existing symlink there.
344pub fn write_regular_file_replacing_symlink(path: &Path, contents: &[u8]) -> io::Result<()> {
345    use std::io::Write;
346    if path
347        .symlink_metadata()
348        .is_ok_and(|m| m.file_type().is_symlink())
349    {
350        fs::remove_file(path)?;
351    }
352    if path.is_file() {
353        if let Ok(mut file) = fs::OpenOptions::new().write(true).truncate(true).open(path) {
354            file.write_all(contents)?;
355            return Ok(());
356        }
357    }
358    fs::write(path, contents)
359}
360
361/// Remove now-empty directories from `dir` upward toward (but not including)
362/// `stop_at`, refusing to remove a directory that contains the process CWD.
363pub fn remove_empty_dirs(
364    dir: &Path,
365    stop_at: &Path,
366    environment: &crate::environment::Environment,
367) {
368    let cwd_rel = crate::worktree_cwd::process_cwd_repo_relative(stop_at, environment);
369    let mut current = dir.to_path_buf();
370    while current != stop_at {
371        if fs::read_dir(&current)
372            .map(|mut d| d.next().is_none())
373            .unwrap_or(false)
374        {
375            if let Some(ref cr) = cwd_rel {
376                if crate::worktree_cwd::cwd_would_be_removed_with_dir(stop_at, &current, cr) {
377                    break;
378                }
379            }
380            let _ = fs::remove_dir(&current);
381            if let Some(parent) = current.parent() {
382                current = parent.to_path_buf();
383            } else {
384                break;
385            }
386        } else {
387            break;
388        }
389    }
390}
391
392/// Which local changes a stash push saves and how the worktree/index are left afterward.
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
394pub enum StashMode {
395    /// Stash staged and unstaged tracked changes (default).
396    #[default]
397    All,
398    /// Stash only index changes vs `HEAD`; unstaged worktree edits on other paths remain.
399    StagedOnly,
400    /// Stash everything, then reset the worktree to match the index (staged content stays).
401    KeepIndex,
402}
403
404/// Paths that would be recorded by
405/// [`RepositoryStash::preview`](crate::repo_handles::RepositoryStash::preview).
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct StashPreview {
408    /// Repository-relative paths with tracked changes that would be stashed.
409    pub paths: Vec<String>,
410    /// Untracked paths that would be included when `include_untracked` is set.
411    pub untracked: Vec<String>,
412    /// For a partial push ([`StashPushOptions::selection`]), the hunk ids that would be stashed,
413    /// per repository-relative path. Empty otherwise.
414    pub stashed_hunks: BTreeMap<String, Vec<HunkId>>,
415    /// For a partial push, the requested line range labels (`start` or `start-end`) that would
416    /// be stashed, per path. Empty otherwise.
417    pub stashed_lines: BTreeMap<String, Vec<String>>,
418}
419
420/// Options for [`RepositoryStash::push`](crate::repo_handles::RepositoryStash::push),
421/// [`RepositoryStash::create`](crate::repo_handles::RepositoryStash::create), and
422/// [`RepositoryStash::preview`](crate::repo_handles::RepositoryStash::preview).
423#[derive(Debug, Clone)]
424pub struct StashPushOptions {
425    /// Reflog/stash message override; when set, the W commit message is `On <branch>: <msg>`.
426    pub message: Option<String>,
427    /// When true, include untracked files as a parentless U commit (parent 3 of W).
428    pub include_untracked: bool,
429    /// Author and committer of the stash commits and identity of the `refs/stash` reflog entry
430    /// (for example from [`Repository::identity`]).
431    pub identity: Signature,
432    /// When set, stash only these unstaged hunks (index is left unchanged on push).
433    pub selection: Option<HunkSelection>,
434    /// Pathspecs narrowing hunk resolution (same as `grit add --hunks`).
435    pub pathspecs: Vec<String>,
436    /// When true, [`RepositoryStash::push`](crate::repo_handles::RepositoryStash::push) refuses
437    /// to run; use [`RepositoryStash::preview`](crate::repo_handles::RepositoryStash::preview),
438    /// which ignores this flag.
439    pub dry_run: bool,
440    /// Push mode (`--staged`, `--keep-index`, or default).
441    pub mode: StashMode,
442}
443
444impl StashPushOptions {
445    /// Push options with only [`Self::identity`] required; other fields match Git defaults.
446    #[must_use]
447    pub fn new(identity: Signature) -> Self {
448        Self {
449            message: None,
450            include_untracked: false,
451            identity,
452            selection: None,
453            pathspecs: Vec::new(),
454            dry_run: false,
455            mode: StashMode::default(),
456        }
457    }
458
459    /// Reject flag combinations Git and grit do not support.
460    ///
461    /// # Errors
462    ///
463    /// Returns [`StashPushValidationError`] when options conflict or
464    /// [`Self::identity`] cannot be written into a commit.
465    pub fn validate(&self) -> std::result::Result<(), StashPushValidationError> {
466        self.identity.validate()?;
467        if self.mode == StashMode::StagedOnly && self.include_untracked {
468            return Err(StashPushValidationError::StagedWithUntracked);
469        }
470        if self.mode == StashMode::StagedOnly && selection_is_active(self) {
471            return Err(StashPushValidationError::StagedWithSelection);
472        }
473        if self.mode == StashMode::KeepIndex && selection_is_active(self) {
474            return Err(StashPushValidationError::KeepIndexWithSelection);
475        }
476        if self.include_untracked && selection_is_active(self) {
477            return Err(StashPushValidationError::UntrackedWithSelection);
478        }
479        Ok(())
480    }
481
482    /// Staged-only push cannot run when a staged path also has unstaged worktree edits.
483    pub fn validate_staged_worktree(
484        &self,
485        repo: &Repository,
486        work_tree: &Path,
487        head_tree: &ObjectId,
488    ) -> crate::error::Result<()> {
489        if self.mode != StashMode::StagedOnly {
490            return Ok(());
491        }
492        let mut index = repo.load_index()?;
493        let staged: HashSet<String> =
494            staged_change_paths_for_options(repo, &index, head_tree, self)?
495                .into_iter()
496                .collect();
497        if staged.is_empty() {
498            return Ok(());
499        }
500        let diff_opts = stash_worktree_diff_opts(repo, &index, None)?;
501        let (unstaged, _) =
502            diff_index_to_worktree_with_options(repo.odb(), &mut index, work_tree, diff_opts)?;
503        for entry in unstaged {
504            let path = entry.path();
505            if staged.contains(path) {
506                return Err(StashError::PushValidation(
507                    StashPushValidationError::StagedWorktreeDirty {
508                        path: path.to_owned(),
509                    },
510                )
511                .into());
512            }
513        }
514        Ok(())
515    }
516}
517
518/// Options for [`RepositoryStash::apply`](crate::repo_handles::RepositoryStash::apply) and
519/// [`RepositoryStash::pop`](crate::repo_handles::RepositoryStash::pop).
520#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
521pub struct StashApplyOptions {
522    /// Restore the stashed index parent instead of keeping the current index at touched paths.
523    ///
524    /// Paths that were only modified in the work tree at stash time come back unstaged, even
525    /// when the stash's index parent equals its base commit's tree.
526    pub restore_index: bool,
527    /// When true, an existing untracked file blocks restore only if its on-disk bytes differ
528    /// from the stashed untracked parent (Git still refuses in all cases).
529    pub overwrite_identical_untracked: bool,
530}
531
532/// Options for [`RepositoryStash::diff`](crate::repo_handles::RepositoryStash::diff).
533#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
534pub struct StashDiffOptions {
535    /// Include untracked files from the stash U parent (same as `git stash show -u`).
536    pub include_untracked: bool,
537}
538
539/// Result of [`RepositoryStash::branch`](crate::repo_handles::RepositoryStash::branch).
540#[derive(Debug, Clone, PartialEq, Eq)]
541pub struct StashBranchOutcome {
542    /// Short name of the branch created at the stash base commit.
543    pub branch: String,
544    /// Stash base commit (parent 1 of the W commit).
545    pub base: ObjectId,
546    /// Stash W commit that was applied.
547    pub stash_oid: ObjectId,
548    /// Stash reflog index when the commit was on `refs/stash`.
549    pub index: Option<usize>,
550    /// Whether applying the stash left merge conflicts.
551    pub conflicts: bool,
552    /// Paths with unmerged index entries when [`Self::conflicts`] is true.
553    pub conflict_paths: Vec<String>,
554}
555
556/// One entry from [`RepositoryStash::list`](crate::repo_handles::RepositoryStash::list)
557/// (`stash@{{index}}` in newest-first order).
558#[derive(Debug, Clone, PartialEq, Eq)]
559#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
560pub struct StashEntry {
561    /// Index matching `stash@{{index}}` (0 is newest).
562    pub index: usize,
563    /// The W commit object id stored in the reflog.
564    pub oid: ObjectId,
565    /// Reflog message (what `git stash list` prints after the colon).
566    pub message: String,
567}
568
569/// How to address a stash entry or a stash-shaped commit.
570#[derive(Debug, Clone, Copy, PartialEq, Eq)]
571pub enum StashReference {
572    /// Newest-first reflog index (`stash@{{n}}`).
573    Index(usize),
574    /// A stash W commit, on or off the stack.
575    Commit(ObjectId),
576}
577
578/// Parse a stash selector.
579///
580/// Missing input defaults to index `0`. `stash@{{n}}` and an all-decimal token select an index
581/// (matching Git: an all-digit token is never treated as a short object id). Any other token is
582/// resolved with [`crate::rev_parse::resolve_revision_as_commit`].
583///
584/// # Errors
585///
586/// Invalid index syntax, unknown revision, or ref parse failures.
587pub fn parse_stash_reference(repo: &Repository, spec: Option<&str>) -> Result<StashReference> {
588    let raw = spec.map(str::trim).unwrap_or("0");
589    if raw.is_empty() {
590        return Ok(StashReference::Index(0));
591    }
592    let digits = if let Some(inner) = raw
593        .strip_prefix("stash@{")
594        .and_then(|s| s.strip_suffix('}'))
595    {
596        inner
597    } else {
598        raw
599    };
600    if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) {
601        let n = digits.parse::<usize>().map_err(|source| {
602            Error::Ref(RefError::ReflogInvalidIndex {
603                spec: raw.to_owned(),
604                source,
605            })
606        })?;
607        return Ok(StashReference::Index(n));
608    }
609    let oid = crate::rev_parse::resolve_revision_as_commit(repo, raw)?;
610    Ok(StashReference::Commit(oid))
611}
612
613/// Newest-first index of `oid` on `refs/stash`, if present.
614pub fn stash_index_for_oid(repo: &Repository, oid: &ObjectId) -> Option<usize> {
615    list_stashes(repo)
616        .ok()?
617        .into_iter()
618        .find(|e| e.oid == *oid)
619        .map(|e| e.index)
620}
621
622fn head_branch_label(head: &HeadState) -> String {
623    match head {
624        HeadState::Branch { short_name, .. } => short_name.clone(),
625        _ => "(no branch)".to_owned(),
626    }
627}
628
629fn head_commit_oid(head: &HeadState) -> crate::error::Result<ObjectId> {
630    head.oid()
631        .copied()
632        .ok_or(crate::error::Error::from(StashError::NoInitialCommit))
633}
634
635fn head_commit_subject(repo: &Repository, head_oid: &ObjectId) -> Result<String> {
636    let commit = repo.odb().read_commit(head_oid)?;
637    Ok(commit
638        .message
639        .lines()
640        .next()
641        .unwrap_or("")
642        .trim_end()
643        .to_owned())
644}
645
646fn stash_context_message(
647    repo: &Repository,
648    head: &HeadState,
649    head_oid: &ObjectId,
650) -> Result<String> {
651    let branch = head_branch_label(head);
652    let short = head_oid.to_short_hex();
653    let subject = head_commit_subject(repo, head_oid)?;
654    Ok(format!("{branch}: {short} {subject}"))
655}
656
657fn stash_worktree_diff_opts(
658    repo: &Repository,
659    index: &Index,
660    pathspecs: Option<&[String]>,
661) -> Result<DiffIndexToWorktreeOptions> {
662    let index_mtime = index_file_mtime(&repo.index_path());
663    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
664    let rules_arc = std::sync::Arc::new(std::sync::Mutex::new(worktree_rules));
665    let restrict_to_paths = match pathspecs {
666        Some(ps) if !ps.is_empty() => Some(std::sync::Arc::new(
667            restricted_index_paths_for_pathspecs(repo, index, ps, repo.pathspec_match_context())?,
668        )),
669        _ => None,
670    };
671    Ok(DiffIndexToWorktreeOptions {
672        index_mtime,
673        ignore_submodule_untracked: true,
674        simplify_gitlinks: true,
675        repository_git_dir: Some(repo.git_dir().to_path_buf()),
676        config: repo.config().snapshot().ok(),
677        worktree_rules: Some(rules_arc),
678        skip_inaccessible_paths: true,
679        diagnostics: Some(repo.diagnostics()),
680        restrict_to_paths,
681        ..DiffIndexToWorktreeOptions::default()
682    })
683}
684
685fn staged_change_paths(
686    repo: &Repository,
687    index: &Index,
688    head_tree: &ObjectId,
689) -> Result<Vec<String>> {
690    let staged = diff_index_to_tree(repo.odb(), index, Some(head_tree), true)?;
691    Ok(staged.into_iter().map(|e| e.path().to_string()).collect())
692}
693
694fn filter_paths_by_pathspecs(
695    repo: &Repository,
696    paths: Vec<String>,
697    pathspecs: &[String],
698) -> Result<Vec<String>> {
699    if pathspecs.is_empty() {
700        return Ok(paths);
701    }
702    let index = repo.load_index().ok();
703    let filter = RepositoryPathspecFilter::try_new(repo, pathspecs)?;
704    Ok(paths
705        .into_iter()
706        .filter(|path| {
707            let mode = index
708                .as_ref()
709                .map(|idx| index_stage0_mode_or_regular(idx, path))
710                .unwrap_or(REGULAR_FILE_MODE);
711            filter.matches_entry(path, mode)
712        })
713        .collect())
714}
715
716fn staged_change_paths_for_options(
717    repo: &Repository,
718    index: &Index,
719    head_tree: &ObjectId,
720    options: &StashPushOptions,
721) -> Result<Vec<String>> {
722    let paths = staged_change_paths(repo, index, head_tree)?;
723    filter_paths_by_pathspecs(repo, paths, &options.pathspecs)
724}
725
726/// What [`has_stashable_changes`] found.
727enum StashableChanges {
728    /// Index and worktree match `HEAD`, and no wanted untracked files exist.
729    Nothing,
730    /// There is something to stash. `unstaged` is the index-to-worktree diff when the scan
731    /// computed one over an index that [`index_is_plain_for_stash`] accepts, so building the W
732    /// tree can reuse it instead of diffing the worktree again.
733    Found { unstaged: Option<Vec<DiffEntry>> },
734}
735
736/// Whether diffing `index` against the worktree gives the same result as diffing an index
737/// built from the tree `index` writes, seeded with its stat data: only plain stage-0 file
738/// entries, none of which carries a flag that a tree-built copy would lose.
739fn index_is_plain_for_stash(index: &Index) -> bool {
740    index.entries.iter().all(|e| {
741        e.stage() == 0
742            && e.mode != MODE_TREE
743            && !e.skip_worktree()
744            && !e.assume_unchanged()
745            && !e.intent_to_add()
746            && !e.fsmonitor_valid()
747    })
748}
749
750fn has_stashable_changes(
751    repo: &Repository,
752    work_tree: &Path,
753    head_tree: &ObjectId,
754    options: &StashPushOptions,
755) -> Result<StashableChanges> {
756    let found = |unstaged: Option<Vec<DiffEntry>>| Ok(StashableChanges::Found { unstaged });
757    let mut index = repo.load_index()?;
758    if options.mode == StashMode::StagedOnly {
759        if staged_change_paths_for_options(repo, &index, head_tree, options)?.is_empty() {
760            return Ok(StashableChanges::Nothing);
761        }
762        return found(None);
763    }
764    if !diff_index_to_tree(repo.odb(), &index, Some(head_tree), true)?.is_empty() {
765        return found(None);
766    }
767    let plain = index_is_plain_for_stash(&index);
768    let include_untracked = options.include_untracked;
769    let diff_opts = stash_worktree_diff_opts(repo, &index, None)?;
770    let (unstaged, _) =
771        diff_index_to_worktree_with_options(repo.odb(), &mut index, work_tree, diff_opts)?;
772    if !unstaged.is_empty() {
773        return found(plain.then_some(unstaged));
774    }
775    if !include_untracked {
776        return Ok(StashableChanges::Nothing);
777    }
778    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, &index)?;
779    let (untracked, _, _) = collect_untracked_and_ignored_inner(
780        repo,
781        &mut index,
782        work_tree,
783        &[],
784        None,
785        UntrackedScan {
786            ignored_mode: IgnoredMode::No,
787            show_all: false,
788            sort_paths: true,
789            use_untracked_cache: false,
790            cache_miss: UntrackedCacheMissAction::RefreshFull,
791            clean_unit_dirs: None,
792            listing_cache: None,
793        },
794        &worktree_rules,
795        None,
796    )?;
797    if untracked.is_empty() {
798        return Ok(StashableChanges::Nothing);
799    }
800    found(plain.then_some(unstaged))
801}
802
803pub(crate) fn collect_untracked_paths(repo: &Repository, work_tree: &Path) -> Result<Vec<String>> {
804    let mut index = repo.load_index()?;
805    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, &index)?;
806    let (untracked, _, _) = collect_untracked_and_ignored_inner(
807        repo,
808        &mut index,
809        work_tree,
810        &[],
811        None,
812        UntrackedScan {
813            ignored_mode: IgnoredMode::No,
814            show_all: true,
815            sort_paths: true,
816            use_untracked_cache: false,
817            cache_miss: UntrackedCacheMissAction::RefreshFull,
818            clean_unit_dirs: None,
819            listing_cache: None,
820        },
821        &worktree_rules,
822        None,
823    )?;
824    Ok(untracked
825        .into_iter()
826        .filter(|path| !path_in_nested_git_worktree(work_tree, path))
827        .collect())
828}
829
830/// Stage every unstaged worktree change into `index`.
831///
832/// `precomputed` is the index-to-worktree diff of an index with the same entries and stat data
833/// as `index`; when absent the diff is computed here.
834fn apply_worktree_diff_to_index(
835    repo: &Repository,
836    work_tree: &Path,
837    index: &mut Index,
838    precomputed: Option<Vec<DiffEntry>>,
839    scope: &mut ProgressScope<'_>,
840) -> Result<()> {
841    let index_mtime = index_file_mtime(&repo.index_path());
842    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
843    let rules_arc = std::sync::Arc::new(std::sync::Mutex::new(worktree_rules));
844    let unstaged = match precomputed {
845        Some(unstaged) => unstaged,
846        None => {
847            let diff_opts = stash_worktree_diff_opts(repo, index, None)?;
848            diff_index_to_worktree_with_options(repo.odb(), index, work_tree, diff_opts)?.0
849        }
850    };
851    let mut worktree_rules = rules_arc.lock().unwrap_or_else(|e| e.into_inner());
852    let precompose = crate::precompose_config::effective_core_precomposeunicode_with_config(
853        Some(repo.git_dir()),
854        Some(&worktree_rules.config_arc()),
855    );
856    scope
857        .sink()
858        .start(ProgressPhase::StagingFiles, Some(unstaged.len() as u64));
859    for entry in unstaged {
860        scope.poll()?;
861        scope.sink().inc(1);
862        let path = entry.path();
863        if entry.status == DiffStatus::Deleted {
864            index.remove(storage_bytes(path).as_ref());
865            continue;
866        }
867        stage_tracked_path_for_stash(
868            repo,
869            work_tree,
870            path,
871            index,
872            index_mtime,
873            &mut worktree_rules,
874            precompose,
875        )?;
876    }
877    scope.sink().finish();
878    Ok(())
879}
880
881fn stage_tracked_path_for_stash(
882    repo: &Repository,
883    work_tree: &Path,
884    rel_path: &str,
885    index: &mut Index,
886    index_mtime: Option<(u32, u32)>,
887    rules: &mut crate::worktree_rules::WorktreeRules,
888    precompose_unicode: bool,
889) -> Result<()> {
890    use crate::diff::{
891        classify_worktree_entry_for_add, mode_from_metadata, WorktreeAddRefresh,
892        WorktreeAddRefreshParams,
893    };
894    use crate::unicode_normalization::resolve_worktree_path_for_staging;
895
896    if stored_path_is_directory_marker(rel_path) {
897        return Ok(());
898    }
899    let index_path = storage_bytes(rel_path);
900    let conv = rules.conversion().clone();
901    let resolved = resolve_worktree_path_for_staging(work_tree, rel_path, precompose_unicode);
902    let abs = resolved.abs;
903    let meta = match fs::symlink_metadata(&abs) {
904        Ok(m) => m,
905        Err(e) if e.kind() == io::ErrorKind::NotFound => {
906            index.remove(index_path.as_ref());
907            return Ok(());
908        }
909        Err(e) => return Err(e.into()),
910    };
911    let Some(ie) = index.get(index_path.as_ref(), 0).cloned() else {
912        return stage_untracked_path_for_stash(
913            repo,
914            work_tree,
915            rel_path,
916            index,
917            precompose_unicode,
918            rules,
919        );
920    };
921    let staged_mode = crate::index::WorktreeModePolicy::from_config(rules.config())
922        .index_mode_for_worktree(mode_from_metadata(&meta), Some(ie.mode));
923    let file_attrs = rules.file_attrs(&as_utf8_for_matching(rel_path), false);
924    let refresh = classify_worktree_entry_for_add(&WorktreeAddRefreshParams {
925        odb: repo.odb(),
926        ie: &ie,
927        meta: &meta,
928        abs_path: &abs,
929        rel_path,
930        conv: &conv,
931        file_attrs: &file_attrs,
932        index_mtime,
933        staged_mode,
934        filter_process: Some(rules.filter_process()),
935    })?;
936    match refresh {
937        WorktreeAddRefresh::UpToDate => Ok(()),
938        WorktreeAddRefresh::ModeOnly { mode } => {
939            if let Some(entry) = index.get_mut(index_path.as_ref(), 0) {
940                entry.mode = mode;
941                index.invalidate_cache_tree_for_path(index_path.as_ref());
942            }
943            Ok(())
944        }
945        WorktreeAddRefresh::StatOnly => {
946            let updated =
947                crate::index::entry_from_metadata(&meta, index_path.as_ref(), ie.oid, ie.mode);
948            index.add_or_replace(updated);
949            Ok(())
950        }
951        WorktreeAddRefresh::NeedsRestage => stage_untracked_path_for_stash(
952            repo,
953            work_tree,
954            rel_path,
955            index,
956            precompose_unicode,
957            rules,
958        ),
959    }
960}
961
962fn stage_untracked_path_for_stash(
963    repo: &Repository,
964    work_tree: &Path,
965    rel_path: &str,
966    index: &mut Index,
967    precompose_unicode: bool,
968    rules: &crate::worktree_rules::WorktreeRules,
969) -> Result<()> {
970    use crate::diff::mode_from_metadata;
971    use crate::index::entry_from_stat;
972    use crate::repo_relpath::{as_utf8_for_matching, storage_bytes};
973    use crate::unicode_normalization::{precompose_utf8_path, resolve_worktree_path_for_staging};
974
975    if stored_path_is_directory_marker(rel_path) {
976        return Ok(());
977    }
978    let resolved = resolve_worktree_path_for_staging(work_tree, rel_path, precompose_unicode);
979    let abs = resolved.abs;
980    let mut index_path_bytes = storage_bytes(rel_path).into_owned();
981    if precompose_unicode {
982        if let Ok(s) = std::str::from_utf8(&index_path_bytes) {
983            index_path_bytes = precompose_utf8_path(s).into_owned().into_bytes();
984        }
985    }
986    let attrs_path = as_utf8_for_matching(rel_path);
987    let meta = fs::symlink_metadata(&abs).map_err(Error::Io)?;
988    if meta.is_dir() {
989        return Ok(());
990    }
991    let recorded_mode = index.get(&index_path_bytes, 0).map(|e| e.mode);
992    let mode = crate::index::WorktreeModePolicy::from_config(rules.config())
993        .index_mode_for_worktree(mode_from_metadata(&meta), recorded_mode);
994    if mode == MODE_TREE {
995        return Ok(());
996    }
997
998    let file_attrs = rules.file_attrs(&attrs_path, false);
999    let conv = rules.conversion();
1000    let filter_fp = Some(rules.filter_process());
1001    let oid = if meta.file_type().is_symlink() {
1002        let target = fs::read_link(&abs).map_err(Error::Io)?;
1003        let data = crate::diff::symlink_target_bytes(&target);
1004        repo.odb().write(ObjectKind::Blob, &data)?
1005    } else {
1006        crate::diff::materialize_worktree_blob(
1007            repo.odb(),
1008            &abs,
1009            &meta,
1010            conv,
1011            &file_attrs,
1012            &attrs_path,
1013            None,
1014            filter_fp,
1015        )
1016        .map_err(|e| materialize_stash_blob_err(e, &attrs_path))?
1017    };
1018    let entry = entry_from_stat(&abs, &index_path_bytes, oid, mode)?;
1019    index.add_or_replace(entry);
1020    Ok(())
1021}
1022
1023fn write_stash_tree_from_index(repo: &Repository, index: &mut Index) -> Result<ObjectId> {
1024    index.sort();
1025    let odb = repo.odb();
1026    let tree = write_tree_update_index(odb, index, "", WriteTreeFlags::silent())?;
1027    if is_empty_tree_oid(odb, &tree) {
1028        odb.write_local(ObjectKind::Tree, b"")?;
1029    }
1030    Ok(tree)
1031}
1032
1033fn write_untracked_stash_commit(
1034    repo: &Repository,
1035    work_tree: &Path,
1036    paths: &[String],
1037    context_msg: &str,
1038    identity: &str,
1039) -> Result<ObjectId> {
1040    let mut index = Index::new();
1041    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, &index)?;
1042    let precompose = crate::precompose_config::effective_core_precomposeunicode_with_config(
1043        Some(repo.git_dir()),
1044        Some(&worktree_rules.config_arc()),
1045    );
1046    for path in paths {
1047        stage_untracked_path_for_stash(
1048            repo,
1049            work_tree,
1050            path,
1051            &mut index,
1052            precompose,
1053            &worktree_rules,
1054        )?;
1055    }
1056    let tree = write_stash_tree_from_index(repo, &mut index)?;
1057    let message = format!("untracked files on {context_msg}\n");
1058    let data = CommitData {
1059        tree,
1060        parents: Vec::new(),
1061        author: identity.to_owned(),
1062        committer: identity.to_owned(),
1063        author_raw: Vec::new(),
1064        committer_raw: Vec::new(),
1065        encoding: None,
1066        message,
1067        raw_message: None,
1068        extra_headers: Vec::new(),
1069    };
1070    write_commit_object(repo, &data, STASH_COMMIT_SIGNING)
1071}
1072
1073fn remove_stashed_untracked(repo: &Repository, work_tree: &Path, paths: &[String]) -> Result<()> {
1074    for path in paths {
1075        if path_in_nested_git_worktree(work_tree, path) {
1076            continue;
1077        }
1078        let stored = if stored_path_is_directory_marker(path) {
1079            stored_directory_marker_parent(path)
1080        } else {
1081            path.clone()
1082        };
1083        let file_path = worktree_abs(work_tree, &stored);
1084        if file_path.is_dir() {
1085            if is_nested_git_worktree(&file_path) {
1086                continue;
1087            }
1088            let _ = fs::remove_dir_all(&file_path);
1089        } else if file_path.exists() || file_path.symlink_metadata().is_ok() {
1090            let _ = fs::remove_file(&file_path);
1091        }
1092        if let Some(parent) = file_path.parent() {
1093            remove_empty_dirs(parent, work_tree, repo.environment());
1094        }
1095    }
1096    Ok(())
1097}
1098
1099/// Stash commits are local bookkeeping and are never signed, whatever `commit.gpgsign` says
1100/// (Git creates them unsigned too).
1101const STASH_COMMIT_SIGNING: Option<bool> = Some(false);
1102
1103struct BuiltStash {
1104    w_commit: ObjectId,
1105    w_tree: ObjectId,
1106    i_tree: ObjectId,
1107    message: String,
1108    untracked_paths: Vec<String>,
1109    partial: Option<ResolvedSelection>,
1110    push_pathspecs: Vec<String>,
1111    staged_only_paths: Vec<String>,
1112    mode: StashMode,
1113}
1114
1115fn selection_is_active(options: &StashPushOptions) -> bool {
1116    options
1117        .selection
1118        .as_ref()
1119        .is_some_and(|sel| !sel.ids.is_empty() || !sel.ranges.is_empty())
1120}
1121
1122fn refresh_index_stat_from_worktree(
1123    index: &mut Index,
1124    work_tree: &Path,
1125    path: &str,
1126    oid: ObjectId,
1127    mode: u32,
1128) -> Result<()> {
1129    let path_bytes = crate::repo_relpath::storage_bytes(path);
1130    let abs = crate::repo_relpath::worktree_abs(work_tree, path);
1131    let meta = fs::symlink_metadata(&abs).map_err(Error::Io)?;
1132    let entry = crate::index::entry_from_metadata(&meta, path_bytes.as_ref(), oid, mode);
1133    index.add_or_replace(entry);
1134    Ok(())
1135}
1136
1137fn apply_staged_worktree_only_reset(
1138    repo: &Repository,
1139    work_tree: &Path,
1140    head_tree: &ObjectId,
1141    staged_paths: &[String],
1142    progress: &mut dyn ProgressSink,
1143    cancel: &CancelToken,
1144) -> Result<()> {
1145    if staged_paths.is_empty() {
1146        return Ok(());
1147    }
1148    let head_entries = flatten_tree_full_raw_for_repo(repo, head_tree)?;
1149    let index = repo.load_index()?;
1150    let worktree_rules = WorktreeRules::from_repository(repo, &index)?;
1151    progress.start(
1152        ProgressPhase::CheckingOutFiles,
1153        Some(staged_paths.len() as u64),
1154    );
1155    for path in staged_paths {
1156        poll_cancel(progress, cancel)?;
1157        progress.inc(1);
1158        let raw = storage_bytes(path);
1159        if let Some(entry) = raw_flat_tree_lookup(&head_entries, raw.as_ref()) {
1160            materialize_raw_flat_entry_in_worktree(repo, work_tree, &worktree_rules, entry)?;
1161        } else {
1162            let file_path = crate::repo_relpath::worktree_abs(work_tree, path);
1163            if file_path.is_dir() {
1164                if !is_nested_git_worktree(&file_path) {
1165                    let _ = fs::remove_dir_all(&file_path);
1166                }
1167            } else if file_path.exists() || file_path.symlink_metadata().is_ok() {
1168                let _ = fs::remove_file(&file_path);
1169            }
1170            if let Some(parent) = file_path.parent() {
1171                remove_empty_dirs(parent, work_tree, repo.environment());
1172            }
1173        }
1174    }
1175    progress.finish();
1176    Ok(())
1177}
1178
1179/// Reset `staged_paths` to `head_tree` in the work tree and index. A cancel stops between
1180/// files and leaves the index unwritten.
1181fn apply_staged_only_reset(
1182    repo: &Repository,
1183    work_tree: &Path,
1184    head_tree: &ObjectId,
1185    staged_paths: &[String],
1186    lock: &mut IndexLock,
1187    progress: &mut dyn ProgressSink,
1188    cancel: &CancelToken,
1189) -> Result<()> {
1190    if staged_paths.is_empty() {
1191        return Ok(());
1192    }
1193    let head_entries = flatten_tree_full_raw_for_repo(repo, head_tree)?;
1194    let mut index = repo.load_index()?;
1195    let worktree_rules = WorktreeRules::from_repository(repo, &index)?;
1196    progress.start(
1197        ProgressPhase::CheckingOutFiles,
1198        Some(staged_paths.len() as u64),
1199    );
1200    for path in staged_paths {
1201        poll_cancel(progress, cancel)?;
1202        progress.inc(1);
1203        let raw = storage_bytes(path);
1204        if let Some(entry) = raw_flat_tree_lookup(&head_entries, raw.as_ref()) {
1205            materialize_raw_flat_entry_in_worktree(repo, work_tree, &worktree_rules, entry)?;
1206            refresh_index_stat_from_worktree(&mut index, work_tree, path, entry.oid, entry.mode)?;
1207        } else {
1208            index.remove(crate::repo_relpath::storage_bytes(path).as_ref());
1209            let file_path = crate::repo_relpath::worktree_abs(work_tree, path);
1210            if file_path.is_dir() {
1211                if !is_nested_git_worktree(&file_path) {
1212                    let _ = fs::remove_dir_all(&file_path);
1213                }
1214            } else if file_path.exists() || file_path.symlink_metadata().is_ok() {
1215                let _ = fs::remove_file(&file_path);
1216            }
1217            if let Some(parent) = file_path.parent() {
1218                remove_empty_dirs(parent, work_tree, repo.environment());
1219            }
1220        }
1221    }
1222    progress.finish();
1223    repo.write_index_with_lock(lock, &mut index, false)
1224}
1225
1226fn tracked_stash_preview_paths(
1227    repo: &Repository,
1228    work_tree: &Path,
1229    head_tree: &ObjectId,
1230    options: &StashPushOptions,
1231) -> Result<Vec<String>> {
1232    let mut index = repo.load_index()?;
1233    let mut paths: BTreeSet<String> = BTreeSet::new();
1234    if options.mode != StashMode::StagedOnly {
1235        let diff_opts = stash_worktree_diff_opts(repo, &index, None)?;
1236        let (unstaged, _) =
1237            diff_index_to_worktree_with_options(repo.odb(), &mut index, work_tree, diff_opts)?;
1238        for entry in unstaged {
1239            paths.insert(entry.path().to_string());
1240        }
1241    }
1242    for path in staged_change_paths_for_options(repo, &index, head_tree, options)? {
1243        paths.insert(path);
1244    }
1245    Ok(paths.into_iter().collect())
1246}
1247
1248/// List paths that would be stashed without writing objects, refs, or worktree state.
1249///
1250/// Returns `None` when there is nothing to save.
1251///
1252/// # Errors
1253///
1254/// Propagates validation and diff failures.
1255pub(crate) fn preview_stash(
1256    repo: &Repository,
1257    options: &StashPushOptions,
1258) -> crate::error::Result<Option<StashPreview>> {
1259    options.validate()?;
1260    let work_tree = repo.work_tree().ok_or(StashError::BareRepository)?;
1261    let head = resolve_head_for_repository(repo)?;
1262    let head_oid = head_commit_oid(&head)?;
1263    let head_tree = repo.odb().commit_tree(&head_oid)?;
1264
1265    if let Some(partial) = resolve_partial_stash(repo, options)? {
1266        if partial.patches.is_empty() {
1267            return Ok(None);
1268        }
1269        let paths: Vec<String> = partial
1270            .patches
1271            .into_iter()
1272            .filter_map(|p| p.new_path.or(p.old_path))
1273            .collect();
1274        return Ok(Some(StashPreview {
1275            paths,
1276            untracked: Vec::new(),
1277            stashed_hunks: partial.selected_hunks,
1278            stashed_lines: partial.selected_lines,
1279        }));
1280    }
1281
1282    options.validate_staged_worktree(repo, work_tree, &head_tree)?;
1283    if matches!(
1284        has_stashable_changes(repo, work_tree, &head_tree, options)?,
1285        StashableChanges::Nothing
1286    ) {
1287        return Ok(None);
1288    }
1289
1290    let paths = tracked_stash_preview_paths(repo, work_tree, &head_tree, options)?;
1291    let untracked = if options.include_untracked && options.mode != StashMode::StagedOnly {
1292        collect_untracked_paths(repo, work_tree)?
1293    } else {
1294        Vec::new()
1295    };
1296    if paths.is_empty() && untracked.is_empty() {
1297        return Ok(None);
1298    }
1299    Ok(Some(StashPreview {
1300        paths,
1301        untracked,
1302        stashed_hunks: BTreeMap::new(),
1303        stashed_lines: BTreeMap::new(),
1304    }))
1305}
1306
1307fn stash_push_pathspecs_active(options: &StashPushOptions) -> bool {
1308    !options.pathspecs.is_empty() && !selection_is_active(options)
1309}
1310
1311fn pathspec_matcher<'a>(
1312    repo: &Repository,
1313    pathspecs: &'a [String],
1314) -> Result<RepositoryPathspecFilter<'a>> {
1315    RepositoryPathspecFilter::try_new(repo, pathspecs)
1316}
1317
1318fn index_stage0_paths(index: &Index) -> Vec<String> {
1319    let mut paths: Vec<String> = index
1320        .entries
1321        .iter()
1322        .filter(|e| e.stage() == 0)
1323        .map(|e| String::from_utf8_lossy(&e.path).into_owned())
1324        .collect();
1325    paths.sort();
1326    paths.dedup();
1327    paths
1328}
1329
1330fn validate_stash_push_pathspecs(
1331    repo: &Repository,
1332    work_tree: &Path,
1333    options: &StashPushOptions,
1334) -> Result<()> {
1335    if !stash_push_pathspecs_active(options) {
1336        return Ok(());
1337    }
1338    let ctx = repo.pathspec_match_context();
1339    let index = repo.load_index()?;
1340    let index_owned = index_stage0_paths(&index);
1341    let index_paths: Vec<&str> = index_owned.iter().map(String::as_str).collect();
1342    for spec in &options.pathspecs {
1343        if pathspec_is_exclude(spec) {
1344            continue;
1345        }
1346        if positive_pathspec_matches_any_path(repo, spec, &index_paths, Some(&index), ctx, None)? {
1347            continue;
1348        }
1349        if options.include_untracked {
1350            let untracked = collect_untracked_paths(repo, work_tree)?;
1351            let untracked_refs: Vec<&str> = untracked.iter().map(String::as_str).collect();
1352            if positive_pathspec_matches_any_path(repo, spec, &untracked_refs, None, ctx, None)? {
1353                continue;
1354            }
1355            if !has_glob_chars(spec) && !spec.starts_with(':') && work_tree.join(spec).exists() {
1356                continue;
1357            }
1358        }
1359        return Err(Error::Worktree(WorktreeError::PathspecNoMatch {
1360            spec: spec.clone(),
1361        }));
1362    }
1363    Ok(())
1364}
1365
1366fn filter_paths_by_pathspec(
1367    repo: &Repository,
1368    pathspecs: &[String],
1369    paths: Vec<String>,
1370) -> Result<Vec<String>> {
1371    let index = repo.load_index()?;
1372    let matcher = pathspec_matcher(repo, pathspecs)?;
1373    Ok(paths
1374        .into_iter()
1375        .filter(|path| {
1376            let mode = index_stage0_mode_or_regular(&index, path);
1377            matcher.matches_entry(path, mode)
1378        })
1379        .collect())
1380}
1381
1382fn has_stashable_changes_for_pathspecs(
1383    repo: &Repository,
1384    work_tree: &Path,
1385    head_tree: &ObjectId,
1386    options: &StashPushOptions,
1387) -> Result<bool> {
1388    let matcher = pathspec_matcher(repo, &options.pathspecs)?;
1389    let mut index = repo.load_index()?;
1390    let staged = diff_index_to_tree(repo.odb(), &index, Some(head_tree), true)?;
1391    if staged
1392        .iter()
1393        .any(|e| matcher.matches_entry(e.path(), diff_entry_path_mode(e)))
1394    {
1395        return Ok(true);
1396    }
1397    let diff_opts = stash_worktree_diff_opts(repo, &index, Some(&options.pathspecs))?;
1398    let (unstaged, _) =
1399        diff_index_to_worktree_with_options(repo.odb(), &mut index, work_tree, diff_opts)?;
1400    if unstaged
1401        .iter()
1402        .any(|e| matcher.matches_entry(e.path(), diff_entry_path_mode(e)))
1403    {
1404        return Ok(true);
1405    }
1406    if options.include_untracked {
1407        let untracked = filter_paths_by_pathspec(
1408            repo,
1409            &options.pathspecs,
1410            collect_untracked_paths(repo, work_tree)?,
1411        )?;
1412        if !untracked.is_empty() {
1413            return Ok(true);
1414        }
1415    }
1416    Ok(false)
1417}
1418
1419fn apply_worktree_diff_to_index_for_pathspecs(
1420    repo: &Repository,
1421    work_tree: &Path,
1422    index: &mut Index,
1423    pathspecs: &[String],
1424    scope: &mut ProgressScope<'_>,
1425) -> Result<()> {
1426    let matcher = pathspec_matcher(repo, pathspecs)?;
1427    let index_mtime = index_file_mtime(&repo.index_path());
1428    let diff_opts = stash_worktree_diff_opts(repo, index, Some(pathspecs))?;
1429    let (unstaged, _) =
1430        diff_index_to_worktree_with_options(repo.odb(), index, work_tree, diff_opts)?;
1431    let mut worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
1432    let precompose = crate::precompose_config::effective_core_precomposeunicode_with_config(
1433        Some(repo.git_dir()),
1434        Some(&worktree_rules.config_arc()),
1435    );
1436    scope
1437        .sink()
1438        .start(ProgressPhase::StagingFiles, Some(unstaged.len() as u64));
1439    for entry in unstaged {
1440        scope.poll()?;
1441        scope.sink().inc(1);
1442        let path = entry.path();
1443        let mode = index_stage0_mode_or_regular(index, path);
1444        if !matcher.matches_entry(path, mode) {
1445            continue;
1446        }
1447        if entry.status == DiffStatus::Deleted {
1448            index.remove(storage_bytes(path).as_ref());
1449            continue;
1450        }
1451        stage_tracked_path_for_stash(
1452            repo,
1453            work_tree,
1454            path,
1455            index,
1456            index_mtime,
1457            &mut worktree_rules,
1458            precompose,
1459        )?;
1460    }
1461    scope.sink().finish();
1462    Ok(())
1463}
1464
1465fn pathspecs_for_push_reset(
1466    repo: &Repository,
1467    head_tree: &ObjectId,
1468    pathspecs: &[String],
1469) -> Result<Vec<String>> {
1470    let protect = crate::path_validate::ProtectOptions::from_config(&*repo.config().snapshot()?);
1471    let head_entries = flatten_tree_full(repo.odb(), head_tree, "", protect)?;
1472    let head_match_entries: Vec<PathspecMatchEntry<'_>> = head_entries
1473        .iter()
1474        .map(|e| PathspecMatchEntry {
1475            path: e.path.as_str(),
1476            mode: e.mode,
1477        })
1478        .collect();
1479    let index = repo.load_index()?;
1480    let index_owned = index_stage0_paths(&index);
1481    let index_paths: Vec<&str> = index_owned.iter().map(String::as_str).collect();
1482    let index_match_entries = pathspec_entries_from_paths(&index_paths, Some(&index));
1483    let ctx = repo.pathspec_match_context();
1484    let mut kept = Vec::new();
1485    for spec in pathspecs {
1486        if pathspec_is_exclude(spec) {
1487            continue;
1488        }
1489        if positive_spec_matches_any_entries(repo, spec, &head_match_entries, ctx, None)?
1490            || positive_spec_matches_any_entries(repo, spec, &index_match_entries, ctx, None)?
1491        {
1492            kept.push(spec.clone());
1493        }
1494    }
1495    Ok(kept)
1496}
1497
1498fn reset_stash_push_pathspecs_to_head(
1499    repo: &Repository,
1500    head_tree: &ObjectId,
1501    pathspecs: &[String],
1502    lock: &mut IndexLock,
1503    progress: &mut dyn ProgressSink,
1504    cancel: &CancelToken,
1505) -> Result<()> {
1506    if pathspecs.is_empty() {
1507        return Ok(());
1508    }
1509    let opts = RestoreOptions {
1510        pathspecs: pathspecs.to_vec(),
1511        pathspec_sources: pathspecs.to_vec(),
1512        source: RestoreSource::Tree(*head_tree),
1513        staged: true,
1514        worktree: true,
1515        stage: None,
1516        remerge: None,
1517    };
1518    restore_paths_with_lock(repo, &opts, lock, repo.load_index()?, progress, cancel)?;
1519    Ok(())
1520}
1521
1522fn merge_stash_index_trees(
1523    repo: &Repository,
1524    base_tree: &ObjectId,
1525    current_index_tree: &ObjectId,
1526    stash_index_tree: &ObjectId,
1527) -> crate::error::Result<Option<ObjectId>> {
1528    if base_tree == stash_index_tree || current_index_tree == stash_index_tree {
1529        return Ok(None);
1530    }
1531    let output = merge_trees_three_way(
1532        repo,
1533        *base_tree,
1534        *current_index_tree,
1535        *stash_index_tree,
1536        MergeFavor::None,
1537        WhitespaceMergeOptions::default(),
1538        None,
1539        TreeMergeConflictPresentation {
1540            label_ours: "Current index",
1541            label_theirs: crate::merge_trees::TheirsConflictLabel::Fixed("Stashed index changes"),
1542            label_base: "Stash base",
1543            ..TreeMergeConflictPresentation::default()
1544        },
1545        DirectoryRenameMode::Off,
1546    )?;
1547    if output.index.entries.iter().any(|entry| entry.stage() != 0) {
1548        return Err(StashError::IndexConflict.into());
1549    }
1550    Ok(Some(output.result_tree))
1551}
1552
1553fn resolve_partial_stash(
1554    repo: &Repository,
1555    options: &StashPushOptions,
1556) -> Result<Option<ResolvedSelection>> {
1557    if !selection_is_active(options) {
1558        return Ok(None);
1559    }
1560    let Some(sel) = options.selection.as_ref() else {
1561        return Ok(None);
1562    };
1563    Ok(Some(resolve_unstaged_selection(
1564        repo,
1565        sel,
1566        &options.pathspecs,
1567    )?))
1568}
1569
1570fn build_stash_commit(
1571    repo: &Repository,
1572    work_tree: &Path,
1573    options: &StashPushOptions,
1574    scope: &mut ProgressScope<'_>,
1575) -> crate::error::Result<Option<BuiltStash>> {
1576    options.validate().map_err(StashError::from)?;
1577    let head = resolve_head_for_repository(repo)?;
1578    let head_oid = head_commit_oid(&head)?;
1579    let head_tree = repo.odb().commit_tree(&head_oid)?;
1580    options.validate_staged_worktree(repo, work_tree, &head_tree)?;
1581    let identity = options.identity.header_line();
1582
1583    let pathspec_push = stash_push_pathspecs_active(options);
1584    if pathspec_push {
1585        validate_stash_push_pathspecs(repo, work_tree, options)?;
1586    }
1587
1588    let partial = resolve_partial_stash(repo, options)?;
1589    let mut reusable_unstaged = None;
1590    if let Some(ref partial) = partial {
1591        if partial.patches.is_empty() {
1592            return Ok(None);
1593        }
1594    } else if pathspec_push {
1595        if !has_stashable_changes_for_pathspecs(repo, work_tree, &head_tree, options)? {
1596            return Ok(None);
1597        }
1598    } else {
1599        match has_stashable_changes(repo, work_tree, &head_tree, options)? {
1600            StashableChanges::Nothing => return Ok(None),
1601            StashableChanges::Found { unstaged } => reusable_unstaged = unstaged,
1602        }
1603    }
1604
1605    let context = stash_context_message(repo, &head, &head_oid)?;
1606    let mut index = repo.load_index()?;
1607    let staged_only_paths = if options.mode == StashMode::StagedOnly {
1608        staged_change_paths_for_options(repo, &index, &head_tree, options)?
1609    } else {
1610        Vec::new()
1611    };
1612    if options.mode == StashMode::StagedOnly && staged_only_paths.is_empty() {
1613        return Ok(None);
1614    }
1615    let i_tree = write_stash_tree_from_index(repo, &mut index)?;
1616
1617    let index_msg = format!("index on {context}\n");
1618    let i_commit_data = CommitData {
1619        tree: i_tree,
1620        parents: vec![head_oid],
1621        author: identity.clone(),
1622        committer: identity.clone(),
1623        author_raw: Vec::new(),
1624        committer_raw: Vec::new(),
1625        encoding: None,
1626        message: index_msg,
1627        raw_message: None,
1628        extra_headers: Vec::new(),
1629    };
1630    let i_commit = write_commit_object(repo, &i_commit_data, STASH_COMMIT_SIGNING)?;
1631
1632    let untracked_paths = if options.include_untracked {
1633        let all = collect_untracked_paths(repo, work_tree)?;
1634        if pathspec_push {
1635            filter_paths_by_pathspec(repo, &options.pathspecs, all)?
1636        } else {
1637            all
1638        }
1639    } else {
1640        Vec::new()
1641    };
1642    let u_commit = if untracked_paths.is_empty() {
1643        None
1644    } else {
1645        Some(write_untracked_stash_commit(
1646            repo,
1647            work_tree,
1648            &untracked_paths,
1649            &context,
1650            &identity,
1651        )?)
1652    };
1653
1654    let w_tree = if options.mode == StashMode::StagedOnly {
1655        i_tree
1656    } else {
1657        // Seeding stat data from the index I was written from lets the worktree diff below hash
1658        // only files whose stat changed, and the primed cache-tree limits the W tree write to
1659        // the directories those files invalidate.
1660        let mut w_index = index_from_tree_with_seeded_stats(repo, &i_tree, &index)?;
1661        if let Some(ref partial) = partial {
1662            apply_patch_to_index(
1663                repo,
1664                &mut w_index,
1665                &partial.patches,
1666                &IndexApplyOptions {
1667                    dry_run: false,
1668                    reverse: false,
1669                    head_tree_oid: None,
1670                },
1671            )
1672            .map_err(StashError::Apply)?;
1673        } else if pathspec_push {
1674            apply_worktree_diff_to_index_for_pathspecs(
1675                repo,
1676                work_tree,
1677                &mut w_index,
1678                &options.pathspecs,
1679                scope,
1680            )?;
1681        } else {
1682            apply_worktree_diff_to_index(repo, work_tree, &mut w_index, reusable_unstaged, scope)?;
1683        }
1684        write_stash_tree_from_index(repo, &mut w_index)?
1685    };
1686
1687    let w_message = match &options.message {
1688        Some(msg) => format!("On {}: {}\n", head_branch_label(&head), msg),
1689        None => format!("WIP on {context}\n"),
1690    };
1691
1692    let mut parents = vec![head_oid, i_commit];
1693    if let Some(u) = u_commit {
1694        parents.push(u);
1695    }
1696    let w_commit_data = CommitData {
1697        tree: w_tree,
1698        parents,
1699        author: identity.clone(),
1700        committer: identity.clone(),
1701        author_raw: Vec::new(),
1702        committer_raw: Vec::new(),
1703        encoding: None,
1704        message: w_message.clone(),
1705        raw_message: None,
1706        extra_headers: Vec::new(),
1707    };
1708    let w_commit = write_commit_object(repo, &w_commit_data, STASH_COMMIT_SIGNING)?;
1709
1710    Ok(Some(BuiltStash {
1711        w_commit,
1712        w_tree,
1713        i_tree,
1714        message: w_message.trim_end().to_owned(),
1715        untracked_paths,
1716        partial,
1717        push_pathspecs: if pathspec_push {
1718            options.pathspecs.clone()
1719        } else {
1720            Vec::new()
1721        },
1722        staged_only_paths,
1723        mode: options.mode,
1724    }))
1725}
1726
1727/// Create a Git-compatible stash commit without updating `refs/stash`.
1728///
1729/// Returns `None` when the index and worktree match `HEAD` and there are no
1730/// untracked paths to save (unless `include_untracked` finds untracked files).
1731///
1732/// The stash commits are never signed, even when `commit.gpgsign` is set (Git
1733/// creates them unsigned too).
1734///
1735/// # Errors
1736///
1737/// Returns [`StashError::NoInitialCommit`] when `HEAD` does not resolve to a commit,
1738/// or propagates index, diff, and object-database failures.
1739pub(crate) fn create_stash(
1740    repo: &Repository,
1741    options: &StashPushOptions,
1742) -> crate::error::Result<Option<ObjectId>> {
1743    let work_tree = repo.work_tree().ok_or(StashError::BareRepository)?;
1744    let mut progress = NullProgress;
1745    let mut scope = ProgressScope::new(&mut progress, CancelToken::never_ref());
1746    Ok(build_stash_commit(repo, work_tree, options, &mut scope)?.map(|b| b.w_commit))
1747}
1748
1749/// Point `refs/stash` at `oid` and append a reflog entry with `message`.
1750///
1751/// # Errors
1752///
1753/// Propagates ref and reflog update failures.
1754pub(crate) fn store_stash(
1755    repo: &Repository,
1756    oid: ObjectId,
1757    message: &str,
1758    identity: &str,
1759) -> Result<()> {
1760    let old_oid = repo
1761        .resolve_ref_oid(STASH_REF)
1762        .unwrap_or_else(|_| ObjectId::zero());
1763    update_direct_ref_on_store(repo.ref_store(), repo.git_dir(), STASH_REF, &oid)?;
1764    append_reflog_on_store(
1765        repo.ref_store(),
1766        STASH_REF,
1767        &old_oid,
1768        &oid,
1769        identity,
1770        message,
1771        true,
1772        repo.config().snapshot()?.as_ref(),
1773    )
1774}
1775
1776/// Result of a successful [`RepositoryStash::push`](crate::repo_handles::RepositoryStash::push).
1777#[derive(Debug, Clone, PartialEq, Eq)]
1778pub struct StashPushResult {
1779    /// The W commit object id stored on `refs/stash`.
1780    pub oid: ObjectId,
1781    /// Reflog-style message stored on `refs/stash`.
1782    pub message: String,
1783    /// Tree recorded on the W commit.
1784    pub w_tree: ObjectId,
1785    /// For a partial push ([`StashPushOptions::selection`]), the hunk ids that were stashed, per
1786    /// repository-relative path. Empty otherwise.
1787    pub stashed_hunks: BTreeMap<String, Vec<HunkId>>,
1788    /// For a partial push, the requested line range labels (`start` or `start-end`) that were
1789    /// stashed, per path. Empty otherwise.
1790    pub stashed_lines: BTreeMap<String, Vec<String>>,
1791}
1792
1793/// Create a stash entry, store it, and reset the worktree and index to `HEAD`.
1794///
1795/// Returns `None` when there is nothing to stash. Untracked paths included in
1796/// the stash are removed from the worktree after the reset. Like
1797/// [`create_stash`], the stash commits are written unsigned.
1798///
1799/// `index.lock` is held from before the index is read until the reset index is written, so
1800/// a lock held by another process refuses the push before any object, ref or file is written.
1801/// Once `refs/stash` is updated, the entry stays there even if the reset fails, so the saved
1802/// changes remain reachable.
1803///
1804/// Hashing work-tree changes reports [`ProgressPhase::StagingFiles`] and the reset reports
1805/// [`ProgressPhase::CheckingOutFiles`]. A cancel before `refs/stash` is updated leaves the
1806/// repository as it was (stash objects already written stay unreachable); a cancel during
1807/// the reset keeps the stored entry, like a failed reset.
1808///
1809/// # Errors
1810///
1811/// [`Error::LockHeld`] when another process holds `index.lock`, with the repository
1812/// unchanged; [`crate::error::Error::Cancelled`] when `cancel` or [`ProgressSink::should_cancel`] fired;
1813/// otherwise the same as [`create_stash`] and [`store_stash`], plus checkout failures.
1814pub(crate) fn push_stash(
1815    repo: &Repository,
1816    options: &StashPushOptions,
1817    progress: &mut dyn ProgressSink,
1818    cancel: &CancelToken,
1819) -> crate::error::Result<Option<StashPushResult>> {
1820    if options.dry_run {
1821        return Err(StashError::PushValidation(StashPushValidationError::DryRunUsePreview).into());
1822    }
1823    options.validate()?;
1824    let work_tree = repo.work_tree().ok_or(StashError::BareRepository)?;
1825    let mut lock = repo.lock_index()?;
1826    let mut scope = ProgressScope::new(progress, cancel);
1827    poll_stash(&mut scope)?;
1828    let Some(built) = build_stash_commit(repo, work_tree, options, &mut scope)? else {
1829        return Ok(None);
1830    };
1831    poll_stash(&mut scope)?;
1832    store_stash(
1833        repo,
1834        built.w_commit,
1835        &built.message,
1836        &options.identity.header_line(),
1837    )?;
1838    reset_after_stash_push(repo, work_tree, &built, &mut lock, scope.sink(), cancel)?;
1839    let (stashed_hunks, stashed_lines) = built
1840        .partial
1841        .map(|partial| (partial.selected_hunks, partial.selected_lines))
1842        .unwrap_or_default();
1843    Ok(Some(StashPushResult {
1844        oid: built.w_commit,
1845        message: built.message,
1846        w_tree: built.w_tree,
1847        stashed_hunks,
1848        stashed_lines,
1849    }))
1850}
1851
1852/// Remove the stashed changes from the worktree and index, writing the index through `lock`.
1853fn reset_after_stash_push(
1854    repo: &Repository,
1855    work_tree: &Path,
1856    built: &BuiltStash,
1857    lock: &mut IndexLock,
1858    progress: &mut dyn ProgressSink,
1859    cancel: &CancelToken,
1860) -> crate::error::Result<()> {
1861    if !built.untracked_paths.is_empty() {
1862        remove_stashed_untracked(repo, work_tree, &built.untracked_paths)?;
1863    }
1864    if let Some(ref partial) = built.partial {
1865        return reverse_apply_patches_to_worktree(
1866            repo,
1867            &partial.patches,
1868            &WorktreeReverseApplyOptions { dry_run: false },
1869            progress,
1870            cancel,
1871        )
1872        .map_err(stash_worktree_step_error);
1873    }
1874    let head = resolve_head_for_repository(repo)?;
1875    let head_oid = head_commit_oid(&head)?;
1876    let head_tree = repo.odb().commit_tree(&head_oid)?;
1877    if !built.push_pathspecs.is_empty() {
1878        let reset_specs = pathspecs_for_push_reset(repo, &head_tree, &built.push_pathspecs)?;
1879        reset_stash_push_pathspecs_to_head(repo, &head_tree, &reset_specs, lock, progress, cancel)?;
1880        if built.mode == StashMode::StagedOnly {
1881            let index = repo.load_index()?;
1882            let all_staged = staged_change_paths(repo, &index, &head_tree)?;
1883            let stashed_set: HashSet<&str> =
1884                built.staged_only_paths.iter().map(String::as_str).collect();
1885            let worktree_only: Vec<String> = all_staged
1886                .into_iter()
1887                .filter(|path| !stashed_set.contains(path.as_str()))
1888                .collect();
1889            apply_staged_worktree_only_reset(
1890                repo,
1891                work_tree,
1892                &head_tree,
1893                &worktree_only,
1894                progress,
1895                cancel,
1896            )?;
1897        }
1898        return Ok(());
1899    }
1900    match built.mode {
1901        StashMode::StagedOnly => apply_staged_only_reset(
1902            repo,
1903            work_tree,
1904            &head_tree,
1905            &built.staged_only_paths,
1906            lock,
1907            progress,
1908            cancel,
1909        ),
1910        StashMode::KeepIndex => checkout_between_trees_locked(
1911            repo,
1912            &built.w_tree,
1913            &built.i_tree,
1914            None,
1915            CheckoutIndexWrite::Commit(lock),
1916            progress,
1917            cancel,
1918        ),
1919        StashMode::All => {
1920            let mut checked_out = repo.load_index()?;
1921            checkout_between_trees_locked(
1922                repo,
1923                &built.w_tree,
1924                &head_tree,
1925                Some(&mut checked_out),
1926                CheckoutIndexWrite::Defer(lock),
1927                progress,
1928                cancel,
1929            )?;
1930            // The checkout left fresh stat data for every path it rewrote; reuse it so the
1931            // refresh only hashes files whose stat does not match.
1932            let mut head_index =
1933                index_from_tree_with_seeded_worktree_stats(repo, &head_tree, &checked_out)?;
1934            drop(checked_out);
1935            repo.write_index_with_lock(lock, &mut head_index, true)
1936        }
1937    }
1938}
1939
1940fn stash_worktree_step_error(err: ApplyError) -> crate::error::Error {
1941    StashError::from_apply_worktree(err)
1942}
1943
1944fn materialize_stash_blob_err(err: Error, index_relpath: &str) -> Error {
1945    match err {
1946        Error::Io(source) => map_worktree_io(index_relpath, WorktreePathOperation::Read, source),
1947        other => other,
1948    }
1949}
1950
1951/// List stash entries from `refs/stash` reflog (newest first).
1952///
1953/// # Errors
1954///
1955/// Propagates reflog read failures.
1956pub(crate) fn list_stashes(repo: &Repository) -> crate::error::Result<Vec<StashEntry>> {
1957    let entries = read_reflog_on_store(repo.ref_store(), STASH_REF)?;
1958    Ok(entries
1959        .into_iter()
1960        .rev()
1961        .enumerate()
1962        .map(|(i, e)| StashEntry {
1963            index: i,
1964            oid: e.new_oid,
1965            message: e.message,
1966        })
1967        .collect())
1968}
1969
1970pub(crate) fn stash_oid_at(repo: &Repository, n: usize) -> crate::error::Result<ObjectId> {
1971    let entries = list_stashes(repo)?;
1972    entries
1973        .into_iter()
1974        .find(|e| e.index == n)
1975        .map(|e| e.oid)
1976        .ok_or(crate::error::Error::from(StashError::NotFound { n }))
1977}
1978
1979/// Remove `stash@{{n}}` from the reflog and move `refs/stash` to the next entry.
1980///
1981/// Deletes `refs/stash` when the reflog becomes empty.
1982///
1983/// # Errors
1984///
1985/// Returns [`StashError::NotFound`] when `n` is out of range.
1986pub(crate) fn drop_stash(repo: &Repository, n: usize) -> crate::error::Result<ObjectId> {
1987    let oid = stash_oid_at(repo, n)?;
1988    let store = repo.ref_store();
1989    delete_reflog_entries_rechain_on_store(store, STASH_REF, &[n])?;
1990    let remaining = read_reflog_on_store(store, STASH_REF)?;
1991    if let Some(top_entry) = remaining.last() {
1992        update_direct_ref_on_store(store, repo.git_dir(), STASH_REF, &top_entry.new_oid)?;
1993    } else {
1994        delete_ref_on_store(store, STASH_REF)?;
1995    }
1996    Ok(oid)
1997}
1998
1999/// Tree diff of stash W against its `HEAD` parent (`stash show` without `--index`).
2000///
2001/// When [`StashDiffOptions::include_untracked`] is set, paths from the U parent that were
2002/// not in the base tree are appended as [`DiffStatus::Added`] entries (matching
2003/// `git stash show -u`).
2004///
2005/// # Errors
2006///
2007/// Returns [`StashError::NotFound`] or [`StashError::CorruptStash`] when the entry is invalid.
2008pub(crate) fn stash_diff(
2009    repo: &Repository,
2010    n: usize,
2011    options: &StashDiffOptions,
2012) -> crate::error::Result<Vec<DiffEntry>> {
2013    let oid = stash_oid_at(repo, n)?;
2014    let stash_commit = repo.odb().read_commit(&oid)?;
2015    let head_parent = stash_commit
2016        .parents
2017        .first()
2018        .ok_or_else(|| corrupt_stash_commit(oid))?;
2019    let head_tree = repo.odb().commit_tree(head_parent)?;
2020    let mut diffs = diff_trees(repo.odb(), Some(&head_tree), Some(&stash_commit.tree), "")?;
2021    if options.include_untracked {
2022        append_stash_untracked_show_entries(repo, &head_tree, &stash_commit, &mut diffs)?;
2023    }
2024    sort_entries_by_path(&mut diffs);
2025    Ok(diffs)
2026}
2027
2028pub(crate) fn stash_diff_stat(
2029    repo: &Repository,
2030    n: usize,
2031    options: &StashDiffOptions,
2032    diff_options: DiffOptions,
2033) -> crate::error::Result<DiffStat> {
2034    let entries = stash_diff(repo, n, options)?;
2035    let config = repo.config().snapshot()?;
2036    let whitespace = diff_options.whitespace;
2037    let output = build_file_diffs(
2038        repo.odb(),
2039        entries,
2040        DiffDetail::Stat,
2041        diff_options,
2042        &config,
2043        &repo.thread_policy(),
2044    )?;
2045    Ok(output
2046        .files
2047        .iter()
2048        .filter(|file| !file.changes_all_ignored(whitespace))
2049        .map(FileStat::from)
2050        .collect())
2051}
2052
2053fn append_stash_untracked_show_entries(
2054    repo: &Repository,
2055    head_tree: &ObjectId,
2056    stash_commit: &CommitData,
2057    diffs: &mut Vec<DiffEntry>,
2058) -> Result<()> {
2059    if stash_commit.parents.len() < 3 {
2060        return Ok(());
2061    }
2062    let ut_oid = &stash_commit.parents[2];
2063    let ut_tree = repo.odb().commit_tree(ut_oid)?;
2064    let head_entries = flatten_tree_full_for_repo(repo, head_tree, "")?;
2065    let ut_entries = flatten_tree_full_for_repo(repo, &ut_tree, "")?;
2066    for entry in ut_entries {
2067        if let Some(idx) = diffs.iter().position(|d| d.path() == entry.path.as_str()) {
2068            if diffs[idx].status == DiffStatus::Deleted {
2069                let head_entry = flat_tree_lookup(&head_entries, &entry.path);
2070                let (old_oid, old_mode, status) = if let Some(h) = head_entry {
2071                    (
2072                        h.oid,
2073                        FileMode::new(h.mode),
2074                        DiffStatus::for_content_change(h.mode, entry.mode),
2075                    )
2076                } else {
2077                    (zero_oid(), FileMode::ABSENT, DiffStatus::Modified)
2078                };
2079                diffs[idx] = DiffEntry {
2080                    status,
2081                    old_path: Some(entry.path.clone()),
2082                    new_path: Some(entry.path.clone()),
2083                    old_mode,
2084                    new_mode: FileMode::new(entry.mode),
2085                    old_oid,
2086                    new_oid: entry.oid,
2087                    score: None,
2088                };
2089            }
2090            continue;
2091        }
2092        diffs.push(DiffEntry {
2093            status: DiffStatus::Added,
2094            old_path: None,
2095            new_path: Some(entry.path.clone()),
2096            old_mode: FileMode::ABSENT,
2097            new_mode: FileMode::new(entry.mode),
2098            old_oid: zero_oid(),
2099            new_oid: entry.oid,
2100            score: None,
2101        });
2102    }
2103    diffs.sort_by(|a, b| a.path().cmp(b.path()));
2104    Ok(())
2105}
2106
2107/// Create `refs/heads/<name>` at the stash base commit, check it out, apply with `--index`, and drop on success.
2108///
2109/// # Errors
2110///
2111/// Returns [`BranchError::AlreadyExists`] when the branch name is taken,
2112/// [`StashError::NotFound`] when `n` is out of range, and apply/switch failures otherwise.
2113pub(crate) fn stash_branch(
2114    repo: &Repository,
2115    name: &str,
2116    n: usize,
2117) -> crate::error::Result<StashBranchOutcome> {
2118    RefName::branch(name).map_err(|reason| BranchError::InvalidName {
2119        name: name.to_owned(),
2120        reason: reason.to_string(),
2121    })?;
2122    let branch_ref = format!("refs/heads/{name}");
2123    if repo.resolve_ref_oid(&branch_ref).is_ok() {
2124        return Err(BranchError::AlreadyExists {
2125            name: name.to_owned(),
2126        }
2127        .into());
2128    }
2129    if repo.work_tree().is_none() {
2130        return Err(StashError::BareRepository.into());
2131    }
2132    let stash_oid = stash_oid_at(repo, n)?;
2133    let stash_commit = repo.odb().read_commit(&stash_oid)?;
2134    let base = *stash_commit
2135        .parents
2136        .first()
2137        .ok_or_else(|| corrupt_stash_commit(stash_oid))?;
2138
2139    switch_repository(
2140        repo,
2141        &SwitchOptions {
2142            mode: SwitchMode::Create {
2143                branch: name.to_owned(),
2144                start_oid: base,
2145                create_source_label: format!("stash@{{{n}}}"),
2146                track_upstream: None,
2147            },
2148            dry_run: false,
2149            hooks: crate::hooks::PostOperationHooks::Run,
2150        },
2151        &mut crate::progress::NullProgress,
2152        &crate::progress::CancelToken::never(),
2153    )?;
2154
2155    let applied = apply_stash_entry(
2156        repo,
2157        n,
2158        &StashApplyOptions {
2159            restore_index: true,
2160            ..Default::default()
2161        },
2162        &mut NullProgress,
2163        CancelToken::never_ref(),
2164    )?;
2165    if !applied.has_conflicts() {
2166        drop_stash(repo, n)?;
2167    }
2168    Ok(StashBranchOutcome {
2169        branch: name.to_owned(),
2170        base,
2171        stash_oid,
2172        index: Some(n),
2173        conflicts: applied.has_conflicts(),
2174        conflict_paths: applied.conflicts.into_iter().map(|c| c.path).collect(),
2175    })
2176}
2177
2178fn stash_branch_from_commit(
2179    repo: &Repository,
2180    name: &str,
2181    stash_oid: ObjectId,
2182) -> crate::error::Result<StashBranchOutcome> {
2183    RefName::branch(name).map_err(|reason| BranchError::InvalidName {
2184        name: name.to_owned(),
2185        reason: reason.to_string(),
2186    })?;
2187    let branch_ref = format!("refs/heads/{name}");
2188    if repo.resolve_ref_oid(&branch_ref).is_ok() {
2189        return Err(BranchError::AlreadyExists {
2190            name: name.to_owned(),
2191        }
2192        .into());
2193    }
2194    if repo.work_tree().is_none() {
2195        return Err(StashError::BareRepository.into());
2196    }
2197    let stash_commit = repo.odb().read_commit(&stash_oid)?;
2198    let base = *stash_commit
2199        .parents
2200        .first()
2201        .ok_or_else(|| corrupt_stash_commit(stash_oid))?;
2202
2203    switch_repository(
2204        repo,
2205        &SwitchOptions {
2206            mode: SwitchMode::Create {
2207                branch: name.to_owned(),
2208                start_oid: base,
2209                create_source_label: stash_oid.to_short_hex(),
2210                track_upstream: None,
2211            },
2212            dry_run: false,
2213            hooks: crate::hooks::PostOperationHooks::Run,
2214        },
2215        &mut crate::progress::NullProgress,
2216        &crate::progress::CancelToken::never(),
2217    )?;
2218
2219    let applied = apply_stash_oid(
2220        repo,
2221        &stash_oid,
2222        &StashApplyOptions {
2223            restore_index: true,
2224            ..Default::default()
2225        },
2226        &mut NullProgress,
2227        CancelToken::never_ref(),
2228    )?;
2229    Ok(StashBranchOutcome {
2230        branch: name.to_owned(),
2231        base,
2232        stash_oid,
2233        index: None,
2234        conflicts: applied.has_conflicts(),
2235        conflict_paths: applied.conflicts.into_iter().map(|c| c.path).collect(),
2236    })
2237}
2238
2239/// Apply a parsed stash reference without dropping it.
2240pub(crate) fn apply_stash_reference(
2241    repo: &Repository,
2242    reference: StashReference,
2243    options: &StashApplyOptions,
2244    progress: &mut dyn ProgressSink,
2245    cancel: &CancelToken,
2246) -> crate::error::Result<StashApplyOutcome> {
2247    match reference {
2248        StashReference::Index(n) => apply_stash_entry(repo, n, options, progress, cancel),
2249        StashReference::Commit(oid) => apply_stash_oid(repo, &oid, options, progress, cancel),
2250    }
2251}
2252
2253/// Pop a parsed stash reference; commit ids must still be on `refs/stash`.
2254pub(crate) fn pop_stash_reference(
2255    repo: &Repository,
2256    reference: StashReference,
2257    options: &StashApplyOptions,
2258    progress: &mut dyn ProgressSink,
2259    cancel: &CancelToken,
2260) -> crate::error::Result<StashApplyOutcome> {
2261    let index = match reference {
2262        StashReference::Index(n) => n,
2263        StashReference::Commit(oid) => {
2264            stash_index_for_oid(repo, &oid).ok_or(StashError::CommitNotOnStack { oid })?
2265        }
2266    };
2267    pop_stash_entry(repo, index, options, progress, cancel)
2268}
2269
2270/// Branch from a parsed stash reference (on- or off-stack).
2271pub(crate) fn stash_branch_reference(
2272    repo: &Repository,
2273    name: &str,
2274    reference: StashReference,
2275) -> crate::error::Result<StashBranchOutcome> {
2276    match reference {
2277        StashReference::Index(n) => stash_branch(repo, name, n),
2278        StashReference::Commit(oid) => {
2279            if let Some(n) = stash_index_for_oid(repo, &oid) {
2280                stash_branch(repo, name, n)
2281            } else {
2282                stash_branch_from_commit(repo, name, oid)
2283            }
2284        }
2285    }
2286}
2287
2288/// Delete `refs/stash` and its reflog, removing every stash entry.
2289///
2290/// # Returns
2291///
2292/// The number of reflog entries that were removed (0 when the reflog was already empty).
2293///
2294/// # Errors
2295///
2296/// Propagates ref store and reflog delete failures.
2297pub(crate) fn clear_stashes(repo: &Repository) -> crate::error::Result<usize> {
2298    let store = repo.ref_store();
2299    let count = read_reflog_on_store(store, STASH_REF)?.len();
2300    let has_ref = repo.resolve_ref_oid(STASH_REF).is_ok();
2301    if count == 0 && !has_ref {
2302        return Ok(0);
2303    }
2304    if count > 0 {
2305        store.delete_reflog(RefNameRef::from_trusted(STASH_REF))?;
2306    }
2307    if has_ref {
2308        delete_ref_on_store(store, STASH_REF)?;
2309    }
2310    Ok(count)
2311}
2312
2313/// One filter-free regular file applied from a stash tree blob via bulk checkout.
2314struct StashCheckoutJob<'a> {
2315    rel_path: &'a str,
2316    mode: u32,
2317    oid: ObjectId,
2318}
2319
2320/// Write one flattened tree entry into the worktree (blob, symlink, or gitlink).
2321fn write_smudged_regular_file_replacing_symlink(
2322    repo: &Repository,
2323    rules: &WorktreeRules,
2324    rel_path: &str,
2325    file_path: &Path,
2326    mode: u32,
2327    blob: &[u8],
2328    oid: &ObjectId,
2329) -> Result<()> {
2330    let worktree_bytes = smudge_bytes_for_worktree_path(repo, rules, rel_path, mode, blob, oid)?;
2331    write_regular_file_replacing_symlink(file_path, &worktree_bytes)?;
2332    #[cfg(unix)]
2333    {
2334        use std::os::unix::fs::PermissionsExt;
2335        if mode == MODE_EXECUTABLE {
2336            let perms = fs::Permissions::from_mode(0o755);
2337            fs::set_permissions(file_path, perms)?;
2338        }
2339    }
2340    Ok(())
2341}
2342
2343fn materialize_raw_flat_entry_in_worktree(
2344    repo: &Repository,
2345    work_tree: &Path,
2346    rules: &WorktreeRules,
2347    entry: &RawFlatTreeEntry,
2348) -> crate::error::Result<()> {
2349    let stored = storage_string(&entry.path);
2350    let file_path = worktree_abs(work_tree, &stored);
2351    if let Some(parent) = file_path.parent() {
2352        if let Ok(rel) = parent.strip_prefix(work_tree) {
2353            let mut cur = work_tree.to_path_buf();
2354            for comp in rel.components() {
2355                cur.push(comp);
2356                if cur.exists() && !cur.is_dir() {
2357                    let path = crate::repo_relpath::strip_worktree_prefix_stored(&cur, work_tree)
2358                        .unwrap_or_else(|| stored.clone());
2359                    return Err(StashError::CouldNotRestoreUntracked { path }.into());
2360                }
2361            }
2362        }
2363        fs::create_dir_all(parent)
2364            .map_err(|source| map_worktree_io(&stored, WorktreePathOperation::Create, source))?;
2365    }
2366    if entry.mode == MODE_GITLINK {
2367        fs::create_dir_all(&file_path)
2368            .map_err(|source| map_worktree_io(&stored, WorktreePathOperation::Create, source))?;
2369        return Ok(());
2370    }
2371    let blob = repo.odb().read(&entry.oid)?;
2372    if entry.mode == MODE_SYMLINK {
2373        let target = String::from_utf8(blob.data).map_err(|_| StashError::SymlinkNotUtf8)?;
2374        if file_path.exists() || file_path.symlink_metadata().is_ok() {
2375            let _ = fs::remove_file(&file_path);
2376        }
2377        let has_symlinks =
2378            crate::index::WorktreeModePolicy::from_config(rules.config()).has_symlinks;
2379        crate::worktree::write_index_symlink_to_worktree(&file_path, &target, has_symlinks)
2380            .map_err(Error::Io)?;
2381    } else {
2382        write_smudged_regular_file_replacing_symlink(
2383            repo, rules, &stored, &file_path, entry.mode, &blob.data, &entry.oid,
2384        )?;
2385    }
2386    Ok(())
2387}
2388
2389/// Whether the cached stat data of `ie` proves the worktree file still matches the index.
2390///
2391/// `false` means "unknown", not "modified": callers must fall back to a content comparison.
2392/// Racily clean entries (modified within the index file's mtime granularity) are never trusted.
2393fn index_entry_stat_clean(
2394    work_tree: &Path,
2395    ie: &IndexEntry,
2396    index_mtime: Option<(u32, u32)>,
2397    stat_policy: crate::index::StatMatchPolicy,
2398    trust_filemode: bool,
2399) -> bool {
2400    if ie.stat_cache_unset() || ie.mode == MODE_GITLINK {
2401        return false;
2402    }
2403    let Ok(rel) = std::str::from_utf8(&ie.path) else {
2404        return false;
2405    };
2406    let Ok(meta) = fs::symlink_metadata(work_tree.join(rel)) else {
2407        return false;
2408    };
2409    if meta.is_dir() || meta.file_type().is_symlink() != (ie.mode == MODE_SYMLINK) {
2410        return false;
2411    }
2412    if trust_filemode && crate::diff::mode_from_metadata(&meta) != ie.mode {
2413        return false;
2414    }
2415    crate::diff::stat_matches_with_policy(ie, &meta, stat_policy)
2416        && !crate::diff::entry_is_racy_with_policy(ie, index_mtime, stat_policy)
2417}
2418
2419/// Refuse to apply when the stash would clobber a locally-modified file.
2420pub fn check_stash_apply_would_overwrite_local_changes(
2421    repo: &Repository,
2422    work_tree: &Path,
2423    stash_commit: &CommitData,
2424) -> crate::error::Result<()> {
2425    let index = load_stash_index(repo)?;
2426    let head_at_stash = stash_commit
2427        .parents
2428        .first()
2429        .ok_or_else(|| corrupt_stash_commit(stash_commit.tree))?;
2430    let head_tree = repo.odb().commit_tree(head_at_stash)?;
2431    let delta = StashTreeDelta::read(repo, &head_tree, &stash_commit.tree)?;
2432    check_stash_local_changes(
2433        repo,
2434        work_tree,
2435        &index,
2436        delta.changes.iter().map(|(path, _)| path.as_slice()),
2437    )
2438}
2439
2440fn check_stash_local_changes<'a>(
2441    repo: &Repository,
2442    work_tree: &Path,
2443    current_index: &Index,
2444    paths: impl IntoIterator<Item = &'a [u8]>,
2445) -> crate::error::Result<()> {
2446    let config = repo.config().snapshot()?;
2447    let stat_policy = crate::index::StatMatchPolicy::from_config(Some(config.as_ref()));
2448    let trust_filemode = config.file_mode();
2449    let index_mtime = crate::diff::index_mtime_for_diff(current_index, None);
2450    let comparer =
2451        crate::diff::WorktreeEntryComparer::new(repo.git_dir(), work_tree, Some(config.as_ref()));
2452
2453    for path in paths {
2454        let Some(idx_entry) = current_index.get(path, 0) else {
2455            continue;
2456        };
2457        if idx_entry.mode == MODE_GITLINK {
2458            continue;
2459        }
2460        if index_entry_stat_clean(
2461            work_tree,
2462            idx_entry,
2463            index_mtime,
2464            stat_policy,
2465            trust_filemode,
2466        ) {
2467            continue;
2468        }
2469        if comparer.differs(repo.odb(), idx_entry, true, None)? {
2470            return Err(StashError::WouldOverwriteLocalChanges {
2471                paths: crate::repo_relpath::storage_string(path),
2472            }
2473            .into());
2474        }
2475    }
2476    Ok(())
2477}
2478
2479/// Worktree paths that would block materializing the stash untracked-files parent.
2480fn collect_worktree_paths_blocking_stash_untracked_restore(
2481    repo: &Repository,
2482    work_tree: &Path,
2483    index: &mut Index,
2484) -> Result<Vec<Vec<u8>>> {
2485    let mut paths = HashSet::new();
2486    for entry in index.entries() {
2487        if entry.stage() != 0 {
2488            continue;
2489        }
2490        let path = crate::repo_relpath::storage_string(&entry.path);
2491        let wt = crate::repo_relpath::worktree_abs(work_tree, &path);
2492        if wt.exists() || wt.symlink_metadata().is_ok() {
2493            paths.insert(entry.path.clone());
2494        }
2495    }
2496    let worktree_rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
2497    let (untracked, ignored, _) = collect_untracked_and_ignored_inner(
2498        repo,
2499        index,
2500        work_tree,
2501        &[],
2502        None,
2503        UntrackedScan {
2504            ignored_mode: IgnoredMode::Traditional,
2505            show_all: true,
2506            sort_paths: true,
2507            use_untracked_cache: false,
2508            cache_miss: UntrackedCacheMissAction::RefreshFull,
2509            clean_unit_dirs: None,
2510            listing_cache: None,
2511        },
2512        &worktree_rules,
2513        None,
2514    )?;
2515    for path in untracked.into_iter().chain(ignored) {
2516        paths.insert(storage_bytes(&path).into_owned());
2517    }
2518    let mut sorted: Vec<Vec<u8>> = paths.into_iter().collect();
2519    sorted.sort();
2520    Ok(sorted)
2521}
2522
2523fn is_component_prefix_bytes(prefix: &[u8], path: &[u8]) -> bool {
2524    if path.len() <= prefix.len() {
2525        return false;
2526    }
2527    path.starts_with(prefix) && path.get(prefix.len()) == Some(&b'/')
2528}
2529
2530fn added_stash_path_collides_with_worktree_path(added: &[u8], existing: &[u8]) -> bool {
2531    let existing = existing.strip_suffix(b"/").unwrap_or(existing);
2532    if existing.is_empty() {
2533        return false;
2534    }
2535    added == existing
2536        || is_component_prefix_bytes(added, existing)
2537        || is_component_prefix_bytes(existing, added)
2538}
2539
2540fn untracked_stash_restore_collisions(
2541    existing_paths: &[Vec<u8>],
2542    ut_entries: &[RawFlatTreeEntry],
2543) -> Vec<Vec<u8>> {
2544    let mut collisions = Vec::new();
2545    for entry in ut_entries {
2546        if entry.mode == MODE_GITLINK || entry.mode == MODE_TREE {
2547            continue;
2548        }
2549        let added = entry.path.as_slice();
2550        for existing in existing_paths {
2551            if added_stash_path_collides_with_worktree_path(added, existing) {
2552                collisions.push(added.to_vec());
2553            }
2554        }
2555    }
2556    collisions.sort();
2557    collisions.dedup();
2558    collisions
2559}
2560
2561/// Refuse when restoring the stash untracked-files parent would clobber an existing worktree path.
2562///
2563/// Must run before any worktree or index mutations in [`apply_stash_oid`].
2564///
2565/// # Errors
2566///
2567/// Returns [`StashError::CouldNotRestoreUntracked`] when a path from the untracked parent
2568/// collides with tracked, untracked, or ignored content already on disk.
2569fn check_stash_untracked_restore(
2570    repo: &Repository,
2571    work_tree: &Path,
2572    stash_commit: &CommitData,
2573    index: &mut Index,
2574    wt_deletions: &BTreeSet<Vec<u8>>,
2575    options: &StashApplyOptions,
2576) -> crate::error::Result<()> {
2577    if stash_commit.parents.len() < 3 {
2578        return Ok(());
2579    }
2580    let ut_oid = &stash_commit.parents[2];
2581    let ut_tree = repo.odb().commit_tree(ut_oid)?;
2582    let ut_entries = flatten_tree_full_raw_for_repo(repo, &ut_tree)?;
2583    if ut_entries.is_empty() {
2584        return Ok(());
2585    }
2586    let ut_file_paths: HashSet<&[u8]> = ut_entries
2587        .iter()
2588        .filter(|e| e.mode != MODE_GITLINK && e.mode != MODE_TREE)
2589        .map(|e| e.path.as_slice())
2590        .collect();
2591    let existing_paths: Vec<Vec<u8>> =
2592        collect_worktree_paths_blocking_stash_untracked_restore(repo, work_tree, index)?
2593            .into_iter()
2594            .filter(|path_bytes| {
2595                for ut_file in &ut_file_paths {
2596                    if path_bytes.as_slice() != *ut_file
2597                        && is_component_prefix_bytes(ut_file, path_bytes)
2598                        && wt_deletions.contains(path_bytes)
2599                    {
2600                        return false;
2601                    }
2602                }
2603                true
2604            })
2605            .collect();
2606    let collisions = untracked_stash_restore_collisions(&existing_paths, &ut_entries);
2607    for path_bytes in collisions {
2608        let path = storage_string(&path_bytes);
2609        if options.overwrite_identical_untracked
2610            && untracked_on_disk_matches_stash(repo, work_tree, index, ut_oid, &ut_entries, &path)?
2611        {
2612            continue;
2613        }
2614        return Err(StashError::CouldNotRestoreUntracked { path }.into());
2615    }
2616    Ok(())
2617}
2618
2619fn untracked_on_disk_matches_stash(
2620    repo: &Repository,
2621    work_tree: &Path,
2622    index: &Index,
2623    ut_commit: &ObjectId,
2624    ut_entries: &[RawFlatTreeEntry],
2625    path: &str,
2626) -> Result<bool> {
2627    let _ = ut_commit;
2628    let Some(entry) = ut_entries.iter().find(|e| storage_string(&e.path) == path) else {
2629        return Ok(false);
2630    };
2631    if entry.mode == MODE_GITLINK || entry.mode == MODE_TREE {
2632        return Ok(false);
2633    }
2634    let abs = crate::index::worktree_path_from_index_rel(work_tree, &entry.path);
2635    let meta = match fs::symlink_metadata(&abs) {
2636        Ok(m) => m,
2637        Err(_) => return Ok(false),
2638    };
2639    if meta.is_dir() {
2640        return Ok(false);
2641    }
2642    let rules = crate::worktree_rules::WorktreeRules::from_repository(repo, index)?;
2643    let stash_blob = repo.odb().read(&entry.oid)?;
2644    let worktree_bytes = smudge_bytes_for_worktree_path(
2645        repo,
2646        &rules,
2647        path,
2648        entry.mode,
2649        &stash_blob.data,
2650        &entry.oid,
2651    )?;
2652    if meta.file_type().is_symlink() {
2653        let target = fs::read_link(&abs).map_err(Error::Io)?;
2654        return Ok(target.as_os_str().as_encoded_bytes() == worktree_bytes);
2655    }
2656    let disk = fs::read(&abs).map_err(Error::Io)?;
2657    Ok(disk == worktree_bytes)
2658}
2659
2660/// Apply a stash commit onto the current worktree and index.
2661///
2662/// Mirrors `git stash apply`: three-way-merges changed files when `HEAD` has moved since the
2663/// stash was created, restores the index from the stash index parent when
2664/// [`StashApplyOptions::restore_index`] is set (otherwise tracks current `HEAD` at touched
2665/// paths), and materializes any untracked-files parent.
2666///
2667/// # Errors
2668///
2669/// Returns [`StashError::BareRepository`] without a work tree, [`StashError::CorruptStash`] for a
2670/// malformed stash commit, and local-change, untracked-overwrite, or index write failures.
2671pub(crate) fn apply_stash_oid(
2672    repo: &Repository,
2673    stash_oid: &ObjectId,
2674    options: &StashApplyOptions,
2675    progress: &mut dyn ProgressSink,
2676    cancel: &CancelToken,
2677) -> crate::error::Result<StashApplyOutcome> {
2678    let work_tree = repo.work_tree().ok_or(StashError::BareRepository)?;
2679    apply_stash_commit(repo, work_tree, stash_oid, options, progress, cancel)
2680}
2681
2682/// Result of [`RepositoryStash::apply`](crate::repo_handles::RepositoryStash::apply),
2683/// [`RepositoryStash::apply_commit`](crate::repo_handles::RepositoryStash::apply_commit), and
2684/// [`RepositoryStash::pop`](crate::repo_handles::RepositoryStash::pop).
2685#[derive(Debug, Clone, PartialEq, Eq, Default)]
2686#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
2687pub struct StashApplyOutcome {
2688    /// Paths left with conflict stages (1–3) in the index, in index order, each with the
2689    /// [`ConflictKind`](crate::operation::ConflictKind) `status` reports for it.
2690    ///
2691    /// Built by [`conflicts_from_index`], so paths use
2692    /// [`crate::repo_relpath::storage_string`] to preserve raw Git path bytes. Empty when the
2693    /// stash applied cleanly.
2694    pub conflicts: Vec<Conflict>,
2695}
2696
2697impl StashApplyOutcome {
2698    /// Whether the apply left merge conflicts in the worktree and index.
2699    ///
2700    /// After a pop, `true` also means the stash entry was kept.
2701    #[must_use]
2702    pub fn has_conflicts(&self) -> bool {
2703        !self.conflicts.is_empty()
2704    }
2705}
2706
2707/// Apply `stash@{{n}}` (newest-first) onto the current worktree and index without dropping it.
2708///
2709/// # Errors
2710///
2711/// Returns [`StashError::NotFound`] when `n` is out of range, plus the [`apply_stash_oid`] errors.
2712pub(crate) fn apply_stash_entry(
2713    repo: &Repository,
2714    n: usize,
2715    options: &StashApplyOptions,
2716    progress: &mut dyn ProgressSink,
2717    cancel: &CancelToken,
2718) -> crate::error::Result<StashApplyOutcome> {
2719    let oid = stash_oid_at(repo, n)?;
2720    apply_stash_oid(repo, &oid, options, progress, cancel)
2721}
2722
2723/// Apply `stash@{{n}}` and drop it when it applied without conflicts.
2724///
2725/// # Errors
2726///
2727/// Propagates [`apply_stash_entry`] and [`drop_stash`] failures.
2728pub(crate) fn pop_stash_entry(
2729    repo: &Repository,
2730    n: usize,
2731    options: &StashApplyOptions,
2732    progress: &mut dyn ProgressSink,
2733    cancel: &CancelToken,
2734) -> crate::error::Result<StashApplyOutcome> {
2735    let outcome = apply_stash_entry(repo, n, options, progress, cancel)?;
2736    if !outcome.has_conflicts() {
2737        drop_stash(repo, n)?;
2738    }
2739    Ok(outcome)
2740}
2741
2742fn apply_stash_commit(
2743    repo: &Repository,
2744    work_tree: &Path,
2745    stash_oid: &ObjectId,
2746    options: &StashApplyOptions,
2747    progress: &mut dyn ProgressSink,
2748    cancel: &CancelToken,
2749) -> crate::error::Result<StashApplyOutcome> {
2750    let restore_index = options.restore_index;
2751    let stash_commit = repo.odb().read_commit(stash_oid)?;
2752
2753    if stash_commit.parents.len() < 2 {
2754        return Err(crate::error::Error::from(corrupt_stash_commit(*stash_oid)));
2755    }
2756
2757    let head_at_stash = &stash_commit.parents[0];
2758    let index_commit_oid = &stash_commit.parents[1];
2759
2760    let mut lock = repo.lock_index()?;
2761    let mut new_index = load_stash_index(repo)?;
2762    let skip_worktree_before: BTreeSet<Vec<u8>> = new_index
2763        .entries
2764        .iter()
2765        .filter(|entry| entry.stage() == 0 && entry.skip_worktree())
2766        .map(|entry| entry.path.clone())
2767        .collect();
2768    let assume_unchanged_before: BTreeMap<Vec<u8>, (ObjectId, u32)> = new_index
2769        .entries
2770        .iter()
2771        .filter(|entry| entry.stage() == 0 && entry.assume_unchanged())
2772        .map(|entry| (entry.path.clone(), (entry.oid, entry.mode)))
2773        .collect();
2774    let head_at_stash_tree = repo.odb().commit_tree(head_at_stash)?;
2775    let idx_tree = repo.odb().commit_tree(index_commit_oid)?;
2776    let merged_index_tree = if restore_index {
2777        let current_index_tree = write_stash_tree_from_index(repo, &mut new_index)?;
2778        merge_stash_index_trees(repo, &head_at_stash_tree, &current_index_tree, &idx_tree)?
2779    } else {
2780        None
2781    };
2782
2783    let StashTreeDelta {
2784        mut base,
2785        changes: wt_changes,
2786    } = StashTreeDelta::read(repo, &head_at_stash_tree, &stash_commit.tree)?;
2787    check_stash_local_changes(
2788        repo,
2789        work_tree,
2790        &new_index,
2791        wt_changes.iter().map(|(p, _)| p.as_slice()),
2792    )?;
2793    let deletions = wt_changes
2794        .iter()
2795        .filter(|(_, e)| e.is_none())
2796        .map(|(p, _)| p.clone())
2797        .collect();
2798    check_stash_untracked_restore(
2799        repo,
2800        work_tree,
2801        &stash_commit,
2802        &mut new_index,
2803        &deletions,
2804        options,
2805    )?;
2806    drop(deletions);
2807
2808    // Include the index delta even when a staged addition was removed again in the worktree.
2809    let index_delta = StashTreeDelta::read(repo, &head_at_stash_tree, &idx_tree)?;
2810    base.extend(index_delta.base);
2811    base.sort_by(|a, b| a.path.cmp(&b.path));
2812    base.dedup_by(|a, b| a.path == b.path);
2813    let base_tree_entries = base;
2814    let idx_tree_loaded: Vec<_> = if idx_tree == head_at_stash_tree {
2815        Vec::new()
2816    } else {
2817        let mut entries: BTreeMap<_, _> = base_tree_entries
2818            .iter()
2819            .map(|e| (e.path.clone(), e.clone()))
2820            .collect();
2821        for (path, entry) in index_delta.changes {
2822            if let Some(entry) = entry {
2823                entries.insert(path, entry);
2824            } else {
2825                entries.remove(&path);
2826            }
2827        }
2828        entries.into_values().collect()
2829    };
2830    let idx_tree_entries = if idx_tree == head_at_stash_tree {
2831        base_tree_entries.as_slice()
2832    } else {
2833        idx_tree_loaded.as_slice()
2834    };
2835    // Determine if HEAD has moved since the stash was created
2836    let current_head = resolve_head_for_repository(repo)?;
2837    let current_head_oid = current_head.oid().copied();
2838    let head_moved = current_head_oid.as_ref() != Some(head_at_stash);
2839
2840    // Current HEAD tree (three-way merge when HEAD moved; index reset without `--index`).
2841    let current_head_loaded = if head_moved {
2842        let Some(head_oid) = current_head_oid.as_ref() else {
2843            return Err(StashError::MissingHead.into());
2844        };
2845        let head_tree = repo.odb().commit_tree(head_oid)?;
2846        let affected: BTreeSet<_> = wt_changes
2847            .iter()
2848            .map(|(p, _)| p.as_slice())
2849            .chain(idx_tree_entries.iter().map(|e| e.path.as_slice()))
2850            .collect();
2851        Some(
2852            affected
2853                .into_iter()
2854                .map(|path| stash_tree_entry_at_path(repo, head_tree, path))
2855                .collect::<Result<Vec<_>>>()?
2856                .into_iter()
2857                .flatten()
2858                .collect::<Vec<_>>(),
2859        )
2860    } else {
2861        None
2862    };
2863    let current_head_entries: &[StashTreeEntry] = if let Some(ref loaded) = current_head_loaded {
2864        loaded
2865    } else {
2866        &base_tree_entries
2867    };
2868
2869    let mut has_conflicts = false;
2870    let worktree_rules = WorktreeRules::from_repository(repo, &new_index)?;
2871    poll_cancel(progress, cancel)?;
2872
2873    let mut checkout_journal = CheckoutJournal::new(work_tree)?;
2874
2875    let apply_result: Result<StashApplyOutcome> = (|| {
2876        // First pass: process deletions (None entries) before additions to avoid
2877        // type conflicts (e.g., trying to write a file where a directory exists).
2878        for (path, change) in &wt_changes {
2879            if change.is_some() {
2880                continue;
2881            }
2882            poll_cancel(progress, cancel)?;
2883            let rel = storage_string(path);
2884            let file_path = crate::index::worktree_path_from_index_rel(work_tree, path);
2885            if file_path.is_dir() {
2886                let git_meta = file_path.join(".git");
2887                if git_meta.is_file() || git_meta.is_dir() {
2888                    continue;
2889                }
2890                checkout_journal.record_removed_dir(&rel);
2891                fs::remove_dir_all(&file_path).map_err(|source| {
2892                    stash_worktree_io(&rel, WorktreePathOperation::Remove, source)
2893                })?;
2894            } else {
2895                checkout_journal.spool_remove(&rel)?;
2896                fs::remove_file(&file_path).map_err(|source| {
2897                    stash_worktree_io(&rel, WorktreePathOperation::Remove, source)
2898                })?;
2899            }
2900            if let Some(parent) = file_path.parent() {
2901                remove_empty_dirs(parent, work_tree, repo.environment());
2902            }
2903        }
2904
2905        // Apply working tree changes (with three-way merge when HEAD has moved)
2906        let mut prepared_dirs: HashSet<std::path::PathBuf> = HashSet::new();
2907        let mut parallel_writes: Vec<StashCheckoutJob<'_>> = Vec::new();
2908        for (path, change) in &wt_changes {
2909            // Deletions all ran in the first pass. Pruning directories here could remove the
2910            // parent of a regular file still queued for bulk checkout.
2911            let Some(entry) = change else {
2912                continue;
2913            };
2914            poll_cancel(progress, cancel)?;
2915            let file_path = crate::index::worktree_path_from_index_rel(work_tree, path);
2916            if let Some(parent) = file_path.parent() {
2917                // Entries of one tree never use another entry's path as a directory, so a
2918                // parent prepared once stays a directory for the rest of this pass.
2919                if !prepared_dirs.contains(parent) {
2920                    // If a component of the parent is a file, remove it first
2921                    let mut cur = work_tree.to_path_buf();
2922                    if let Ok(rel) = parent.strip_prefix(work_tree) {
2923                        for comp in rel.components() {
2924                            cur.push(comp);
2925                            if cur.exists() && !cur.is_dir() {
2926                                if let Ok(rel_comp) = cur.strip_prefix(work_tree) {
2927                                    let rel_s = crate::repo_relpath::storage_string(
2928                                        rel_comp.as_os_str().as_encoded_bytes(),
2929                                    );
2930                                    checkout_journal.spool_remove(&rel_s)?;
2931                                }
2932                                fs::remove_file(&cur).map_err(|source| {
2933                                    stash_worktree_io(
2934                                        &storage_string(path),
2935                                        WorktreePathOperation::Remove,
2936                                        source,
2937                                    )
2938                                })?;
2939                            }
2940                        }
2941                    }
2942                    let rel_display = storage_string(path);
2943                    fs::create_dir_all(parent).map_err(|source| {
2944                        stash_worktree_io(&rel_display, WorktreePathOperation::Create, source)
2945                    })?;
2946                    prepared_dirs.insert(parent.to_path_buf());
2947                }
2948            }
2949            if entry.mode == MODE_GITLINK {
2950                let rel_display = storage_string(path);
2951                checkout_journal.spool_remove(&rel_display)?;
2952                if file_path.is_file() || file_path.is_symlink() {
2953                    fs::remove_file(&file_path).map_err(|source| {
2954                        stash_worktree_io(&rel_display, WorktreePathOperation::Remove, source)
2955                    })?;
2956                } else if file_path.is_dir() {
2957                    let git_meta = file_path.join(".git");
2958                    if !(git_meta.is_file() || git_meta.is_dir()) {
2959                        checkout_journal.record_removed_dir(&rel_display);
2960                        fs::remove_dir_all(&file_path).map_err(|source| {
2961                            stash_worktree_io(&rel_display, WorktreePathOperation::Remove, source)
2962                        })?;
2963                    }
2964                }
2965                checkout_journal.record_created(&rel_display);
2966                fs::create_dir_all(&file_path).map_err(|source| {
2967                    stash_worktree_io(&rel_display, WorktreePathOperation::Create, source)
2968                })?;
2969                continue;
2970            }
2971
2972            if !head_moved && entry.mode != MODE_SYMLINK {
2973                let file_attrs = worktree_rules.file_attrs(&String::from_utf8_lossy(path), false);
2974                // The bulk driver matches attributes against its stored path strings. Keep
2975                // encoded names on this writer, which matches against the original name.
2976                if let Ok(rel_path) = std::str::from_utf8(path) {
2977                    if !rel_path.starts_with(crate::repo_relpath::STORAGE_PREFIX)
2978                        && is_eligible_for_parallel_checkout(entry.mode, &file_attrs)
2979                    {
2980                        parallel_writes.push(StashCheckoutJob {
2981                            rel_path,
2982                            mode: entry.mode,
2983                            oid: entry.oid,
2984                        });
2985                        continue;
2986                    }
2987                }
2988            }
2989
2990            let stash_blob = repo.odb().read(&entry.oid)?;
2991
2992            let rel_display = storage_string(path);
2993            checkout_journal.preserve_before_write(&rel_display)?;
2994
2995            if entry.mode == MODE_SYMLINK {
2996                let target =
2997                    String::from_utf8(stash_blob.data).map_err(|_| StashError::SymlinkNotUtf8)?;
2998                if file_path.exists() || file_path.symlink_metadata().is_ok() {
2999                    fs::remove_file(&file_path).map_err(|source| {
3000                        stash_worktree_io(&rel_display, WorktreePathOperation::Remove, source)
3001                    })?;
3002                }
3003                let has_symlinks =
3004                    crate::index::WorktreeModePolicy::from_config(worktree_rules.config())
3005                        .has_symlinks;
3006                crate::worktree::write_index_symlink_to_worktree(&file_path, &target, has_symlinks)
3007                    .map_err(Error::Io)?;
3008            } else if head_moved {
3009                // Three-way merge: base (head_at_stash), ours (current HEAD), theirs (stash)
3010                let base_content = StashTreeEntry::lookup(&base_tree_entries, path)
3011                    .and_then(|e| repo.odb().read(&e.oid).ok())
3012                    .map(|o| o.data)
3013                    .unwrap_or_default();
3014                let ours_content = StashTreeEntry::lookup(current_head_entries, path)
3015                    .and_then(|e| repo.odb().read(&e.oid).ok())
3016                    .map(|o| o.data)
3017                    .unwrap_or_default();
3018                let theirs_content = stash_blob.data;
3019
3020                // If ours == base, no conflict (only stash changed this file)
3021                if ours_content == base_content {
3022                    write_smudged_regular_file_replacing_symlink(
3023                        repo,
3024                        &worktree_rules,
3025                        &String::from_utf8_lossy(path),
3026                        &file_path,
3027                        entry.mode,
3028                        &theirs_content,
3029                        &entry.oid,
3030                    )?;
3031                } else if ours_content == theirs_content {
3032                    // Both changed the same way, no conflict
3033                    let smudge_oid = StashTreeEntry::lookup(current_head_entries, path)
3034                        .map(|e| e.oid)
3035                        .unwrap_or(entry.oid);
3036                    write_smudged_regular_file_replacing_symlink(
3037                        repo,
3038                        &worktree_rules,
3039                        &String::from_utf8_lossy(path),
3040                        &file_path,
3041                        entry.mode,
3042                        &ours_content,
3043                        &smudge_oid,
3044                    )?;
3045                } else {
3046                    // Both sides changed differently — try content merge
3047                    use crate::merge_file::{
3048                        merge, ConflictStyle, MergeFavor, MergeInput, TREE_MERGE_DIFF_ALGORITHM,
3049                    };
3050                    let input = MergeInput {
3051                        base: &base_content,
3052                        ours: &ours_content,
3053                        theirs: &theirs_content,
3054                        label_ours: "Updated upstream",
3055                        label_base: "Stashed changes",
3056                        label_theirs: "Stashed changes",
3057                        favor: MergeFavor::None,
3058                        style: ConflictStyle::Merge,
3059                        marker_size: 7,
3060                        diff_algorithm: Some(TREE_MERGE_DIFF_ALGORITHM.to_string()),
3061                        ignore_all_space: false,
3062                        ignore_space_change: false,
3063                        ignore_space_at_eol: false,
3064                        ignore_cr_at_eol: false,
3065                    };
3066                    let output = merge(&input)?;
3067                    let marker_oid = repo.odb().hash(ObjectKind::Blob, &output.content)?;
3068                    let worktree_bytes = smudge_bytes_for_worktree_path(
3069                        repo,
3070                        &worktree_rules,
3071                        &String::from_utf8_lossy(path),
3072                        entry.mode,
3073                        &output.content,
3074                        &marker_oid,
3075                    )?;
3076                    write_regular_file_replacing_symlink(&file_path, &worktree_bytes).map_err(
3077                        |source| {
3078                            stash_worktree_io(
3079                                &String::from_utf8_lossy(path),
3080                                WorktreePathOperation::Replace,
3081                                source,
3082                            )
3083                        },
3084                    )?;
3085                    if output.conflicts > 0 {
3086                        has_conflicts = true;
3087                        // Write conflict stages to index
3088                        let path_bytes = path.as_slice();
3089                        let original_mode = new_index
3090                            .get(path_bytes, 0)
3091                            .map(|e| e.mode)
3092                            .unwrap_or(crate::index::MODE_REGULAR);
3093                        // Remove existing stage-0 entry
3094                        new_index
3095                            .entries
3096                            .retain(|e| e.path != path_bytes || e.stage() != 0);
3097                        // Adding non-zero stages drops this path from any valid stage-0
3098                        // cache-tree; invalidate it (Git's add_index_entry ->
3099                        // cache_tree_invalidate_path) so a stale TREE extension is not written
3100                        // alongside the conflicted index (otherwise the index write rejects it
3101                        // with "corrupted cache-tree has entries not present in
3102                        // index"; t7600 'merge with conflicted --autostash changes').
3103                        new_index.invalidate_cache_tree_for_path(path_bytes);
3104                        // Add stage entries
3105                        if let Some(base_entry) = StashTreeEntry::lookup(&base_tree_entries, path) {
3106                            add_stage_entry(
3107                                &mut new_index,
3108                                path_bytes,
3109                                &base_entry.oid,
3110                                base_entry.mode,
3111                                1,
3112                            );
3113                        }
3114                        if let Some(ours_entry) = StashTreeEntry::lookup(current_head_entries, path)
3115                        {
3116                            add_stage_entry(
3117                                &mut new_index,
3118                                path_bytes,
3119                                &ours_entry.oid,
3120                                original_mode,
3121                                2,
3122                            );
3123                        }
3124                        add_stage_entry(&mut new_index, path_bytes, &entry.oid, entry.mode, 3);
3125                    }
3126                }
3127            } else {
3128                write_smudged_regular_file_replacing_symlink(
3129                    repo,
3130                    &worktree_rules,
3131                    &String::from_utf8_lossy(path),
3132                    &file_path,
3133                    entry.mode,
3134                    &stash_blob.data,
3135                    &entry.oid,
3136                )?;
3137            }
3138        }
3139
3140        // Bulk checkout stages each blob it writes. Without an index merge, `--index` must keep the
3141        // pre-apply entries at those paths, so a stash whose index matched its base stays unstaged.
3142        let mut index_before_checkout: Vec<(&[u8], Option<IndexEntry>)> = Vec::new();
3143        if restore_index && merged_index_tree.is_none() {
3144            index_before_checkout = parallel_writes
3145                .iter()
3146                .map(|job| {
3147                    let path = job.rel_path.as_bytes();
3148                    (path, new_index.get(path, 0).cloned())
3149                })
3150                .collect();
3151        }
3152        if !parallel_writes.is_empty() {
3153            let checkout_changes: Vec<DiffEntry> = parallel_writes
3154                .iter()
3155                .map(|job| {
3156                    let base = StashTreeEntry::lookup(&base_tree_entries, job.rel_path.as_bytes());
3157                    DiffEntry {
3158                        status: DiffStatus::Modified,
3159                        old_path: Some(crate::repo_relpath::storage_string(
3160                            job.rel_path.as_bytes(),
3161                        )),
3162                        new_path: Some(crate::repo_relpath::storage_string(
3163                            job.rel_path.as_bytes(),
3164                        )),
3165                        old_mode: FileMode::new(
3166                            base.map(|e| e.mode).unwrap_or(crate::index::MODE_REGULAR),
3167                        ),
3168                        new_mode: FileMode::new(job.mode),
3169                        old_oid: base.map(|e| e.oid).unwrap_or_else(zero_oid),
3170                        new_oid: job.oid,
3171                        score: None,
3172                    }
3173                })
3174                .collect();
3175            checkout_tree_changes_into_deferred_journal(
3176                repo,
3177                &checkout_changes,
3178                &mut new_index,
3179                progress,
3180                cancel,
3181                crate::porcelain::checkout::CheckoutApplyOptions {
3182                    parallel_prepare_blobs: true,
3183                    ..crate::porcelain::checkout::CheckoutApplyOptions::default()
3184                },
3185                None,
3186                &lock,
3187                &mut checkout_journal,
3188            )?;
3189        }
3190        drop(parallel_writes);
3191        // Update the index
3192
3193        if restore_index && !has_conflicts {
3194            if let Some(merged_tree) = merged_index_tree {
3195                new_index = index_from_tree_with_worktree_stats(repo, &merged_tree)?;
3196            } else {
3197                // Stash index matched current index or HEAD at stash time; replay per-path index parent.
3198                for (path, entry) in index_before_checkout {
3199                    match entry {
3200                        Some(entry) => new_index.stage_file(entry),
3201                        None => {
3202                            new_index.remove(path);
3203                        }
3204                    }
3205                }
3206                for base_entry in &base_tree_entries {
3207                    if StashTreeEntry::lookup(idx_tree_entries, &base_entry.path).is_none() {
3208                        new_index.remove(&base_entry.path);
3209                    }
3210                }
3211                for idx_entry in idx_tree_entries {
3212                    let path = &idx_entry.path;
3213                    let base = StashTreeEntry::lookup(&base_tree_entries, path);
3214                    if base.map(|e| (e.oid, e.mode)) != Some((idx_entry.oid, idx_entry.mode)) {
3215                        let path_bytes = path.as_slice();
3216                        if let Some(ie) = new_index.get_mut(path_bytes, 0) {
3217                            ie.oid = idx_entry.oid;
3218                            ie.mode = idx_entry.mode;
3219                        } else {
3220                            let flags = if path.len() > 0xFFF {
3221                                0xFFF
3222                            } else {
3223                                path.len() as u16
3224                            };
3225                            new_index.push_entry_unsorted(IndexEntry {
3226                                ctime_sec: 0,
3227                                ctime_nsec: 0,
3228                                mtime_sec: 0,
3229                                mtime_nsec: 0,
3230                                dev: 0,
3231                                ino: 0,
3232                                mode: idx_entry.mode,
3233                                uid: 0,
3234                                gid: 0,
3235                                size: 0,
3236                                oid: idx_entry.oid,
3237                                flags,
3238                                flags_extended: None,
3239                                path: path_bytes.to_vec(),
3240                                base_index_pos: 0,
3241                            });
3242                        }
3243                    }
3244                }
3245                new_index.sort();
3246            }
3247        } else if !restore_index {
3248            // Without --index: index tracks current HEAD for paths the stash touched
3249            // (worktree gets the stashed changes; index matches HEAD at those paths).
3250            //
3251            // Exception: paths that exist in the stash index parent but not on **current** HEAD
3252            // (e.g. a newly `git add`ed file) must be re-staged from the stash index parent
3253            // (t3903 `stash an added file`).
3254            let mut touched: BTreeSet<Vec<u8>> =
3255                wt_changes.iter().map(|(p, _)| p.clone()).collect();
3256            for entry in idx_tree_entries {
3257                if StashTreeEntry::lookup(&base_tree_entries, &entry.path).is_none() {
3258                    touched.insert(entry.path.clone());
3259                }
3260            }
3261            // Unmerged paths only come from the starting index or the conflict pass above, and the
3262            // loop below never adds or removes conflict stages, so one snapshot covers every path.
3263            let unmerged: HashSet<Vec<u8>> = new_index
3264                .entries
3265                .iter()
3266                .filter(|e| e.stage() > 0)
3267                .map(|e| e.path.clone())
3268                .collect();
3269            for path in &touched {
3270                if let Some(te) = StashTreeEntry::lookup(current_head_entries, path) {
3271                    let path_bytes = path.as_slice();
3272                    let size = if te.mode == MODE_SYMLINK || te.mode == MODE_GITLINK {
3273                        0u32
3274                    } else {
3275                        repo.odb().read_info(&te.oid)?.size as u32
3276                    };
3277                    let new_entry = IndexEntry {
3278                        ctime_sec: 0,
3279                        ctime_nsec: 0,
3280                        mtime_sec: 0,
3281                        mtime_nsec: 0,
3282                        dev: 0,
3283                        ino: 0,
3284                        mode: te.mode,
3285                        uid: 0,
3286                        gid: 0,
3287                        size,
3288                        oid: te.oid,
3289                        flags: path_bytes.len().min(0xFFF) as u16,
3290                        flags_extended: None,
3291                        path: path_bytes.to_vec(),
3292                        base_index_pos: 0,
3293                    };
3294                    // Do not replace unmerged index entries: `stage_file` strips stages 1–3, which
3295                    // would hide merge conflicts after stash apply (t9903 conflict prompt).
3296                    if !unmerged.contains(path_bytes) {
3297                        new_index.stage_file(new_entry);
3298                    }
3299                } else {
3300                    let path_bytes = path.as_slice();
3301                    if unmerged.contains(path_bytes) {
3302                        continue;
3303                    }
3304                    if let Some(ie) = StashTreeEntry::lookup(idx_tree_entries, path) {
3305                        let had_staged = match StashTreeEntry::lookup(&base_tree_entries, path) {
3306                            Some(b) => b.oid != ie.oid || b.mode != ie.mode,
3307                            None => true,
3308                        };
3309                        if had_staged {
3310                            let size = if ie.mode == MODE_SYMLINK || ie.mode == MODE_GITLINK {
3311                                0u32
3312                            } else {
3313                                repo.odb().read_info(&ie.oid)?.size as u32
3314                            };
3315                            new_index.stage_file(IndexEntry {
3316                                ctime_sec: 0,
3317                                ctime_nsec: 0,
3318                                mtime_sec: 0,
3319                                mtime_nsec: 0,
3320                                dev: 0,
3321                                ino: 0,
3322                                mode: ie.mode,
3323                                uid: 0,
3324                                gid: 0,
3325                                size,
3326                                oid: ie.oid,
3327                                flags: path_bytes.len().min(0xFFF) as u16,
3328                                flags_extended: None,
3329                                path: path_bytes.to_vec(),
3330                                base_index_pos: 0,
3331                            });
3332                        } else {
3333                            new_index.remove(path_bytes);
3334                        }
3335                    } else {
3336                        new_index.remove(path_bytes);
3337                    }
3338                }
3339            }
3340            new_index.sort();
3341        }
3342
3343        if has_conflicts {
3344            new_index.sort();
3345            // A conflicted index (unmerged stages) cannot have a valid stage-0 cache-tree; drop the
3346            // TREE extension so write_index does not persist a stale one (which would fail
3347            // cache-tree verification with "corrupted cache-tree has entries not present in
3348            // index"). Mirrors Git, which only keeps a cache-tree for a fully merged index.
3349            new_index.clear_cache_tree();
3350        }
3351        // Refresh cached stat for entries restored from the stash trees whose worktree content matches
3352        // the recorded OID, so a following `git diff-files` reflects only genuine differences (t3903
3353        // 'stash apply --index refreshes the index').
3354        if !has_conflicts {
3355            if restore_index || head_moved {
3356                refresh_index_stats_content_verified(repo, work_tree, &mut new_index)?;
3357            } else {
3358                // HEAD is unchanged and the index was not restored, so a touched path's index entry
3359                // can only match the worktree when it holds the very blob just written there (a newly
3360                // added file whose staged and worktree content agree). Every other touched entry is
3361                // known to differ, and untouched entries keep their stat data.
3362                let mut written = Index::new();
3363                for (path, change) in &wt_changes {
3364                    let Some(stashed) = change else {
3365                        continue;
3366                    };
3367                    if let Some(ie) = new_index.get(path, 0) {
3368                        if ie.oid == stashed.oid && ie.mode == stashed.mode {
3369                            written.push_entry_unsorted(ie.clone());
3370                        }
3371                    }
3372                }
3373                if !written.entries.is_empty() {
3374                    written.sort();
3375                    written.source_mtime = new_index.source_mtime;
3376                    written.source_checksum = new_index.source_checksum.clone();
3377                    written.source_file_len = new_index.source_file_len;
3378                    refresh_index_stats_content_verified(repo, work_tree, &mut written)?;
3379                    for refreshed in written.entries {
3380                        if let Some(ie) = new_index.get_mut(&refreshed.path, 0) {
3381                            *ie = refreshed;
3382                        }
3383                    }
3384                }
3385            }
3386        }
3387        let conflicts = if has_conflicts {
3388            conflicts_from_index(&new_index)
3389        } else {
3390            Vec::new()
3391        };
3392        let stashed_worktree_paths: BTreeSet<Vec<u8>> =
3393            wt_changes.iter().map(|(path, _)| path.clone()).collect();
3394        for path in &skip_worktree_before {
3395            if !stashed_worktree_paths.contains(path) {
3396                if let Some(entry) = new_index.get_mut(path, 0) {
3397                    entry.set_skip_worktree(true);
3398                }
3399            }
3400        }
3401        for (path, &(oid, mode)) in &assume_unchanged_before {
3402            if !stashed_worktree_paths.contains(path) {
3403                if let Some(entry) = new_index.get_mut(path, 0) {
3404                    if entry.oid == oid && entry.mode == mode {
3405                        entry.set_assume_unchanged(true);
3406                    }
3407                }
3408            }
3409        }
3410        if stash_commit.parents.len() >= 3 {
3411            let ut_oid = &stash_commit.parents[2];
3412            let ut_tree = repo.odb().commit_tree(ut_oid)?;
3413            let ut_entries = flatten_tree_full_raw_for_repo(repo, &ut_tree)?;
3414            for entry in &ut_entries {
3415                let stored = storage_string(&entry.path);
3416                checkout_journal.preserve_before_write(&stored)?;
3417                materialize_raw_flat_entry_in_worktree(repo, work_tree, &worktree_rules, entry)?;
3418            }
3419        }
3420        repo.write_index_with_lock(&mut lock, &mut new_index, false)
3421            .map_err(|err| match err.path_io() {
3422                Some(source) => StashError::IndexWrite { source }.into(),
3423                None => err,
3424            })?;
3425        Ok(StashApplyOutcome { conflicts })
3426    })();
3427
3428    match apply_result {
3429        Ok(outcome) => {
3430            checkout_journal.commit();
3431            Ok(outcome)
3432        }
3433        Err(err) => checkout_journal.finish(repo, Err::<StashApplyOutcome, _>(err)),
3434    }
3435}
3436
3437/// Refresh cached stat data for stage-0 entries whose worktree content matches their blob.
3438fn refresh_index_stats_content_verified(
3439    repo: &Repository,
3440    work_tree: &Path,
3441    index: &mut Index,
3442) -> Result<()> {
3443    let rules = WorktreeRules::from_repository(repo, index).ok();
3444    let rules_arc = rules.map(|r| std::sync::Arc::new(std::sync::Mutex::new(r)));
3445    crate::diff::refresh_index_stat_content_verified_with_rules(
3446        repo.odb(),
3447        repo.git_dir(),
3448        index,
3449        work_tree,
3450        None,
3451        repo.config().snapshot().ok().as_deref(),
3452        None,
3453        rules_arc.as_ref(),
3454    )?;
3455    Ok(())
3456}
3457
3458const STASH_REF: &str = "refs/stash";
3459
3460/// Remove one stash commit from `refs/stash` when it is the reflog tip.
3461///
3462/// # Returns
3463///
3464/// `true` when the stash entry was removed.
3465///
3466/// # Errors
3467///
3468/// Propagates ref and reflog update failures.
3469pub(crate) fn drop_stash_commit(repo: &Repository, stash_oid: &ObjectId) -> Result<bool> {
3470    const RETRIES: u32 = 128;
3471    let store = repo.ref_store();
3472    let git_dir = repo.git_dir();
3473    for _ in 0..RETRIES {
3474        if store
3475            .resolve(RefNameRef::from_trusted(STASH_REF))
3476            .ok()
3477            .is_none_or(|tip| tip != *stash_oid)
3478        {
3479            return Ok(false);
3480        }
3481        let mut new_tip = None;
3482        match store.rewrite_reflog_str(RefNameRef::from_trusted(STASH_REF), &mut |mut entries| {
3483            if entries.last().is_none_or(|tip| tip.new_oid != *stash_oid) {
3484                return Err(crate::error::Error::Ref(RefError::Store(
3485                    crate::refs::store::RefStoreError::ReflogRewriteStale {
3486                        name: STASH_REF.to_owned(),
3487                    },
3488                )));
3489            }
3490            entries.pop();
3491            new_tip = entries.last().map(|entry| entry.new_oid);
3492            Ok(entries)
3493        }) {
3494            Ok(()) => {}
3495            Err(crate::error::Error::Ref(RefError::Store(
3496                crate::refs::store::RefStoreError::ReflogRewriteStale { .. },
3497            ))) => continue,
3498            Err(err) => return Err(err),
3499        }
3500        let ref_result = match new_tip {
3501            None => crate::refs::store_write_value_on_store(
3502                store,
3503                git_dir,
3504                STASH_REF,
3505                None,
3506                crate::refs::store::Expected::Oid(*stash_oid),
3507                None,
3508            ),
3509            Some(prev) => crate::refs::store_write_value_on_store(
3510                store,
3511                git_dir,
3512                STASH_REF,
3513                Some(crate::refs::store::RawRef::Direct(prev)),
3514                crate::refs::store::Expected::Oid(*stash_oid),
3515                None,
3516            ),
3517        };
3518        match ref_result {
3519            Ok(()) => return Ok(true),
3520            Err(crate::error::Error::Ref(RefError::Store(
3521                crate::refs::store::RefStoreError::ExpectedMismatch { .. },
3522            ))) => continue,
3523            Err(err) => return Err(err),
3524        }
3525    }
3526    Err(crate::error::Error::Ref(RefError::Store(
3527        crate::refs::store::RefStoreError::Corrupt {
3528            detail: "refs/stash changed too often during drop".to_owned(),
3529        },
3530    )))
3531}
3532
3533/// Stash dirty worktree/index changes before `pull --autostash` / merge autostash.
3534///
3535/// Returns `None` when there is nothing to stash.
3536///
3537/// # Errors
3538///
3539/// Propagates stash creation and checkout failures.
3540pub(crate) fn push_operation_autostash(
3541    repo: &Repository,
3542    identity: &str,
3543) -> Result<Option<ObjectId>> {
3544    Ok(push_stash(
3545        repo,
3546        &StashPushOptions {
3547            message: Some("autostash".to_owned()),
3548            include_untracked: true,
3549            identity: identity.parse()?,
3550            selection: None,
3551            pathspecs: Vec::new(),
3552            dry_run: false,
3553            mode: StashMode::default(),
3554        },
3555        &mut NullProgress,
3556        CancelToken::never_ref(),
3557    )?
3558    .map(|r| r.oid))
3559}
3560
3561/// Re-apply an operation autostash after a successful pull/merge/rebase integration.
3562///
3563/// # Returns
3564///
3565/// `true` when applying the autostash left conflicts (the stash entry is kept).
3566///
3567/// # Errors
3568///
3569/// Propagates stash apply failures.
3570pub(crate) fn apply_operation_autostash(repo: &Repository, stash_oid: &ObjectId) -> Result<bool> {
3571    let conflicts = apply_stash_oid(
3572        repo,
3573        stash_oid,
3574        &StashApplyOptions::default(),
3575        &mut NullProgress,
3576        CancelToken::never_ref(),
3577    )?
3578    .has_conflicts();
3579    if !conflicts {
3580        let _ = drop_stash_commit(repo, stash_oid)?;
3581    }
3582    Ok(conflicts)
3583}
3584
3585/// Put a stashed autostash back after an aborted pull/merge (integration did not finish).
3586///
3587/// # Errors
3588///
3589/// Propagates stash apply failures.
3590pub(crate) fn restore_operation_autostash(repo: &Repository, stash_oid: &ObjectId) -> Result<()> {
3591    let conflicts = apply_stash_oid(
3592        repo,
3593        stash_oid,
3594        &StashApplyOptions::default(),
3595        &mut NullProgress,
3596        CancelToken::never_ref(),
3597    )?
3598    .has_conflicts();
3599    if !conflicts {
3600        let _ = drop_stash_commit(repo, stash_oid)?;
3601    }
3602    Ok(())
3603}
3604
3605/// Move the merge autostash commit onto `refs/stash` without applying it, matching `git reset`
3606/// clearing merge state (`save_autostash_ref`).
3607///
3608/// # Errors
3609///
3610/// Propagates parse, stash store, and I/O failures.
3611pub(crate) fn save_merge_autostash_ref(repo: &Repository, identity: &str) -> Result<()> {
3612    let path = repo.git_dir().join("MERGE_AUTOSTASH");
3613    let Ok(content) = fs::read_to_string(&path) else {
3614        return Ok(());
3615    };
3616    let trimmed = content.trim();
3617    if trimmed.is_empty() {
3618        let _ = fs::remove_file(&path);
3619        return Ok(());
3620    }
3621    let stash_oid = ObjectId::from_hex(trimmed)?;
3622    store_stash(repo, stash_oid, "autostash", identity)?;
3623    fs::remove_file(&path).map_err(Error::Io)?;
3624    Ok(())
3625}
3626
3627/// Record `stash_oid` as the merge autostash (`MERGE_AUTOSTASH`) of a merge left in progress,
3628/// so finishing it ([`apply_merge_autostash`]) or aborting it puts the stashed edits back.
3629///
3630/// # Errors
3631///
3632/// [`Error::Io`] when the file cannot be written.
3633pub(crate) fn record_merge_autostash(repo: &Repository, stash_oid: &ObjectId) -> Result<()> {
3634    fs::write(
3635        repo.git_dir().join("MERGE_AUTOSTASH"),
3636        format!("{}\n", stash_oid.to_hex()),
3637    )
3638    .map_err(Error::Io)
3639}
3640
3641/// Apply and drop the merge autostash recorded in `MERGE_AUTOSTASH`, matching `git commit` after
3642/// `git merge --autostash`.
3643///
3644/// # Returns
3645///
3646/// `true` when applying the autostash left index/worktree conflicts (the stash entry is kept).
3647///
3648/// # Errors
3649///
3650/// Propagates stash apply, index, and I/O failures.
3651pub(crate) fn apply_merge_autostash(repo: &Repository) -> Result<bool> {
3652    let path = repo.git_dir().join("MERGE_AUTOSTASH");
3653    let Ok(content) = fs::read_to_string(&path) else {
3654        return Ok(false);
3655    };
3656    let trimmed = content.trim();
3657    if trimmed.is_empty() {
3658        let _ = fs::remove_file(&path);
3659        return Ok(false);
3660    }
3661    let stash_oid = ObjectId::from_hex(trimmed)?;
3662    let conflicts = apply_stash_oid(
3663        repo,
3664        &stash_oid,
3665        &StashApplyOptions::default(),
3666        &mut NullProgress,
3667        CancelToken::never_ref(),
3668    )?
3669    .has_conflicts();
3670    let _ = fs::remove_file(&path);
3671    if !conflicts {
3672        let _ = drop_stash_commit(repo, &stash_oid)?;
3673    }
3674    Ok(conflicts)
3675}
3676
3677#[cfg(test)]
3678mod coverage_tests {
3679    #![allow(clippy::expect_used, clippy::unwrap_used)]
3680
3681    use super::*;
3682    use crate::environment::RepositoryOptions;
3683    use crate::index::{entry_from_stat, MODE_REGULAR};
3684    use crate::refs;
3685    use std::fs;
3686    use std::path::Path;
3687    use tempfile::TempDir;
3688
3689    fn init_repo(root: &Path) -> Repository {
3690        let git = root.join(".git");
3691        fs::create_dir_all(git.join("objects")).unwrap();
3692        fs::create_dir_all(git.join("refs/heads")).unwrap();
3693        fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
3694        fs::write(
3695            git.join("config"),
3696            "[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tlogAllRefUpdates = true\n",
3697        )
3698        .unwrap();
3699        let repo =
3700            Repository::open(&git, &RepositoryOptions::empty().with_work_tree(root)).unwrap();
3701        let wt = root.join("f");
3702        fs::write(&wt, b"base\n").unwrap();
3703        let mut index = repo.load_index().unwrap();
3704        let oid = repo.odb().write(ObjectKind::Blob, b"base\n").unwrap();
3705        index.add_or_replace(entry_from_stat(&wt, b"f", oid, MODE_REGULAR).unwrap());
3706        index.sort();
3707        repo.write_index(&mut index).unwrap();
3708        let tree = write_stash_tree_from_index(&repo, &mut index).unwrap();
3709        let parent = refs::resolve_ref(repo.git_dir(), "HEAD").ok();
3710        let commit = CommitData {
3711            tree,
3712            parents: parent.into_iter().collect(),
3713            author: "T <t@t> 0 +0000".into(),
3714            committer: "T <t@t> 0 +0000".into(),
3715            author_raw: Vec::new(),
3716            committer_raw: Vec::new(),
3717            encoding: None,
3718            message: "init\n".into(),
3719            raw_message: None,
3720            extra_headers: Vec::new(),
3721        };
3722        let commit_oid = write_commit_object(&repo, &commit, None).unwrap();
3723        refs::write_ref(repo.git_dir(), "HEAD", &commit_oid).unwrap();
3724        refs::write_ref(repo.git_dir(), "refs/heads/main", &commit_oid).unwrap();
3725        repo
3726    }
3727
3728    #[test]
3729    fn create_store_list_drop_and_diff_public_api() {
3730        let tmp = TempDir::new().unwrap();
3731        let repo = init_repo(tmp.path());
3732        let ident = "T <t@t> 1 +0000";
3733        fs::write(tmp.path().join("f"), b"changed\n").unwrap();
3734        let opts = StashPushOptions {
3735            message: Some("msg".into()),
3736            include_untracked: false,
3737            identity: ident.parse().expect("signature"),
3738            selection: None,
3739            pathspecs: Vec::new(),
3740            dry_run: false,
3741            mode: StashMode::default(),
3742        };
3743        let oid = create_stash(&repo, &opts).expect("create").expect("some");
3744        store_stash(&repo, oid, "On main: msg", ident).expect("store");
3745        let listed = list_stashes(&repo).expect("list");
3746        assert_eq!(listed.len(), 1);
3747        assert_eq!(listed[0].oid, oid);
3748        let diffs = stash_diff(&repo, 0, &StashDiffOptions::default()).expect("diff");
3749        assert!(!diffs.is_empty());
3750        let dropped = drop_stash(&repo, 0).expect("drop");
3751        assert_eq!(dropped, oid);
3752        assert!(list_stashes(&repo).expect("list").is_empty());
3753    }
3754
3755    #[test]
3756    fn push_stash_refreshes_index_stat_for_clean_status() {
3757        use crate::porcelain::status::{status, StatusOptions};
3758        use crate::progress::NullProgress;
3759
3760        let tmp = TempDir::new().unwrap();
3761        let repo = init_repo(tmp.path());
3762        fs::write(tmp.path().join("f"), b"base\n").unwrap();
3763        fs::write(tmp.path().join("g"), b"also\n").unwrap();
3764        let mut index = repo.load_index().unwrap();
3765        for (path, bytes) in [("f", b"base\n" as &[u8]), ("g", b"also\n")] {
3766            let oid = repo.odb().write(ObjectKind::Blob, bytes).unwrap();
3767            index.add_or_replace(
3768                entry_from_stat(&tmp.path().join(path), path.as_bytes(), oid, MODE_REGULAR)
3769                    .unwrap(),
3770            );
3771        }
3772        index.sort();
3773        repo.write_index(&mut index).unwrap();
3774        let tree = write_stash_tree_from_index(&repo, &mut index).unwrap();
3775        let commit = CommitData {
3776            tree,
3777            parents: vec![],
3778            author: "T <t@t> 0 +0000".into(),
3779            committer: "T <t@t> 0 +0000".into(),
3780            author_raw: Vec::new(),
3781            committer_raw: Vec::new(),
3782            encoding: None,
3783            message: "two files\n".into(),
3784            raw_message: None,
3785            extra_headers: Vec::new(),
3786        };
3787        let head = write_commit_object(&repo, &commit, None).unwrap();
3788        refs::write_ref(repo.git_dir(), "HEAD", &head).unwrap();
3789        refs::write_ref(repo.git_dir(), "refs/heads/main", &head).unwrap();
3790
3791        fs::write(tmp.path().join("f"), b"changed\n").unwrap();
3792        let opts = StashPushOptions {
3793            message: None,
3794            include_untracked: false,
3795            identity: "T <t@t> 1 +0000".parse().expect("signature"),
3796            selection: None,
3797            pathspecs: Vec::new(),
3798            dry_run: false,
3799            mode: StashMode::default(),
3800        };
3801        push_stash(&repo, &opts, &mut NullProgress, CancelToken::never_ref())
3802            .expect("push")
3803            .expect("oid");
3804
3805        let index = repo.load_index().unwrap();
3806        assert!(index.get(b"f", 0).expect("f").size > 0);
3807        assert!(index.get(b"g", 0).expect("g").size > 0);
3808        let st = status(
3809            &repo,
3810            &StatusOptions::default(),
3811            &mut NullProgress,
3812            CancelToken::never_ref(),
3813        )
3814        .expect("status");
3815        assert!(
3816            st.unstaged.is_empty(),
3817            "worktree matches HEAD after stash push"
3818        );
3819        assert!(st.staged.is_empty());
3820    }
3821
3822    #[test]
3823    fn push_stash_returns_none_when_clean() {
3824        let tmp = TempDir::new().unwrap();
3825        let repo = init_repo(tmp.path());
3826        let opts = StashPushOptions {
3827            message: None,
3828            include_untracked: false,
3829            identity: "T <t@t> 1 +0000".parse().expect("signature"),
3830            selection: None,
3831            pathspecs: Vec::new(),
3832            dry_run: false,
3833            mode: StashMode::default(),
3834        };
3835        assert!(
3836            push_stash(&repo, &opts, &mut NullProgress, CancelToken::never_ref())
3837                .expect("push")
3838                .is_none()
3839        );
3840    }
3841
3842    #[test]
3843    fn drop_stash_commit_races_concurrent_stash_push() {
3844        use std::sync::Arc;
3845        use std::thread;
3846
3847        let tmp = TempDir::new().unwrap();
3848        let repo = Arc::new(init_repo(tmp.path()));
3849        let ident = "T <t@t> 1 +0000";
3850        fs::write(tmp.path().join("f"), b"dirty\n").unwrap();
3851        let opts = StashPushOptions {
3852            message: Some("m".into()),
3853            include_untracked: false,
3854            identity: ident.parse().expect("signature"),
3855            selection: None,
3856            pathspecs: Vec::new(),
3857            dry_run: false,
3858            mode: StashMode::default(),
3859        };
3860        let oid = create_stash(&repo, &opts).expect("create").expect("some");
3861        store_stash(&repo, oid, "On main: m", ident).expect("store");
3862        let drop_repo = repo.clone();
3863        let drop_oid = oid;
3864        let dropper = thread::spawn(move || {
3865            for _ in 0..50 {
3866                let _ = drop_stash_commit(drop_repo.as_ref(), &drop_oid);
3867            }
3868        });
3869        let mut pushed = 0usize;
3870        while !dropper.is_finished() {
3871            fs::write(tmp.path().join("f"), format!("v{pushed}\n")).unwrap();
3872            if push_stash(&repo, &opts, &mut NullProgress, CancelToken::never_ref())
3873                .expect("push")
3874                .is_some()
3875            {
3876                pushed += 1;
3877            }
3878        }
3879        dropper.join().expect("join");
3880        assert!(
3881            list_stashes(&repo).expect("list").len() >= pushed,
3882            "concurrent stash pushes lost during drop_stash_commit"
3883        );
3884    }
3885
3886    #[test]
3887    fn drop_stash_commit_removes_tip_after_store() {
3888        let tmp = TempDir::new().unwrap();
3889        let repo = init_repo(tmp.path());
3890        let ident = "T <t@t> 1 +0000";
3891        fs::write(tmp.path().join("f"), b"dirty\n").unwrap();
3892        let opts = StashPushOptions {
3893            message: Some("m".into()),
3894            include_untracked: false,
3895            identity: ident.parse().expect("signature"),
3896            selection: None,
3897            pathspecs: Vec::new(),
3898            dry_run: false,
3899            mode: StashMode::default(),
3900        };
3901        let oid = create_stash(&repo, &opts).expect("create").expect("some");
3902        store_stash(&repo, oid, "On main: m", ident).expect("store");
3903        assert_eq!(list_stashes(&repo).expect("list").len(), 1);
3904        assert!(drop_stash_commit(&repo, &oid).expect("drop"));
3905        assert!(
3906            list_stashes(&repo).expect("list").is_empty(),
3907            "rollback must remove the tip entry"
3908        );
3909    }
3910
3911    #[test]
3912    fn stash_delta_keeps_only_changed_leaves_and_validates_paths() {
3913        use crate::objects::{serialize_tree, TreeEntry};
3914        let tmp = TempDir::new().unwrap();
3915        let repo = init_repo(tmp.path());
3916        let blob = repo.odb().write(ObjectKind::Blob, b"base").unwrap();
3917        let changed = repo.odb().write(ObjectKind::Blob, b"changed").unwrap();
3918        let tree = |entries: Vec<TreeEntry>| {
3919            repo.odb()
3920                .write(ObjectKind::Tree, &serialize_tree(&entries))
3921                .unwrap()
3922        };
3923        let leaf = |name: &str, mode, oid| TreeEntry {
3924            name: name.as_bytes().to_vec(),
3925            mode,
3926            oid,
3927        };
3928        let stable = tree(
3929            (0..20_000)
3930                .map(|i| leaf(&format!("f{i:05}"), MODE_REGULAR, blob))
3931                .collect(),
3932        );
3933        let base = tree(vec![
3934            leaf("edited", MODE_REGULAR, blob),
3935            leaf("removed", MODE_REGULAR, blob),
3936            leaf("stable", MODE_TREE, stable),
3937        ]);
3938        let other = tree(vec![
3939            leaf("added", MODE_REGULAR, changed),
3940            leaf("edited", 0o100755, changed),
3941            leaf("stable", MODE_TREE, stable),
3942        ]);
3943        let delta = StashTreeDelta::read(&repo, &base, &other).unwrap();
3944        assert_eq!(delta.base.len(), 2);
3945        assert_eq!(
3946            delta
3947                .changes
3948                .iter()
3949                .map(|(p, _)| p.as_slice())
3950                .collect::<Vec<_>>(),
3951            [b"added".as_slice(), b"edited", b"removed"]
3952        );
3953        assert_eq!(delta.changes[1].1.as_ref().unwrap().mode, 0o100755);
3954        assert!(delta.changes[2].1.is_none());
3955        assert!(stash_tree_entry_at_path(&repo, base, b"removed/child")
3956            .unwrap()
3957            .is_none());
3958        assert!(stash_tree_entry_at_path(&repo, base, b"stable")
3959            .unwrap()
3960            .is_none());
3961        assert_eq!(
3962            stash_tree_entry_at_path(&repo, base, b"stable/f19999")
3963                .unwrap()
3964                .unwrap()
3965                .oid,
3966            blob
3967        );
3968        let bad = tree(vec![leaf(".git", MODE_REGULAR, changed)]);
3969        assert!(StashTreeDelta::read(&repo, &base, &bad).is_err());
3970    }
3971
3972    #[test]
3973    fn stash_delta_decodes_paths_before_validation_and_lookup() {
3974        use crate::index::MODE_REGULAR;
3975        use crate::objects::{serialize_tree, TreeEntry};
3976
3977        let tmp = TempDir::new().unwrap();
3978        let repo = init_repo(tmp.path());
3979        let blob = repo.odb().write(ObjectKind::Blob, b"base").unwrap();
3980        let tree = |name: &[u8], mode, oid| {
3981            repo.odb()
3982                .write(
3983                    ObjectKind::Tree,
3984                    &serialize_tree(&[TreeEntry {
3985                        name: name.to_vec(),
3986                        mode,
3987                        oid,
3988                    }]),
3989                )
3990                .unwrap()
3991        };
3992        let empty = repo.odb().write(ObjectKind::Tree, b"").unwrap();
3993        for path in [b"grit+pathhex:6162".as_slice(), b"non-utf8-\xff"] {
3994            let other = tree(path, MODE_REGULAR, blob);
3995            let delta = StashTreeDelta::read(&repo, &empty, &other).unwrap();
3996            assert_eq!(delta.changes[0].0, path);
3997            assert_eq!(
3998                stash_tree_entry_at_path(&repo, other, path)
3999                    .unwrap()
4000                    .unwrap()
4001                    .oid,
4002                blob
4003            );
4004        }
4005        let unsafe_child = tree(b".git", MODE_REGULAR, blob);
4006        let other = tree(b"non-utf8-\xff", MODE_TREE, unsafe_child);
4007        assert!(StashTreeDelta::read(&repo, &empty, &other).is_err());
4008    }
4009
4010    #[test]
4011    fn check_stash_untracked_restore_rejects_collision() {
4012        let tmp = TempDir::new().unwrap();
4013        let repo = init_repo(tmp.path());
4014        let ident = "T <t@t> 1 +0000";
4015        fs::write(tmp.path().join("u.txt"), b"stashed\n").unwrap();
4016        let opts = StashPushOptions {
4017            message: Some("m".into()),
4018            include_untracked: true,
4019            identity: ident.parse().expect("signature"),
4020            selection: None,
4021            pathspecs: Vec::new(),
4022            dry_run: false,
4023            mode: StashMode::default(),
4024        };
4025        push_stash(&repo, &opts, &mut NullProgress, CancelToken::never_ref())
4026            .expect("push")
4027            .expect("oid");
4028        fs::write(tmp.path().join("u.txt"), b"precious\n").unwrap();
4029        let oid = list_stashes(&repo).expect("list")[0].oid;
4030        let err = super::apply_stash_oid(
4031            &repo,
4032            &oid,
4033            &StashApplyOptions::default(),
4034            &mut NullProgress,
4035            CancelToken::never_ref(),
4036        )
4037        .expect_err("collision");
4038        assert!(matches!(
4039            err,
4040            crate::error::Error::Stash(StashError::CouldNotRestoreUntracked { ref path }) if path == "u.txt"
4041        ));
4042    }
4043}
4044
4045#[cfg(test)]
4046mod hunk_push_tests {
4047    #![allow(clippy::expect_used, clippy::unwrap_used)]
4048
4049    use super::*;
4050    use crate::diff::{hunk_ids, DiffSide};
4051    use crate::diff::{unstaged_file_diffs_with_peer_hunks, DiffOptions};
4052    use crate::environment::RepositoryOptions;
4053    use crate::porcelain::hunk_select::{HunkSelection, LineRange};
4054    use crate::porcelain::index_from_tree::index_from_tree;
4055    use crate::repo::Repository;
4056    use std::process::Command;
4057    use tempfile::TempDir;
4058
4059    fn git(dir: &std::path::Path, args: &[&str]) {
4060        let out = Command::new("git")
4061            .current_dir(dir)
4062            .args(args)
4063            .env("GIT_CONFIG_GLOBAL", "/dev/null")
4064            .env("GIT_CONFIG_SYSTEM", "/dev/null")
4065            .output()
4066            .expect("git");
4067        assert!(
4068            out.status.success(),
4069            "git {args:?}: {}",
4070            String::from_utf8_lossy(&out.stderr)
4071        );
4072    }
4073
4074    fn open_repo(root: &std::path::Path) -> Repository {
4075        git(root, &["config", "user.email", "t@example.com"]);
4076        git(root, &["config", "user.name", "Test"]);
4077        Repository::discover(Some(root), &RepositoryOptions::empty()).expect("discover")
4078    }
4079
4080    fn two_hunk_file() -> (String, String) {
4081        let mut base = String::new();
4082        for i in 0..24 {
4083            base.push_str(&format!("line{i}\n"));
4084        }
4085        let mut edited = base.clone();
4086        edited = edited.replacen("line5\n", "LINE5\n", 1);
4087        edited = edited.replacen("line18\n", "LINE18\n", 1);
4088        (base, edited)
4089    }
4090
4091    fn tree_blob(repo: &Repository, tree_oid: &ObjectId, path: &str) -> Vec<u8> {
4092        let index = index_from_tree(repo, tree_oid).expect("tree index");
4093        let entry = index.get(path.as_bytes(), 0).expect("path in tree");
4094        repo.odb().read(&entry.oid).expect("blob").data
4095    }
4096
4097    fn stash_w_tree(repo: &Repository, stash_oid: &ObjectId) -> ObjectId {
4098        repo.odb().commit_tree(stash_oid).unwrap()
4099    }
4100
4101    fn hunk_selection_for_first_hunk(repo: &Repository) -> HunkSelection {
4102        let (files, peers) =
4103            unstaged_file_diffs_with_peer_hunks(repo, &[], DiffOptions::default()).unwrap();
4104        let ids = hunk_ids(
4105            DiffSide::Unstaged,
4106            "f.txt",
4107            &files[0].hunks,
4108            peers.get("f.txt").map(|v| v.as_slice()).unwrap_or(&[]),
4109        );
4110        HunkSelection {
4111            ids: vec![ids[0].clone()],
4112            ranges: Vec::new(),
4113        }
4114    }
4115
4116    const IDENT: &str = "Test <t@example.com> 1000000000 +0000";
4117
4118    fn setup_two_hunk_repo() -> (TempDir, Repository, HunkSelection) {
4119        let tmp = TempDir::new().unwrap();
4120        let root = tmp.path();
4121        git(root, &["init", "-q", "-b", "main"]);
4122        let (base, edited) = two_hunk_file();
4123        fs::write(root.join("f.txt"), base).unwrap();
4124        git(root, &["add", "f.txt"]);
4125        git(root, &["commit", "-qm", "init"]);
4126        let repo = open_repo(root);
4127        fs::write(root.join("f.txt"), edited).unwrap();
4128        let selection = hunk_selection_for_first_hunk(&repo);
4129        (tmp, repo, selection)
4130    }
4131
4132    #[cfg_attr(
4133        not(feature = "full-tests"),
4134        ignore = "starts system git or is heavy; run with --features full-tests"
4135    )]
4136    #[test]
4137    fn stash_push_hunks_dry_run_does_not_mutate_repo() {
4138        let (tmp, repo, selection) = setup_two_hunk_repo();
4139        let selected_ids = selection.ids.clone();
4140        let before = fs::read_to_string(tmp.path().join("f.txt")).unwrap();
4141        let preview = preview_stash(
4142            &repo,
4143            &StashPushOptions {
4144                message: Some("preview".into()),
4145                include_untracked: false,
4146                identity: IDENT.parse().expect("signature"),
4147                selection: Some(selection),
4148                pathspecs: Vec::new(),
4149                dry_run: true,
4150                mode: StashMode::default(),
4151            },
4152        )
4153        .expect("preview")
4154        .expect("paths");
4155        assert!(preview.paths.iter().any(|p| p == "f.txt"));
4156        assert_eq!(
4157            preview.stashed_hunks,
4158            BTreeMap::from([("f.txt".to_string(), selected_ids)])
4159        );
4160        assert!(preview.stashed_lines.is_empty());
4161        assert_eq!(list_stashes(&repo).expect("list").len(), 0);
4162        assert_eq!(
4163            fs::read_to_string(tmp.path().join("f.txt")).unwrap(),
4164            before,
4165            "dry-run must not change worktree"
4166        );
4167    }
4168
4169    #[cfg_attr(
4170        not(feature = "full-tests"),
4171        ignore = "starts system git or is heavy; run with --features full-tests"
4172    )]
4173    #[test]
4174    fn stash_push_hunks_stashes_only_selected() {
4175        let (tmp, repo, selection) = setup_two_hunk_repo();
4176        let selected_ids = selection.ids.clone();
4177        let pushed = push_stash(
4178            &repo,
4179            &StashPushOptions {
4180                message: Some("partial".into()),
4181                include_untracked: false,
4182                identity: IDENT.parse().expect("signature"),
4183                selection: Some(selection),
4184                pathspecs: Vec::new(),
4185                dry_run: false,
4186                mode: StashMode::default(),
4187            },
4188            &mut NullProgress,
4189            CancelToken::never_ref(),
4190        )
4191        .expect("push")
4192        .expect("oid");
4193        assert_eq!(
4194            pushed.stashed_hunks,
4195            BTreeMap::from([("f.txt".to_string(), selected_ids)])
4196        );
4197        assert!(pushed.stashed_lines.is_empty());
4198        let w_tree = stash_w_tree(&repo, &pushed.oid);
4199        let blob = tree_blob(&repo, &w_tree, "f.txt");
4200        let text = String::from_utf8_lossy(&blob);
4201        assert!(text.contains("LINE5"), "stashed hunk in W tree: {text}");
4202        assert!(
4203            !text.contains("LINE18"),
4204            "unselected hunk must not be in stash tree: {text}"
4205        );
4206        git(tmp.path(), &["fsck", "--strict"]);
4207    }
4208
4209    #[cfg_attr(
4210        not(feature = "full-tests"),
4211        ignore = "starts system git or is heavy; run with --features full-tests"
4212    )]
4213    #[test]
4214    fn stash_push_hunks_worktree_keeps_rest() {
4215        let (tmp, repo, selection) = setup_two_hunk_repo();
4216        push_stash(
4217            &repo,
4218            &StashPushOptions {
4219                message: None,
4220                include_untracked: false,
4221                identity: IDENT.parse().expect("signature"),
4222                selection: Some(selection),
4223                pathspecs: Vec::new(),
4224                dry_run: false,
4225                mode: StashMode::default(),
4226            },
4227            &mut NullProgress,
4228            CancelToken::never_ref(),
4229        )
4230        .expect("push")
4231        .expect("oid");
4232        let on_disk = fs::read_to_string(tmp.path().join("f.txt")).unwrap();
4233        assert!(
4234            on_disk.contains("line5\n") && !on_disk.contains("LINE5"),
4235            "first hunk reverted toward index: {on_disk}"
4236        );
4237        assert!(
4238            on_disk.contains("LINE18"),
4239            "second hunk still unstaged on disk: {on_disk}"
4240        );
4241        git(tmp.path(), &["fsck", "--strict"]);
4242    }
4243
4244    #[cfg_attr(
4245        not(feature = "full-tests"),
4246        ignore = "starts system git or is heavy; run with --features full-tests"
4247    )]
4248    #[test]
4249    fn stash_push_hunks_roundtrip_with_git_stash_apply() {
4250        let (tmp, repo, selection) = setup_two_hunk_repo();
4251        push_stash(
4252            &repo,
4253            &StashPushOptions {
4254                message: None,
4255                include_untracked: false,
4256                identity: IDENT.parse().expect("signature"),
4257                selection: Some(selection),
4258                pathspecs: Vec::new(),
4259                dry_run: false,
4260                mode: StashMode::default(),
4261            },
4262            &mut NullProgress,
4263            CancelToken::never_ref(),
4264        )
4265        .expect("push")
4266        .expect("oid");
4267        git(
4268            tmp.path(),
4269            &["restore", "--worktree", "--source=HEAD", "--", "f.txt"],
4270        );
4271        git(tmp.path(), &["stash", "apply"]);
4272        let on_disk = fs::read_to_string(tmp.path().join("f.txt")).unwrap();
4273        assert!(on_disk.contains("LINE5"), "git stash apply restored hunk");
4274        git(tmp.path(), &["fsck", "--strict"]);
4275    }
4276
4277    #[cfg_attr(
4278        not(feature = "full-tests"),
4279        ignore = "starts system git or is heavy; run with --features full-tests"
4280    )]
4281    #[test]
4282    fn stash_push_hunks_pop_restores() {
4283        let (tmp, repo, selection) = setup_two_hunk_repo();
4284        push_stash(
4285            &repo,
4286            &StashPushOptions {
4287                message: None,
4288                include_untracked: false,
4289                identity: IDENT.parse().expect("signature"),
4290                selection: Some(selection),
4291                pathspecs: Vec::new(),
4292                dry_run: false,
4293                mode: StashMode::default(),
4294            },
4295            &mut NullProgress,
4296            CancelToken::never_ref(),
4297        )
4298        .expect("push")
4299        .expect("oid");
4300        git(
4301            tmp.path(),
4302            &["restore", "--worktree", "--source=HEAD", "--", "f.txt"],
4303        );
4304        git(tmp.path(), &["stash", "pop"]);
4305        let on_disk = fs::read_to_string(tmp.path().join("f.txt")).unwrap();
4306        assert!(
4307            on_disk.contains("LINE5"),
4308            "pop restored stashed hunk: {on_disk}"
4309        );
4310        git(tmp.path(), &["fsck", "--strict"]);
4311    }
4312
4313    fn options_with(selection: Option<HunkSelection>, include_untracked: bool) -> StashPushOptions {
4314        StashPushOptions {
4315            message: None,
4316            include_untracked,
4317            identity: IDENT.parse().expect("signature"),
4318            selection,
4319            pathspecs: Vec::new(),
4320            dry_run: false,
4321            mode: StashMode::default(),
4322        }
4323    }
4324
4325    #[test]
4326    fn validate_rejects_include_untracked_with_selection() {
4327        let selection = HunkSelection {
4328            ids: Vec::new(),
4329            ranges: vec![LineRange {
4330                path: "f.txt".into(),
4331                start: 1,
4332                end: 1,
4333            }],
4334        };
4335        let err = options_with(Some(selection), true)
4336            .validate()
4337            .expect_err("conflict");
4338        assert!(
4339            matches!(err, StashPushValidationError::UntrackedWithSelection),
4340            "got {err:?}"
4341        );
4342    }
4343
4344    #[test]
4345    fn validate_allows_include_untracked_with_empty_selection() {
4346        options_with(Some(HunkSelection::default()), true)
4347            .validate()
4348            .expect("an empty selection is a full stash");
4349        options_with(None, true).validate().expect("no selection");
4350    }
4351
4352    #[cfg_attr(
4353        not(feature = "full-tests"),
4354        ignore = "starts system git or is heavy; run with --features full-tests"
4355    )]
4356    #[test]
4357    fn stash_push_lines_reports_line_labels() {
4358        let (tmp, repo, _) = setup_two_hunk_repo();
4359        let selection = HunkSelection {
4360            ids: Vec::new(),
4361            ranges: vec![LineRange {
4362                path: "f.txt".into(),
4363                start: 6,
4364                end: 6,
4365            }],
4366        };
4367        let preview = preview_stash(&repo, &options_with(Some(selection.clone()), false))
4368            .expect("preview")
4369            .expect("something to stash");
4370        let expected_lines = BTreeMap::from([("f.txt".to_string(), vec!["6".to_string()])]);
4371        assert_eq!(preview.stashed_lines, expected_lines);
4372        assert!(preview.stashed_hunks.is_empty());
4373
4374        let pushed = push_stash(
4375            &repo,
4376            &options_with(Some(selection), false),
4377            &mut NullProgress,
4378            CancelToken::never_ref(),
4379        )
4380        .expect("push")
4381        .expect("stashed");
4382        assert_eq!(pushed.stashed_lines, expected_lines);
4383        assert!(pushed.stashed_hunks.is_empty());
4384        let on_disk = fs::read_to_string(tmp.path().join("f.txt")).unwrap();
4385        assert!(!on_disk.contains("LINE5") && on_disk.contains("LINE18"));
4386        git(tmp.path(), &["fsck", "--strict"]);
4387    }
4388
4389    #[cfg_attr(
4390        not(feature = "full-tests"),
4391        ignore = "starts system git or is heavy; run with --features full-tests"
4392    )]
4393    #[test]
4394    fn stash_push_without_selection_reports_no_hunks() {
4395        let (_tmp, repo, _) = setup_two_hunk_repo();
4396        let preview = preview_stash(&repo, &options_with(None, false))
4397            .expect("preview")
4398            .expect("something to stash");
4399        assert!(preview.stashed_hunks.is_empty() && preview.stashed_lines.is_empty());
4400        let pushed = push_stash(
4401            &repo,
4402            &options_with(None, false),
4403            &mut NullProgress,
4404            CancelToken::never_ref(),
4405        )
4406        .expect("push")
4407        .expect("stashed");
4408        assert!(pushed.stashed_hunks.is_empty() && pushed.stashed_lines.is_empty());
4409    }
4410}