Skip to main content

grit_lib/worktree/
error.rs

1//! Worktree-area failures: checkout, paths, pathspecs, filters, and linked worktrees.
2
3pub use super::linked_worktree_error::{LinkedWorktreeError, LinkedWorktreeOperation};
4
5#[cfg(doc)]
6use crate::error::Error;
7use crate::error::{
8    AttrPathspecError, ErrorSummary, FilterError, OverwriteReason, PathOutsideRepoError,
9    PathspecFromFileParseError, SubmoduleError, WorktreeOperation as DirtyWorktreeOperation,
10};
11
12/// Worktree-area failure (checkout, status, add/rm/mv/restore/clean, pathspec, filters, linked worktrees).
13///
14/// Surfaced on the umbrella as [`Error::Worktree`](crate::error::Error::Worktree).
15#[derive(Debug, thiserror::Error)]
16#[non_exhaustive]
17pub enum WorktreeError {
18    /// Linked worktree registry add/remove/move/lock/repair failure.
19    #[error(transparent)]
20    Linked(#[from] LinkedWorktreeError),
21
22    /// Filesystem I/O on a repository-relative worktree path.
23    #[error("{0}")]
24    PathIo(#[from] crate::error::PathIoError),
25
26    /// A worktree file changed while it was being hashed and stored.
27    #[error("{path} changed while it was being added")]
28    FileChanged {
29        /// Index-relative path of the file.
30        path: String,
31    },
32
33    /// General path resolution failure (invalid UTF-8, out-of-bounds, etc.).
34    #[error("path error: {detail}")]
35    Path {
36        /// What went wrong with the path.
37        detail: String,
38    },
39
40    /// A path that must be UTF-8 for this operation is not.
41    #[error("path is not valid UTF-8: {path}")]
42    NonUtf8Path {
43        /// The path with invalid bytes replaced.
44        path: String,
45    },
46
47    /// A path string failed validation (legacy invalid-path checks).
48    #[error("invalid path '{path}'")]
49    InvalidPath {
50        /// Offending path text.
51        path: String,
52    },
53
54    /// A repository-relative path failed component validation.
55    #[error("invalid path '{path}': {reason}")]
56    InvalidPathComponent {
57        /// Full repository-relative path that was rejected.
58        path: String,
59        /// Which component rule failed.
60        reason: crate::path_validate::PathComponentError,
61    },
62
63    /// Path resolves outside the repository.
64    #[error(transparent)]
65    OutsideRepo(#[from] PathOutsideRepoError),
66
67    /// `--pathspec-from-file` parse failure.
68    #[error(transparent)]
69    PathspecFromFile(#[from] PathspecFromFileParseError),
70
71    /// Malformed `:(attr:...)` pathspec magic.
72    #[error("invalid attr magic in pathspec '{spec}': {reason}")]
73    InvalidAttrPathspec {
74        /// The offending pathspec as given.
75        spec: String,
76        /// What is wrong with its attr clause.
77        #[source]
78        reason: AttrPathspecError,
79    },
80
81    /// Pathspec matched no tracked or indexed file.
82    #[error("pathspec '{spec}' did not match any file(s) known to git")]
83    PathspecNoMatch {
84        /// User-supplied pathspec that matched nothing.
85        spec: String,
86    },
87
88    /// Literal pathspec crosses a symlink directory component.
89    #[error("pathspec '{spec}' is beyond a symbolic link")]
90    PathspecBeyondSymlink {
91        /// User-supplied pathspec that crosses a symlink directory.
92        spec: String,
93    },
94
95    /// Explicit pathspecs name ignored paths.
96    #[error("the following paths are ignored:\n{}", paths.join("\n"))]
97    PathspecIgnored {
98        /// Repository-relative paths that cannot be staged while ignored.
99        paths: Vec<String>,
100    },
101
102    /// Restore conflict options combined with `--staged`.
103    #[error("conflict restore options cannot be used with --staged")]
104    RestoreConflictWithStaged,
105
106    /// Restore conflict options combined with `--source`.
107    #[error("conflict restore options cannot be used with --source")]
108    RestoreConflictWithSource,
109
110    /// Missing "theirs" stage for a conflict restore path.
111    #[error("path '{path}' does not have their version")]
112    RestoreConflictMissingTheirs {
113        /// Repository-relative path.
114        path: String,
115    },
116
117    /// Missing "ours" stage for a conflict restore path.
118    #[error("path '{path}' does not have our version")]
119    RestoreConflictMissingOurs {
120        /// Repository-relative path.
121        path: String,
122    },
123
124    /// Path is not unmerged when remerge was requested.
125    #[error("path '{path}' is not unmerged")]
126    RestoreConflictNotUnmerged {
127        /// Repository-relative path.
128        path: String,
129    },
130
131    /// Worktree restore requested for paths that still have conflict stages.
132    #[error("{}", crate::error::restore_unmerged_message(paths))]
133    RestorePathUnmerged {
134        /// Matched repository-relative paths with conflict stages (sorted, deduplicated).
135        paths: Vec<String>,
136    },
137
138    /// Nested `.git` checkout has no commit on its current branch.
139    #[error("embedded git repository '{path}' has no commit checked out")]
140    EmbeddedRepoWithoutCommit {
141        /// Repository-relative path to the nested checkout directory.
142        path: String,
143    },
144
145    /// Remove refused paths with unsaved content without `--force`.
146    #[error(
147        "refusing to remove paths with unsaved content:\n{}",
148        paths.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n")
149    )]
150    RemoveBlocked {
151        /// Each refused path with the reason it was refused.
152        paths: Vec<crate::porcelain::paths::BlockedRemoval>,
153    },
154
155    /// Directory pathspec without `-r` on remove.
156    #[error("not removing '{path}' recursively without -r")]
157    NotRemovingRecursively {
158        /// Directory path that requires `-r`.
159        path: String,
160    },
161
162    /// Remove called with no pathspecs.
163    #[error("you must specify path(s) to remove")]
164    RemovePathsRequired,
165
166    /// Clean refused to remove a directory that contains the current working directory.
167    #[error("refusing to remove '{path}' because it contains the current directory")]
168    RemoveContainsCurrentDirectory {
169        /// Repository-relative directory path.
170        path: String,
171    },
172
173    /// Restore called with no pathspecs.
174    #[error("you must specify path(s) to restore")]
175    RestorePathsRequired,
176
177    /// Restore was asked both to pick a conflict side and to rebuild conflict markers.
178    #[error("cannot combine choosing a conflict side with rebuilding the conflict")]
179    RestoreStageWithRemerge,
180
181    /// Operation requires a checked-out work tree.
182    #[error("this operation must be run in a work tree")]
183    RequiresWorkTree,
184
185    /// Move source is not tracked.
186    #[error("'{src}' is not under version control")]
187    MoveSourceNotTracked {
188        /// Untracked or missing source path.
189        src: String,
190    },
191
192    /// Move destination exists without `--force`.
193    #[error("destination '{destination}' already exists")]
194    MoveDestinationExists {
195        /// Source path in the move request.
196        src: String,
197        /// Existing destination path.
198        destination: String,
199    },
200
201    /// Trailing slash named a destination that is not a directory.
202    #[error("destination '{destination}' is not a directory")]
203    MoveDestinationNotDirectory {
204        /// Destination path (trailing slash already removed).
205        destination: String,
206    },
207
208    /// Destination lies under the source directory.
209    #[error("cannot move '{src}' to a subdirectory of itself, '{destination}'")]
210    MoveIntoSubdirectory {
211        /// Source directory path.
212        src: String,
213        /// Invalid destination under the source.
214        destination: String,
215    },
216
217    /// Source and destination are the same path.
218    #[error("cannot move '{src}' into itself")]
219    MoveIntoSelf {
220        /// Source path.
221        src: String,
222        /// Destination equal to the source.
223        destination: String,
224    },
225
226    /// Source has no index entries to move.
227    #[error("nothing to move from '{src}'")]
228    MoveNothingToMove {
229        /// Source path with no index entries.
230        src: String,
231    },
232
233    /// Multiple sources would move to the same destination.
234    #[error("multiple sources would move to '{destination}'")]
235    MoveDuplicateDestination {
236        /// Destination path that would receive more than one source.
237        destination: String,
238    },
239
240    /// Move source path is missing or not a file, directory, or symlink.
241    #[error("cannot move '{src}' to '{destination}': bad source path")]
242    MoveBadSource {
243        /// Source path.
244        src: String,
245        /// Planned destination path.
246        destination: String,
247    },
248
249    /// Internal invariant: missing index entry during a move.
250    #[error("internal error: missing index entry for '{path}'")]
251    MoveMissingIndexEntry {
252        /// Index path that should exist during a move.
253        path: String,
254    },
255
256    /// Checkout or switch would overwrite local or untracked content.
257    #[error("{message}")]
258    WouldOverwrite {
259        /// Whether tracked local edits or untracked paths block the operation.
260        reason: OverwriteReason,
261        /// Repository-relative paths that would be overwritten (sorted, deduplicated).
262        paths: Vec<String>,
263        /// Human-readable summary (depends on [`OverwriteReason`]).
264        message: String,
265    },
266
267    /// Staged or unstaged changes block an operation that needs a clean worktree.
268    #[error("you have uncommitted changes — commit them before {operation}")]
269    DirtyWorktree {
270        /// The operation that was refused.
271        operation: DirtyWorktreeOperation,
272        /// Repository-relative paths with staged or unstaged changes (sorted, deduplicated).
273        paths: Vec<String>,
274    },
275
276    /// A checkout failed or was cancelled before it finished, and putting the work tree back
277    /// failed for some paths.
278    ///
279    /// Refs and the index are unchanged, as after any failed checkout; only `unrestored`
280    /// differ from the index. [`Error::is_cancelled`] reports whether `source` was a
281    /// cancellation.
282    #[error("{source}; {} work-tree path(s) could not be restored", unrestored.len())]
283    CheckoutRollbackIncomplete {
284        /// Why the checkout stopped.
285        source: ErrorSummary,
286        /// Repository-relative paths left different from the index (sorted, deduplicated).
287        unrestored: Vec<String>,
288    },
289
290    /// A move failed, and putting the work tree back failed too.
291    ///
292    /// The index is unchanged; renames that could not be reversed and forced-destination
293    /// backups that could not be restored are left as they are on disk.
294    #[error("{}", move_rollback_incomplete_message(source, *unreversed, backup_restore.as_ref()))]
295    MoveRollbackIncomplete {
296        /// Why the move stopped.
297        source: ErrorSummary,
298        /// Number of completed renames that could not be reversed.
299        unreversed: usize,
300        /// Why restoring the destinations a forced move replaced failed, when it did.
301        backup_restore: Option<ErrorSummary>,
302    },
303
304    /// Staging refused paths that still contain conflict markers.
305    #[error("unmerged paths still have conflict markers")]
306    UnmergedConflictMarkers {
307        /// Repository-relative paths that were not staged because markers remain.
308        paths: Vec<String>,
309    },
310
311    /// Clean/smudge filter or EOL conversion failure.
312    #[error(transparent)]
313    Filter(#[from] FilterError),
314
315    /// Submodule layout or state failure during worktree operations.
316    #[error(transparent)]
317    Submodule(#[from] SubmoduleError),
318}
319
320impl WorktreeError {
321    /// Whether this failure records a cancellation (a checkout whose rollback was incomplete
322    /// after it was cancelled).
323    #[must_use]
324    pub fn is_cancelled(&self) -> bool {
325        match self {
326            Self::CheckoutRollbackIncomplete { source, .. }
327            | Self::MoveRollbackIncomplete { source, .. } => source.is_cancelled(),
328            _ => false,
329        }
330    }
331
332    /// Stable snake_case slug for this failure (matches former [`Error::kind_name`] values).
333    #[must_use]
334    pub fn kind_name(&self) -> &'static str {
335        match self {
336            Self::Linked(_) => "worktree",
337            Self::PathIo(path_io) => match path_io.operation {
338                crate::error::PathIoOperation::Worktree(_) => "worktree_path_io",
339                crate::error::PathIoOperation::GitDir(_) => "git_dir_path_io",
340            },
341            Self::FileChanged { .. } => "worktree_file_changed",
342            Self::Path { .. } => "path_error",
343            Self::NonUtf8Path { .. } => "non_utf8_path",
344            Self::InvalidPath { .. } => "invalid_path",
345            Self::InvalidPathComponent { .. } => "invalid_path_component",
346            Self::OutsideRepo(_) => "path_outside_repo",
347            Self::PathspecFromFile(_) => "pathspec_from_file",
348            Self::InvalidAttrPathspec { .. } => "invalid_attr_pathspec",
349            Self::PathspecNoMatch { .. } => "pathspec_no_match",
350            Self::PathspecBeyondSymlink { .. } => "pathspec_beyond_symlink",
351            Self::PathspecIgnored { .. } => "pathspec_ignored",
352            Self::RestoreConflictWithStaged => "restore_conflict_with_staged",
353            Self::RestoreConflictWithSource => "restore_conflict_with_source",
354            Self::RestoreConflictMissingTheirs { .. } => "restore_conflict_missing_theirs",
355            Self::RestoreConflictMissingOurs { .. } => "restore_conflict_missing_ours",
356            Self::RestoreConflictNotUnmerged { .. } => "restore_conflict_not_unmerged",
357            Self::RestorePathUnmerged { .. } => "restore_path_unmerged",
358            Self::EmbeddedRepoWithoutCommit { .. } => "embedded_repo_without_commit",
359            Self::RemoveBlocked { .. } => "remove_blocked",
360            Self::NotRemovingRecursively { .. } => "not_removing_recursively",
361            Self::RemovePathsRequired => "remove_paths_required",
362            Self::RemoveContainsCurrentDirectory { .. } => "remove_contains_current_directory",
363            Self::RestorePathsRequired => "restore_paths_required",
364            Self::RestoreStageWithRemerge => "restore_stage_with_remerge",
365            Self::MoveRollbackIncomplete { .. } => "move_rollback_incomplete",
366            Self::RequiresWorkTree => "requires_work_tree",
367            Self::MoveSourceNotTracked { .. } => "move_source_not_tracked",
368            Self::MoveDestinationExists { .. } => "move_destination_exists",
369            Self::MoveDestinationNotDirectory { .. } => "move_destination_not_directory",
370            Self::MoveIntoSubdirectory { .. } => "move_into_subdirectory",
371            Self::MoveIntoSelf { .. } => "move_into_self",
372            Self::MoveNothingToMove { .. } => "move_nothing_to_move",
373            Self::MoveDuplicateDestination { .. } => "move_duplicate_destination",
374            Self::MoveBadSource { .. } => "move_bad_source",
375            Self::MoveMissingIndexEntry { .. } => "move_missing_index_entry",
376            Self::WouldOverwrite { .. } => "would_overwrite",
377            Self::DirtyWorktree { .. } => "dirty_worktree",
378            Self::CheckoutRollbackIncomplete { .. } => "checkout_rollback_incomplete",
379            Self::UnmergedConflictMarkers { .. } => "unmerged_conflict_markers",
380            Self::Filter(_) => "filter",
381            Self::Submodule(_) => "submodule",
382        }
383    }
384}
385
386fn move_rollback_incomplete_message(
387    source: &ErrorSummary,
388    unreversed: usize,
389    backup_restore: Option<&ErrorSummary>,
390) -> String {
391    let mut message = source.to_string();
392    if unreversed > 0 {
393        message.push_str(&format!(
394            "; incomplete worktree rollback ({unreversed} rename(s) could not be reversed)"
395        ));
396    }
397    if let Some(err) = backup_restore {
398        message.push_str(&format!(
399            "; restoring forced-destination backups failed: {err}"
400        ));
401    }
402    message
403}