Skip to main content

grit_lib/porcelain/
stash_error.rs

1//! Typed failures for stash list, push, apply, pop, and drop.
2
3use thiserror::Error;
4
5use crate::error::PathIoError;
6use crate::objects::ObjectId;
7use crate::porcelain::branch_error::BranchError;
8use crate::porcelain::hunk_select::HunkSelectError;
9
10/// Why a stash commit object cannot be interpreted for apply, show, or branch.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum CorruptStashReason {
14    /// The W commit has fewer than two parents (index and base).
15    InsufficientParents,
16}
17
18/// Incompatible [`super::stash::StashPushOptions`](crate::stash::StashPushOptions) flag combinations.
19///
20/// Returned from [`crate::stash::StashPushOptions::validate`] before any repository I/O.
21#[derive(Debug, Error, Clone, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum StashPushValidationError {
24    /// Author or committer line on [`crate::stash::StashPushOptions::identity`] is invalid.
25    #[error(transparent)]
26    InvalidSignature(#[from] crate::ident::SignatureError),
27
28    /// `--staged` with `--include-untracked`.
29    #[error("cannot combine --staged with --include-untracked")]
30    StagedWithUntracked,
31    /// `--staged` with `--hunks` or `--lines`.
32    #[error("cannot combine --staged with --hunks or --lines")]
33    StagedWithSelection,
34    /// `--keep-index` with `--hunks` or `--lines`.
35    #[error("cannot combine --keep-index with --hunks or --lines")]
36    KeepIndexWithSelection,
37    /// `--include-untracked` with `--hunks` or `--lines`.
38    #[error("cannot combine --include-untracked with --hunks or --lines")]
39    UntrackedWithSelection,
40    /// `--staged` on a path that also has unstaged worktree edits.
41    #[error("cannot stash staged changes for '{path}': worktree has unstaged changes")]
42    StagedWorktreeDirty {
43        /// Repository-relative path.
44        path: String,
45    },
46    /// [`crate::stash::StashPushOptions::dry_run`] on push; use preview instead.
47    #[error("dry-run is not supported on push; use preview instead")]
48    DryRunUsePreview,
49}
50
51/// Stash list, push, apply, pop, drop, and branch failures.
52#[derive(Debug, Error)]
53#[non_exhaustive]
54pub enum StashError {
55    /// Stash W commit has an invalid parent layout.
56    #[error("corrupt stash commit {oid}: {reason}")]
57    CorruptStash {
58        /// Stash W commit object id.
59        oid: ObjectId,
60        /// What was wrong with the commit graph.
61        reason: CorruptStashReason,
62    },
63
64    /// `stash@{{n}}` is out of range for the current stash reflog.
65    #[error("stash entry stash@{{{n}}} not found")]
66    NotFound {
67        /// Stash reflog index (`stash@{{n}}`).
68        n: usize,
69    },
70
71    /// A stash commit id was given to pop but is not on `refs/stash`.
72    #[error("stash commit {oid} is not on the stash stack")]
73    CommitNotOnStack {
74        /// Stash W commit object id.
75        oid: ObjectId,
76    },
77
78    /// Push or create requires at least one commit on the current branch.
79    #[error("cannot stash without a commit")]
80    NoInitialCommit,
81
82    /// Apply, push, or pop requires a working tree.
83    #[error("cannot stash in a bare repository")]
84    BareRepository,
85
86    /// Apply with `restore_index` could not merge the current index with the stashed index parent.
87    #[error("conflicts in index while applying stash with --index")]
88    IndexConflict,
89
90    /// `HEAD` does not resolve while applying a stash entry.
91    #[error("missing HEAD while applying stash")]
92    MissingHead,
93
94    /// Applying a stash would overwrite locally modified worktree content.
95    #[error(
96        "your local changes to the following files would be overwritten by stash apply: {paths}"
97    )]
98    WouldOverwriteLocalChanges {
99        /// Space-separated paths (same layout as Git's message list).
100        paths: String,
101    },
102
103    /// The index could not be written after a successful stash apply.
104    #[error("writing index after stash apply")]
105    IndexWrite {
106        /// Git-directory path I/O failure.
107        #[source]
108        source: PathIoError,
109    },
110
111    /// A symlink blob in a stash commit is not valid UTF-8.
112    #[error("symlink target is not UTF-8")]
113    SymlinkNotUtf8,
114
115    /// Applying a stash with an untracked-files parent would replace an existing worktree path.
116    #[error("stash untracked restore blocked: '{path}' already exists on disk")]
117    CouldNotRestoreUntracked {
118        /// Worktree path that already exists and blocks untracked restore.
119        path: String,
120    },
121
122    /// Partial push hunk selection failed.
123    #[error(transparent)]
124    HunkSelection(#[from] HunkSelectError),
125
126    /// Branch create during `stash branch` failed validation or state checks.
127    #[error(transparent)]
128    Branch(#[from] BranchError),
129
130    /// Patch application while building the W tree failed.
131    #[error(transparent)]
132    Apply(#[from] crate::error::ApplyError),
133
134    /// Identity on push options could not be written into a commit.
135    #[error(transparent)]
136    InvalidSignature(#[from] crate::ident::SignatureError),
137
138    /// Incompatible [`crate::stash::StashPushOptions`] flags (see [`StashPushValidationError`]).
139    #[error(transparent)]
140    PushValidation(#[from] StashPushValidationError),
141
142    /// Worktree path update failed while finishing a stash push reset.
143    #[error("could not update '{path}' while finishing stash: {message}")]
144    WorktreeUpdateFailed {
145        /// Repository-relative path.
146        path: String,
147        /// Apply or checkout detail.
148        message: String,
149    },
150}
151
152impl StashError {
153    pub(crate) fn corrupt_stash(oid: ObjectId, reason: CorruptStashReason) -> Self {
154        Self::CorruptStash { oid, reason }
155    }
156
157    pub(crate) fn from_apply_worktree(err: crate::error::ApplyError) -> crate::error::Error {
158        match err {
159            crate::error::ApplyError::Cancelled => crate::error::Error::Cancelled,
160            crate::error::ApplyError::Failed { path, message } if !path.is_empty() => {
161                Self::WorktreeUpdateFailed { path, message }.into()
162            }
163            other => Self::Apply(other).into(),
164        }
165    }
166}
167
168impl StashError {
169    /// Stable snake_case slug for this failure (the `kind` of its serialized form).
170    #[must_use]
171    pub fn kind_name(&self) -> &'static str {
172        match self {
173            Self::CorruptStash { .. } => "corrupt_stash",
174            Self::NotFound { .. } => "stash_not_found",
175            Self::CommitNotOnStack { .. } => "stash_commit_not_on_stack",
176            Self::NoInitialCommit => "stash_no_initial_commit",
177            Self::BareRepository => "stash_bare_repository",
178            Self::IndexConflict => "stash_index_conflict",
179            Self::MissingHead => "stash_missing_head",
180            Self::WouldOverwriteLocalChanges { .. } => "stash_would_overwrite_local_changes",
181            Self::IndexWrite { .. } => "stash_index_write",
182            Self::SymlinkNotUtf8 => "stash_symlink_not_utf8",
183            Self::CouldNotRestoreUntracked { .. } => "stash_could_not_restore_untracked",
184            Self::PushValidation(_) => "stash_option_conflict",
185            Self::HunkSelection(_) => "hunk_selection",
186            Self::Branch(_) => "branch",
187            Self::Apply(_) => "apply",
188            Self::InvalidSignature(_) => "invalid_signature",
189            Self::WorktreeUpdateFailed { .. } => "stash_worktree_update_failed",
190        }
191    }
192}
193
194#[cfg(feature = "serde-models")]
195impl serde::Serialize for StashError {
196    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
197    where
198        S: serde::Serializer,
199    {
200        use serde::ser::SerializeStruct;
201
202        match self {
203            Self::CouldNotRestoreUntracked { path } => {
204                let mut out = serializer.serialize_struct("Error", 3)?;
205                out.serialize_field("kind", self.kind_name())?;
206                out.serialize_field("message", &self.to_string())?;
207                out.serialize_field("path", path)?;
208                out.end()
209            }
210            _ => {
211                let mut out = serializer.serialize_struct("Error", 2)?;
212                out.serialize_field("kind", self.kind_name())?;
213                out.serialize_field("message", &self.to_string())?;
214                out.end()
215            }
216        }
217    }
218}
219
220impl std::fmt::Display for CorruptStashReason {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        match self {
223            Self::InsufficientParents => f.write_str("expected at least 2 parents"),
224        }
225    }
226}