Skip to main content

grit_lib/error/
mod.rs

1//! Shared error types for grit-lib.
2//!
3//! Every fallible operation returns [`enum@Error`]. It has one variant per functional area
4//! (repository, objects, index, refs, revisions, config, work tree, diff, commit, merge,
5//! history, stash, branches, tags, notes, remotes, hooks) plus the cross-cutting
6//! [`Error::Io`], [`Error::LockHeld`] and [`Error::Cancelled`]. Each area enum lists that
7//! area's failures with structured fields, so callers match on the area and then on the
8//! specific failure. The binary wraps these with `anyhow` for human-readable top-level
9//! reporting.
10//!
11//! Library guide: [typed errors](https://grit-scm.com/docs/library/errors) and [embedding](https://grit-scm.com/docs/library/embedding)
12//!
13//! ```rust
14//! use grit_lib::error::{Error, RefError};
15//!
16//! fn describe(err: &Error) -> &'static str {
17//!     match err {
18//!         Error::Ref(RefError::UnbornHead) => "no commits yet",
19//!         Error::Cancelled => "cancelled",
20//!         other => other.area(),
21//!     }
22//! }
23//! assert_eq!(describe(&Error::Ref(RefError::UnbornHead)), "no commits yet");
24//! ```
25
26use std::path::PathBuf;
27
28use thiserror::Error;
29
30mod diff;
31mod notes;
32mod object;
33mod refs;
34mod revision;
35mod summary;
36
37pub use diff::DiffError;
38pub use notes::NotesError;
39pub use object::{ObjectError, PromisorFetchFailure};
40pub use refs::RefError;
41pub use revision::RevisionError;
42pub use summary::ErrorSummary;
43
44pub use crate::git_dir::GitDirPathOperation;
45pub use crate::midx_error::MidxError;
46pub use crate::repo::RepositoryError;
47pub use crate::worktree::io_error::WorktreePathOperation;
48
49/// Lock file could not be created because another process holds it (or left a stale lock).
50#[derive(Debug, Clone, PartialEq, Eq, Error)]
51#[error(
52    "lock file {} already exists",
53    crate::git_path::user_display_path(.path.as_path())
54)]
55pub struct LockHeldError {
56    /// Lock file that could not be created.
57    pub path: PathBuf,
58    /// Owner recorded in the lock's pid sidecar (`core.lockfilePid`), when one was written.
59    pub holder: Option<crate::lockfile::LockHolder>,
60}
61
62/// Operation stopped because [`CancelToken`](crate::progress::CancelToken) fired before completion.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct Cancelled;
65
66impl std::fmt::Display for Cancelled {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.write_str("operation cancelled")
69    }
70}
71
72/// Which filesystem area a [`PathIoError`] refers to.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74#[non_exhaustive]
75pub enum PathIoOperation {
76    /// Path under the git directory (objects, refs, index, …).
77    GitDir(GitDirPathOperation),
78    /// Repository-relative worktree path.
79    Worktree(WorktreePathOperation),
80}
81
82/// Structured path I/O failure shared by worktree and git-directory operations.
83#[derive(Debug)]
84pub struct PathIoError {
85    /// What the operation was doing when I/O failed.
86    pub operation: PathIoOperation,
87    /// Path that failed, when known.
88    pub path: Option<PathBuf>,
89    /// Underlying OS error.
90    pub source: std::io::Error,
91}
92
93/// Copy an [`std::io::Error`] without dropping [`raw_os_error`](std::io::Error::raw_os_error).
94fn preserve_io_error(source: &std::io::Error) -> std::io::Error {
95    if let Some(raw) = source.raw_os_error() {
96        std::io::Error::from_raw_os_error(raw)
97    } else {
98        std::io::Error::new(source.kind(), source.to_string())
99    }
100}
101
102impl std::fmt::Display for PathIoError {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.write_str(&self.message())
105    }
106}
107
108impl std::error::Error for PathIoError {
109    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
110        Some(&self.source)
111    }
112}
113
114impl PathIoError {
115    /// Build a worktree-path failure (path is the index- or worktree-relative display path).
116    #[must_use]
117    pub fn worktree(
118        path: impl Into<String>,
119        operation: WorktreePathOperation,
120        source: std::io::Error,
121    ) -> Self {
122        Self {
123            operation: PathIoOperation::Worktree(operation),
124            path: Some(PathBuf::from(path.into())),
125            source,
126        }
127    }
128
129    /// Build a git-directory path failure (`path` is already a display path such as `.git/objects`).
130    #[must_use]
131    pub fn git_dir(
132        path: impl Into<String>,
133        operation: GitDirPathOperation,
134        source: std::io::Error,
135    ) -> Self {
136        Self {
137            operation: PathIoOperation::GitDir(operation),
138            path: Some(PathBuf::from(path.into())),
139            source,
140        }
141    }
142
143    /// Human-readable summary (the display text of the worktree or git-dir path I/O failure).
144    #[must_use]
145    pub fn message(&self) -> String {
146        let path = self
147            .path
148            .as_ref()
149            .map(|p| p.to_string_lossy().into_owned())
150            .unwrap_or_default();
151        match self.operation {
152            PathIoOperation::Worktree(op) => {
153                crate::worktree::io_error::format_worktree_path_io_message(&path, op, &self.source)
154            }
155            PathIoOperation::GitDir(op) => {
156                crate::git_dir::io_error::format_git_dir_io_message(&path, op, &self.source)
157            }
158        }
159    }
160}
161
162/// Why a Git config numeric value was rejected (`git config int` strict parsing).
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum BadNumericSource {
165    /// Suffix unit letter is invalid or missing where required.
166    InvalidUnit,
167    /// Parsed value or scaled product does not fit.
168    OutOfRange,
169}
170
171impl BadNumericSource {
172    fn detail(self) -> &'static str {
173        match self {
174            Self::InvalidUnit => "invalid unit",
175            Self::OutOfRange => "out of range",
176        }
177    }
178}
179
180impl std::fmt::Display for BadNumericSource {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        f.write_str(self.detail())
183    }
184}
185
186/// Why a tree transition would overwrite existing worktree content.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub enum OverwriteReason {
189    /// Staged or unstaged edits on paths that differ between trees.
190    LocalChanges,
191    /// Untracked paths that a checkout would replace.
192    Untracked,
193}
194
195impl std::fmt::Display for OverwriteReason {
196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197        match self {
198            Self::LocalChanges => f.write_str("local_changes"),
199            Self::Untracked => f.write_str("untracked"),
200        }
201    }
202}
203
204/// Why a remote could not be read or written ([`RemoteError::Unreadable`](crate::remote::RemoteError::Unreadable)).
205///
206/// Every reason is a failure to talk to the remote at all, as opposed to the remote refusing
207/// an update. [`Self::Transport`] is the one usually worth retrying on a flaky network.
208#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum RemoteUnreadableReason {
211    /// A local path or `file://` URL does not name a Git directory (valid `HEAD`, plus
212    /// `objects/` and `refs/` in the common directory).
213    RepositoryNotFound,
214    /// The connection failed or broke: name resolution, refused or reset connection, TLS, or
215    /// timeouts.
216    Transport {
217        /// Transport-level description of the failure, with URL credentials redacted.
218        detail: String,
219    },
220    /// A smart-HTTP server answered with an error status other than an authentication
221    /// challenge (those are [`RemoteError::Auth`](crate::remote::RemoteError::Auth)).
222    HttpStatus {
223        /// HTTP status code (`>= 400`).
224        status: u16,
225    },
226    /// An HTTP response looked successful but was not a Git smart-HTTP ref advertisement
227    /// (for example `200 text/html` from a parked or mistyped host).
228    NotGitServer {
229        /// HTTP status code (often `200`).
230        status: u16,
231        /// Response `Content-Type` when present (media type only, without parameters).
232        content_type: Option<String>,
233    },
234    /// The transport ran, but the remote never completed the Git protocol handshake (for
235    /// example `ssh` exited, or a `git://` peer closed, before any ref advertisement).
236    NoHandshake,
237    /// The remote ended a fetch response before sending the pack it was asked for (the
238    /// stream closed before the `packfile` section).
239    ResponseTruncated,
240}
241
242impl RemoteUnreadableReason {
243    /// Stable snake-case name for machine-readable output (`repository_not_found`,
244    /// `transport`, `http_status`, `not_git_server`, `no_handshake`, `response_truncated`).
245    #[must_use]
246    pub fn slug(&self) -> &'static str {
247        match self {
248            Self::RepositoryNotFound => "repository_not_found",
249            Self::Transport { .. } => "transport",
250            Self::HttpStatus { .. } => "http_status",
251            Self::NotGitServer { .. } => "not_git_server",
252            Self::NoHandshake => "no_handshake",
253            Self::ResponseTruncated => "response_truncated",
254        }
255    }
256}
257
258pub(crate) fn remote_unreadable_message(
259    url: Option<&str>,
260    reason: &RemoteUnreadableReason,
261) -> String {
262    let target = url.map_or_else(|| "the remote".to_owned(), |u| format!("'{u}'"));
263    match reason {
264        RemoteUnreadableReason::RepositoryNotFound => {
265            format!("could not find repository at {target}")
266        }
267        RemoteUnreadableReason::Transport { detail } => {
268            format!("could not reach {target}: {detail}")
269        }
270        RemoteUnreadableReason::HttpStatus { status } => match url {
271            Some(u) => format!("HTTP {status} from {u}"),
272            None => format!("HTTP {status} from the remote"),
273        },
274        RemoteUnreadableReason::NotGitServer {
275            status,
276            content_type,
277        } => {
278            let got = match content_type
279                .as_deref()
280                .map(|ct| ct.split(';').next().unwrap_or(ct).trim())
281                .filter(|ct| !ct.is_empty())
282            {
283                Some(ct) => format!("{status} {ct}"),
284                None => status.to_string(),
285            };
286            format!("{target} did not answer like a Git server (got {got})")
287        }
288        RemoteUnreadableReason::NoHandshake => {
289            format!("could not read from {target}: no Git protocol response")
290        }
291        RemoteUnreadableReason::ResponseTruncated => {
292            format!("{target} closed the connection before sending the pack")
293        }
294    }
295}
296
297/// Display text for [`RemoteError::Transport`].
298pub(crate) fn remote_transport_message(url: Option<&str>, detail: &str) -> String {
299    match url {
300        Some(u) => format!("could not reach {u}: {detail}"),
301        None => format!("transport failure: {detail}"),
302    }
303}
304
305/// Display text for [`RemoteError::HttpStatus`].
306pub(crate) fn remote_http_status_message(url: Option<&str>, status: u16) -> String {
307    match url {
308        Some(u) => format!("HTTP {status} from {u}"),
309        None => format!("HTTP {status} from the remote"),
310    }
311}
312
313/// Why an HTTP remote refused access ([`RemoteError::Auth`](crate::remote::RemoteError::Auth)).
314#[derive(Debug, Clone, PartialEq, Eq, Error)]
315#[non_exhaustive]
316pub enum AuthFailure {
317    /// The server asked for credentials (`401`) and no credential provider is wired.
318    #[error("no credential provider is configured")]
319    NoCredentialProvider,
320    /// The credential provider could not supply credentials (no helper has them, and
321    /// prompting is not possible).
322    #[error("{detail}")]
323    CredentialsUnavailable {
324        /// The provider's explanation (for example that no helper has credentials and
325        /// prompting is disabled).
326        detail: String,
327        /// The `credential.helper` programs the provider asked, when it reported them
328        /// (see [`RemoteError::CredentialsUnavailable`](crate::remote::RemoteError::CredentialsUnavailable)); empty when none is configured or
329        /// the provider is not helper-based.
330        helpers: Vec<String>,
331    },
332    /// The provider answered without a usable username and password.
333    #[error("the credential helper returned no usable username and password")]
334    UnusableCredentials,
335    /// The URL could not be split into the credential fields helpers expect.
336    #[error("the URL cannot be described to a credential helper")]
337    UrlNotDescribable,
338    /// The server only offers authentication schemes grit does not speak (no `Basic`).
339    #[error("unsupported authentication scheme: {}", schemes.join(", "))]
340    UnsupportedScheme {
341        /// The `WWW-Authenticate` challenges the server sent.
342        schemes: Vec<String>,
343    },
344    /// Credentials were sent and the server rejected them (`401` again).
345    #[error("the server rejected the credentials")]
346    Rejected,
347}
348
349impl AuthFailure {
350    /// Whether credentials were sent and refused, as opposed to never being available.
351    #[must_use]
352    pub fn is_rejected(&self) -> bool {
353        matches!(self, Self::Rejected)
354    }
355
356    /// The failure an HTTP client reports when a credential provider's
357    /// [`fill`](crate::credentials::CredentialProvider::fill) fails with `err`.
358    ///
359    /// Always [`AuthFailure::CredentialsUnavailable`]: `detail` is `err`'s message,
360    /// and `helpers` is the list [`RemoteError::CredentialsUnavailable`](crate::remote::RemoteError::CredentialsUnavailable) carries (empty
361    /// for any other error). Custom [`HttpClient`](crate::transport::http::HttpClient)
362    /// implementations use it to report fill failures the way the built-in client does.
363    #[must_use]
364    pub fn from_fill_error(err: Error) -> Self {
365        let helpers = match &err {
366            Error::Remote(crate::remote::RemoteError::CredentialsUnavailable { helpers }) => {
367                helpers.clone()
368            }
369            _ => Vec::new(),
370        };
371        Self::CredentialsUnavailable {
372            detail: err.to_string(),
373            helpers,
374        }
375    }
376}
377
378/// The command a dirty worktree blocked ([`WorktreeError::DirtyWorktree`](crate::worktree::WorktreeError::DirtyWorktree)).
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub enum WorktreeOperation {
382    /// Switching branches or checking out a commit.
383    Switch,
384    /// Picking (cherry-picking) or reverting commits.
385    Pick,
386    /// Merging.
387    Merge,
388    /// Rebasing with `--exec`.
389    RebaseExec,
390    /// Starting a rebase that stops on conflicts (the stop rewrites the index and worktree).
391    Rebase,
392}
393
394impl std::fmt::Display for WorktreeOperation {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        f.write_str(match self {
397            Self::Switch => "switching",
398            Self::Pick => "picking",
399            Self::Merge => "merging",
400            Self::RebaseExec => "rebasing with --exec",
401            Self::Rebase => "rebasing",
402        })
403    }
404}
405
406/// Configuration parse and validation failures.
407#[derive(Debug, Error, Clone, PartialEq)]
408#[non_exhaustive]
409pub enum ConfigError {
410    /// A line in a config file could not be parsed.
411    #[error("bad config line {line} in {location}")]
412    BadConfigLine {
413        /// Config source label or path where the error was detected.
414        location: String,
415        /// One-based line number within that source.
416        line: usize,
417    },
418
419    /// Same as [`Self::BadConfigLine`] with an explicit file path (Git file diagnostics).
420    #[error("bad config line {line} in file '{file}'")]
421    BadConfigLineInFile {
422        /// Path to the config file involved in the error.
423        file: String,
424        /// One-based line number within that file.
425        line: usize,
426    },
427
428    /// A config key requires a value but none was given.
429    #[error("missing value for '{key}'")]
430    MissingValue {
431        /// Config key name that failed validation.
432        key: String,
433    },
434
435    /// `fetch.negotiationalgorithm` and similar keys with missing values.
436    #[error("bad config variable '{key}' in file '{file}' at line {line}")]
437    BadConfigVariable {
438        /// Config key name that failed validation.
439        key: String,
440        /// Path to the config file involved in the error.
441        file: String,
442        /// One-based line number within the config source.
443        line: usize,
444    },
445
446    /// `unset` or a scoped read/write was requested for a key that is not set in that file.
447    #[error("key '{key}' is not set")]
448    KeyNotSet {
449        /// Config key that was not present.
450        key: String,
451    },
452
453    /// Integer config value could not be parsed or is out of range.
454    #[error("bad numeric config value '{value}' for '{key}': {reason}")]
455    BadNumericValue {
456        /// Config key name that failed validation.
457        key: String,
458        /// Raw config value that could not be parsed.
459        value: String,
460        /// Why the value or operation was rejected.
461        reason: BadNumericSource,
462    },
463
464    /// Same as [`Self::BadNumericValue`] with file context.
465    #[error("bad numeric config value '{value}' for '{key}' in file {file}: {reason}")]
466    BadNumericValueInFile {
467        /// Config key name that failed validation.
468        key: String,
469        /// Raw config value that could not be parsed.
470        value: String,
471        /// Path to the config file involved in the error.
472        file: String,
473        /// Why the value or operation was rejected.
474        reason: BadNumericSource,
475    },
476
477    /// `diff.context` (or similar) failed variable validation.
478    #[error("bad config variable '{key}' in file '{file}' at line {line}")]
479    BadConfigVariableAtLine {
480        /// Config key name that failed validation.
481        key: String,
482        /// Path to the config file involved in the error.
483        file: String,
484        /// One-based line number within the config source.
485        line: usize,
486    },
487
488    /// Command-line config could not supply a parseable value for a key.
489    #[error("unable to parse '{key}' from command-line config")]
490    UnableToParseFromCommandLine {
491        /// Config key name that failed validation.
492        key: String,
493    },
494
495    /// A `remote.<name>.url` is set in a file reached through a conditional include while
496    /// `includeIf.hasconfig:remote.*.url` conditions are evaluated (such URLs could change
497    /// which conditions hold).
498    #[error(
499        "remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"
500    )]
501    RemoteUrlInHasconfigInclude,
502
503    /// `[include]` / `[includeIf]` nesting exceeded the Git-compatible depth limit.
504    #[error("exceeded maximum include depth (depth {depth} exceeds limit {limit})")]
505    IncludeDepthExceeded {
506        /// Current include nesting depth when the limit was hit.
507        depth: usize,
508        /// Maximum allowed include nesting depth.
509        limit: usize,
510    },
511
512    /// A config key is not `section[.subsection].variable` with a valid section and
513    /// variable name.
514    #[error("{}", invalid_key_message(key, *reason))]
515    InvalidKey {
516        /// Key as the caller spelled it.
517        key: String,
518        /// Which part of the key is malformed.
519        reason: InvalidKeyReason,
520    },
521
522    /// A section name passed to a section-level edit is not a valid section name.
523    #[error("invalid section name: {section}")]
524    InvalidSectionName {
525        /// Section name as the caller spelled it.
526        section: String,
527    },
528
529    /// A value pattern (`regex` or `!regex`) is not a valid regular expression.
530    #[error("invalid value-pattern regex '{pattern}': {reason}")]
531    InvalidValuePattern {
532        /// Pattern as given, including any leading `!`.
533        pattern: String,
534        /// Why the regular expression engine rejected it.
535        reason: String,
536    },
537
538    /// A config key regexp (for example `git config --get-regexp`) is not valid.
539    #[error("invalid key pattern '{pattern}': {source}")]
540    InvalidPattern {
541        /// Pattern as given.
542        pattern: String,
543        /// Why the regular expression engine rejected it.
544        #[source]
545        source: regex::Error,
546    },
547
548    /// Parsed config text declares an unsupported `core.repositoryformatversion`.
549    #[error("unknown repository format version: {version}")]
550    UnsupportedRepositoryFormatVersion {
551        /// Parsed format version.
552        version: u32,
553    },
554
555    /// A repository-local config cache mutex was poisoned.
556    #[error("config cache lock poisoned")]
557    ConfigCacheLockPoisoned,
558
559    /// Repository config session mutex was poisoned.
560    #[error("config session lock poisoned")]
561    ConfigSessionLockPoisoned,
562
563    /// Config session state was missing after refresh.
564    #[error("config session missing after refresh")]
565    ConfigSessionMissingAfterRefresh,
566
567    /// A list prefix is empty or is not `section.` / `section.subsection.`.
568    #[error("invalid list prefix '{prefix}'")]
569    InvalidListPrefix {
570        /// Prefix as the caller spelled it.
571        prefix: String,
572    },
573
574    /// A value is not one of the words the key accepts (for example `protocol.version` or
575    /// `gpg.format`).
576    #[error("unknown value '{value}' for '{key}'")]
577    UnknownValue {
578        /// Config key whose value was rejected.
579        key: String,
580        /// Raw config value.
581        value: String,
582    },
583
584    /// A thread-count key (for example `pack.threads`) holds a negative number.
585    #[error("invalid number of threads ({value}) for '{key}'")]
586    InvalidThreadCount {
587        /// Config key whose value was rejected.
588        key: String,
589        /// The negative value.
590        value: i64,
591    },
592
593    /// `GIT_CONFIG_COUNT` is not a non-negative integer no larger than `i32::MAX`.
594    #[error("bogus count in GIT_CONFIG_COUNT: '{value}'")]
595    InvalidEnvironmentCount {
596        /// Raw `GIT_CONFIG_COUNT` value.
597        value: String,
598    },
599
600    /// `GIT_CONFIG_COUNT` names more entries than there are `GIT_CONFIG_KEY_<n>` variables.
601    #[error("missing config key GIT_CONFIG_KEY_{index}")]
602    MissingEnvironmentKey {
603        /// Zero-based index of the first missing `GIT_CONFIG_KEY_<n>`.
604        index: usize,
605    },
606
607    /// `GIT_CONFIG_PARAMETERS` is not a whitespace-separated list of single-quoted entries.
608    #[error("bogus format in GIT_CONFIG_PARAMETERS")]
609    MalformedConfigParameters,
610
611    /// A relative `include.path` / `includeIf.<cond>.path` appeared in config that did not
612    /// come from a file on disk, so there is no directory to resolve it against.
613    #[error("relative config includes must come from files")]
614    RelativeIncludeOutsideFile,
615
616    /// The config location (`--local` or `--worktree`) needs a repository, but none was given.
617    #[error("not in a git repository")]
618    RepositoryRequired,
619
620    /// No home directory or `GIT_CONFIG_GLOBAL` is available to place the global config file.
621    #[error("could not determine global config path")]
622    NoGlobalConfigPath,
623
624    /// A config value that must be a date (an approxidate such as `2.weeks.ago`) is
625    /// not one.
626    #[error("'{value}' is not a date for '{key}'")]
627    InvalidDate {
628        /// Config key name that failed validation.
629        key: String,
630        /// Raw config value that could not be parsed.
631        value: String,
632    },
633
634    /// The config file could not be written because a `.lock` file is already present.
635    #[error("could not lock config file {path}: File exists")]
636    ConfigFileLocked {
637        /// Path to the config file that could not be locked.
638        path: String,
639    },
640
641    /// A single-value operation was requested but the key has multiple values.
642    #[error("cannot overwrite multiple values with a single value for '{key}'")]
643    MultipleValues {
644        /// Config key name that failed validation.
645        key: String,
646    },
647
648    /// Per-worktree config was requested but `extensions.worktreeConfig` is off.
649    #[error(
650        "worktree config is only allowed when extensions.worktreeConfig is enabled in the common config"
651    )]
652    WorktreeConfigNotEnabled,
653
654    /// `remove-section` or `rename-section` did not find the named section.
655    #[error("section '{section}' not found")]
656    SectionNotFound {
657        /// Section header name (e.g. `remote.origin`).
658        section: String,
659    },
660
661    /// Inline `--comment` text must not span lines.
662    #[error("no multi-line comment allowed")]
663    MultilineCommentNotAllowed,
664
665    /// `status.showUntrackedFiles` must be `no`, `normal`, `all`, or a Git boolean synonym.
666    #[error(
667        "invalid value '{value}' for 'status.showUntrackedFiles' (expected no, normal, all, boolean words, or integer 0 vs nonzero)"
668    )]
669    InvalidUntrackedFilesMode {
670        /// Raw config value that could not be parsed.
671        value: String,
672    },
673
674    /// `merge.directoryRenames` must be `conflict` or a Git boolean.
675    #[error(
676        "invalid value '{value}' for 'merge.directoryRenames' (expected true, false or conflict)"
677    )]
678    InvalidDirectoryRenames {
679        /// Raw config value that could not be parsed.
680        value: String,
681    },
682
683    /// The value of `key` is not valid for the type the key requires (a boolean, an integer
684    /// or a color).
685    #[error("{source} for '{key}'")]
686    InvalidValue {
687        /// Config key whose value was rejected, as the caller spelled it.
688        key: String,
689        /// Why the value was rejected.
690        #[source]
691        source: ConfigValueError,
692    },
693}
694
695/// Why a raw config value could not be read as a boolean, integer or color.
696///
697/// Returned by [`crate::config::parse_bool`], [`crate::config::parse_i64`] and
698/// [`crate::config::parse_color`], which see only the value. Readers that also know the key
699/// ([`crate::config::ConfigSet::get_bool`], [`crate::config::ConfigSet::get_i64`]) wrap it in
700/// [`ConfigError::InvalidValue`].
701#[derive(Debug, Error, Clone, PartialEq, Eq)]
702#[non_exhaustive]
703pub enum ConfigValueError {
704    /// Not one of the boolean words (`true`/`yes`/`on`, `false`/`no`/`off`) or an integer.
705    #[error("bad boolean config value '{value}'")]
706    InvalidBool {
707        /// Raw config value that could not be parsed.
708        value: String,
709    },
710
711    /// An integer was required but the value is empty or only whitespace.
712    #[error("empty integer value")]
713    EmptyInteger,
714
715    /// Not a decimal integer with an optional `k`/`m`/`g` suffix.
716    #[error("invalid integer: '{value}'")]
717    InvalidInteger {
718        /// Raw config value (trimmed) that could not be parsed.
719        value: String,
720    },
721
722    /// The integer does not fit in an `i64` once its `k`/`m`/`g` suffix is applied.
723    #[error("integer overflow: '{value}'")]
724    IntegerOverflow {
725        /// Raw config value (trimmed) that overflowed.
726        value: String,
727    },
728
729    /// Not a color specification (color names, numbers or `#rrggbb`, plus attributes).
730    #[error("bad color value '{value}'")]
731    InvalidColor {
732        /// Raw config value (trimmed) that could not be parsed.
733        value: String,
734    },
735}
736
737impl ConfigValueError {
738    /// Attach the config `key` whose value was rejected.
739    ///
740    /// # Parameters
741    ///
742    /// - `key`: the config key as the caller spelled it (for example `core.bare`).
743    ///
744    /// # Returns
745    ///
746    /// [`ConfigError::InvalidValue`] carrying `key` and this error as its source.
747    #[must_use]
748    pub fn for_key(self, key: impl Into<String>) -> ConfigError {
749        ConfigError::InvalidValue {
750            key: key.into(),
751            source: self,
752        }
753    }
754}
755
756/// Which part of a config key [`ConfigError::InvalidKey`] rejected.
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758#[non_exhaustive]
759pub enum InvalidKeyReason {
760    /// The key contains a newline or carriage return.
761    LineBreak,
762    /// The key has no `.`, so there is no section.
763    MissingSection,
764    /// The key ends with `.`, so there is no variable name.
765    MissingVariable,
766    /// The section is empty or has characters other than alphanumerics (Unicode
767    /// [`char::is_alphanumeric`]) and `-`.
768    InvalidSection,
769    /// The variable name does not start with an ASCII letter, or has characters other than
770    /// alphanumerics (Unicode [`char::is_alphanumeric`]) and `-`.
771    InvalidVariable,
772}
773
774fn invalid_key_message(key: &str, reason: InvalidKeyReason) -> String {
775    match reason {
776        InvalidKeyReason::LineBreak => format!(
777            "invalid key: '{}'",
778            key.replace('\n', "\\n").replace('\r', "\\r")
779        ),
780        InvalidKeyReason::MissingSection => format!("key does not contain a section: '{key}'"),
781        InvalidKeyReason::MissingVariable => {
782            format!("key does not contain variable name: '{key}'")
783        }
784        InvalidKeyReason::InvalidSection => format!("invalid key (bad section): '{key}'"),
785        InvalidKeyReason::InvalidVariable => format!("invalid key (bad variable name): '{key}'"),
786    }
787}
788
789impl From<crate::config::GitConfigIntStrictError> for BadNumericSource {
790    fn from(value: crate::config::GitConfigIntStrictError) -> Self {
791        match value {
792            crate::config::GitConfigIntStrictError::InvalidUnit => Self::InvalidUnit,
793            crate::config::GitConfigIntStrictError::OutOfRange => Self::OutOfRange,
794        }
795    }
796}
797
798/// Submodule layout and state failures: where a submodule's git directory lives and whether
799/// its checkout can be inspected.
800#[derive(Debug, Error, Clone, PartialEq, Eq)]
801#[non_exhaustive]
802pub enum SubmoduleError {
803    /// The submodule path is empty.
804    #[error("submodule path is empty")]
805    EmptyPath,
806
807    /// A component of the submodule path is a symbolic link, so the path could escape the
808    /// work tree.
809    #[error("submodule path '{path}' passes through symbolic link '{component}'")]
810    SymlinkInPath {
811        /// Submodule path relative to the work tree.
812        path: String,
813        /// The component that is a symbolic link.
814        component: String,
815    },
816
817    /// A legacy submodule git dir (`modules/<name>`) does not end with `/<name>`.
818    #[error("git dir {} of submodule '{name}' does not end with its name", .git_dir.display())]
819    GitDirNameMismatch {
820        /// Submodule name.
821        name: String,
822        /// Git directory that was checked.
823        git_dir: std::path::PathBuf,
824    },
825
826    /// A submodule git dir lies inside another submodule's git dir.
827    #[error("git dir of submodule '{name}' lies inside another submodule's git dir")]
828    GitDirNested {
829        /// Submodule name.
830        name: String,
831    },
832
833    /// An encoded submodule git dir has no `modules/` path segment.
834    #[error("submodule git dir {} has no modules/ segment", .git_dir.display())]
835    GitDirOutsideModules {
836        /// Git directory that was checked.
837        git_dir: std::path::PathBuf,
838    },
839
840    /// The segment after `modules/` in an encoded submodule git dir contains `/`.
841    #[error("encoded submodule git dir {} has '/' after modules/", .git_dir.display())]
842    GitDirSegmentHasSlash {
843        /// Git directory that was checked.
844        git_dir: std::path::PathBuf,
845    },
846
847    /// Another submodule already uses this git dir.
848    #[error("git dir {} of submodule '{name}' is already used by another submodule", .git_dir.display())]
849    GitDirInUse {
850        /// Submodule name.
851        name: String,
852        /// Git directory that was checked.
853        git_dir: std::path::PathBuf,
854    },
855
856    /// This git dir differs from another submodule's only by case, on a case-insensitive
857    /// file system.
858    #[error("git dir {} of submodule '{name}' differs only in case from another submodule's", .git_dir.display())]
859    GitDirCaseConflict {
860        /// Submodule name.
861        name: String,
862        /// Git directory that was checked.
863        git_dir: std::path::PathBuf,
864    },
865
866    /// Every candidate git dir for a new submodule was invalid or already taken.
867    #[error("could not choose a git dir for submodule '{name}'")]
868    GitDirUnavailable {
869        /// Submodule name.
870        name: String,
871    },
872
873    /// `submodulePathConfig` is enabled but `submodule.<name>.gitdir` is not set.
874    #[error("submodule.{name}.gitdir is not set (submodulePathConfig is enabled)")]
875    GitDirNotConfigured {
876        /// Submodule name.
877        name: String,
878    },
879
880    /// The submodule has an embedded git dir but its `HEAD` could not be read.
881    #[error("could not read HEAD of submodule '{path}'")]
882    HeadUnreadable {
883        /// Submodule path relative to the superproject work tree.
884        path: String,
885    },
886
887    /// The submodule has no checkout (no embedded git directory) to update.
888    #[error("submodule at '{path}' is not checked out")]
889    NotCheckedOut {
890        /// Submodule work tree path.
891        path: String,
892    },
893
894    /// The submodule's `HEAD` names an object that is missing or is not a commit.
895    #[error("HEAD of submodule '{path}' does not point to a readable commit")]
896    HeadCommitMissing {
897        /// Submodule path relative to the superproject work tree.
898        path: String,
899    },
900}
901
902impl ConfigError {
903    /// Git stderr body for this error (without a `fatal:` prefix).
904    #[must_use]
905    pub fn message_body(&self) -> String {
906        self.to_string()
907    }
908}
909
910/// Reference lock failures while creating or updating a ref.
911#[derive(Debug, Error, Clone, PartialEq, Eq)]
912#[non_exhaustive]
913pub enum RefLockError {
914    /// A non-empty directory occupies the path where the ref file must be created.
915    #[error(
916        "cannot lock ref '{refname}': there is a non-empty directory '{path}' blocking reference '{refname}'"
917    )]
918    DirectoryInTheWay {
919        /// Full ref name (for example `refs/heads/main`).
920        refname: String,
921        /// Directory path blocking creation of the ref file.
922        path: String,
923    },
924
925    /// Another process holds the `packed-refs.lock` file (or it already exists).
926    #[error("Unable to create '{lock_path}': File exists.")]
927    PackedRefsLockHeld {
928        /// Path to the lock file that could not be created.
929        lock_path: String,
930    },
931}
932
933/// Clean/smudge filter and EOL conversion failures.
934#[derive(Debug, Error, Clone, PartialEq, Eq)]
935#[non_exhaustive]
936pub enum FilterError {
937    /// External clean or smudge filter command failed.
938    #[error("{path}: {phase} filter '{driver}' failed")]
939    ExternalFilterFailed {
940        /// Filter driver name from `.gitattributes`.
941        driver: String,
942        /// Repository-relative or filesystem path related to the failure.
943        path: String,
944        /// Whether the clean or smudge filter hook failed.
945        phase: FilterPhase,
946    },
947
948    /// A required clean or smudge filter could not be started (for example, no shell to run
949    /// it), so the content was neither filtered nor stored unfiltered.
950    #[error("{path}: cannot start {phase} filter '{driver}' ({program}): {detail}")]
951    ExternalFilterSpawnFailed {
952        /// Filter driver name from `.gitattributes`.
953        driver: String,
954        /// Repository-relative path being filtered.
955        path: String,
956        /// Whether the clean or smudge filter was being started.
957        phase: FilterPhase,
958        /// Program grit tried to spawn (`sh` for shell-command filters).
959        program: String,
960        /// OS error kind from the failed spawn.
961        kind: std::io::ErrorKind,
962        /// OS error message from the failed spawn.
963        detail: String,
964    },
965
966    /// Filter output did not round-trip (clean/smudge mismatch).
967    #[error("{path}: {detail}")]
968    NotFilteredProperly {
969        /// Repository-relative or filesystem path related to the failure.
970        path: String,
971        /// Why clean/smudge output did not round-trip.
972        detail: String,
973    },
974
975    /// Invalid `working-tree-encoding` attribute value.
976    #[error("true/false are no valid working-tree-encodings")]
977    InvalidWorkingTreeEncoding,
978
979    /// Line-ending conversion would modify the worktree against user settings.
980    #[error("{detail}")]
981    LineEndingWouldChange {
982        /// Additional human-readable detail for the failure.
983        detail: String,
984    },
985
986    /// A long-running filter process delayed a checkout, which this operation cannot wait for.
987    #[error("{path}: filter delayed the checkout, which this operation does not support")]
988    DelayedCheckoutUnsupported {
989        /// Repository-relative path being checked out.
990        path: String,
991    },
992
993    /// Shell filter subprocess exited non-zero.
994    #[error("filter command exited with status {status}")]
995    Failed {
996        /// Subprocess exit status from the filter command.
997        status: i32,
998    },
999}
1000
1001/// Which filter hook failed.
1002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1003pub enum FilterPhase {
1004    /// Index → worktree (smudge).
1005    Smudge,
1006    /// Worktree → index (clean).
1007    Clean,
1008}
1009
1010impl std::fmt::Display for FilterPhase {
1011    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1012        match self {
1013            Self::Smudge => f.write_str("smudge"),
1014            Self::Clean => f.write_str("clean"),
1015        }
1016    }
1017}
1018
1019/// Sparse-checkout cone pattern parse warnings (non-fatal).
1020#[derive(Debug, Clone, PartialEq, Eq)]
1021pub enum SparseCheckoutWarning {
1022    /// A cone pattern line was not recognized.
1023    UnrecognizedPattern {
1024        /// Raw pattern text from the sparse-checkout file.
1025        pattern: String,
1026    },
1027    /// A negative cone pattern line was not recognized.
1028    UnrecognizedNegativePattern {
1029        /// Raw negative pattern text from the sparse-checkout file.
1030        pattern: String,
1031    },
1032    /// The same cone pattern appears more than once in the sparse-checkout file.
1033    RepeatedPattern {
1034        /// Duplicated pattern text.
1035        pattern: String,
1036    },
1037    /// Cone pattern matching was disabled due to invalid sparse-checkout contents.
1038    DisablingConePatternMatching,
1039}
1040
1041impl SparseCheckoutWarning {
1042    /// Human-readable body without a `warning:` prefix.
1043    #[must_use]
1044    pub fn body(&self) -> String {
1045        match self {
1046            Self::UnrecognizedPattern { pattern } => {
1047                format!("unrecognized pattern: '{pattern}'")
1048            }
1049            Self::UnrecognizedNegativePattern { pattern } => {
1050                format!("unrecognized negative pattern: '{pattern}'")
1051            }
1052            Self::RepeatedPattern { pattern } => format!(
1053                "your sparse-checkout file may have issues: pattern '{pattern}' is repeated"
1054            ),
1055            Self::DisablingConePatternMatching => "disabling cone pattern matching".to_owned(),
1056        }
1057    }
1058
1059    /// Git-style `warning: …` line.
1060    #[must_use]
1061    pub fn format_line(&self) -> String {
1062        crate::diagnostics::warning_line(&self.body())
1063    }
1064}
1065
1066/// Unified diff / patch application errors.
1067#[derive(Debug, Error, Clone, PartialEq, Eq)]
1068#[non_exhaustive]
1069pub enum ApplyError {
1070    /// Patch bytes are malformed at a known input location.
1071    #[error("corrupt patch at {input}:{line}")]
1072    CorruptPatch {
1073        /// Patch input label (file name or `stdin`).
1074        input: String,
1075        /// One-based line number within the patch input.
1076        line: usize,
1077    },
1078
1079    /// Preimage context could not be located in the blob at any search offset.
1080    #[error(
1081        "patch failed: context mismatch at hunk {hunk_index} (expected near line {expected_line})"
1082    )]
1083    ContextMismatch {
1084        /// Zero-based index of the hunk in the input slice.
1085        hunk_index: usize,
1086        /// One-based line number from the hunk header (`old_start`).
1087        expected_line: usize,
1088    },
1089
1090    /// A later hunk would modify lines already changed by an earlier hunk.
1091    #[error("patch failed: overlapping hunks at hunk {hunk_index}")]
1092    HunksOverlap {
1093        /// Zero-based index of the hunk that overlaps prior applied changes.
1094        hunk_index: usize,
1095    },
1096
1097    /// The patch removes more lines than exist in the blob (without a valid EOF match).
1098    #[error("patch failed: unexpected end of file at hunk {hunk_index}")]
1099    UnexpectedEof {
1100        /// Zero-based index of the offending hunk.
1101        hunk_index: usize,
1102    },
1103
1104    /// A path named by the patch is not valid UTF-8.
1105    #[error("diff path is not valid UTF-8")]
1106    PathNotUtf8,
1107
1108    /// A traditional (non-git) patch header names no file that the strip level leaves.
1109    #[error("unable to find filename in traditional patch")]
1110    MissingFilename,
1111
1112    /// A `diff --git` header path has fewer leading components than the strip level removes.
1113    #[error("malformed {side} path in diff --git header: {path}")]
1114    MalformedHeaderPath {
1115        /// Which side of the header the path is on.
1116        side: PatchSide,
1117        /// The path as written in the header.
1118        path: String,
1119    },
1120
1121    /// A mode header line (`old mode`, `new file mode`, …) carries no mode.
1122    #[error("invalid mode on line {line}: {text}")]
1123    InvalidMode {
1124        /// One-based line number in the patch input.
1125        line: usize,
1126        /// The header line as written.
1127        text: String,
1128    },
1129
1130    /// A `@@ -a,b +c,d @@` hunk header could not be parsed.
1131    #[error("invalid hunk header: {header}")]
1132    InvalidHunkHeader {
1133        /// The header line as written.
1134        header: String,
1135    },
1136
1137    /// A `GIT binary patch` section is malformed or cannot be applied.
1138    #[error(transparent)]
1139    BinaryPatch(#[from] BinaryPatchError),
1140
1141    /// A text hunk could not be matched or applied.
1142    #[error("patch failed: {path}:{line}")]
1143    PatchFailed {
1144        /// File path from the patch.
1145        path: String,
1146        /// One-based line number in the patch input.
1147        line: usize,
1148    },
1149
1150    /// Index or blob apply failed for a path.
1151    #[error("could not apply patch to {path}: {message}")]
1152    Failed {
1153        /// Repository-relative path.
1154        path: String,
1155        /// Failure detail.
1156        message: String,
1157    },
1158
1159    /// `--cached` apply requires a stage-0 index entry at the preimage path.
1160    #[error("'{path}' is not in the index")]
1161    NotInIndex {
1162        /// Missing path.
1163        path: String,
1164    },
1165
1166    /// A binary diff marker without `GIT binary patch` payload cannot be applied.
1167    #[error("binary patch data missing for '{path}'")]
1168    BinaryDataMissing {
1169        /// Path from the patch.
1170        path: String,
1171    },
1172
1173    /// The caller's [`crate::progress::CancelToken`] stopped the apply between files.
1174    #[error("operation cancelled")]
1175    Cancelled,
1176}
1177
1178/// Side of a patch a header path belongs to ([`ApplyError::MalformedHeaderPath`]).
1179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1180#[non_exhaustive]
1181pub enum PatchSide {
1182    /// The preimage (`a/…`, `---`).
1183    Old,
1184    /// The postimage (`b/…`, `+++`).
1185    New,
1186}
1187
1188impl std::fmt::Display for PatchSide {
1189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1190        f.write_str(match self {
1191            Self::Old => "old",
1192            Self::New => "new",
1193        })
1194    }
1195}
1196
1197/// Why a `GIT binary patch` section could not be read or applied ([`ApplyError::BinaryPatch`]).
1198#[derive(Debug, Error, Clone, PartialEq, Eq)]
1199#[non_exhaustive]
1200pub enum BinaryPatchError {
1201    /// A section header is neither `literal <size>` nor `delta <size>`.
1202    #[error("unsupported binary patch section: '{header}'")]
1203    UnsupportedSection {
1204        /// The section header as written.
1205        header: String,
1206    },
1207    /// The size after `literal` / `delta` is not a decimal number.
1208    #[error("invalid binary patch section size: '{size}'")]
1209    InvalidSectionSize {
1210        /// The size text as written.
1211        size: String,
1212    },
1213    /// A payload line is empty where a length marker was expected.
1214    #[error("empty binary patch payload line")]
1215    EmptyLine,
1216    /// A payload line starts with a character that is not a length marker (`A`–`Z`, `a`–`z`).
1217    #[error("invalid binary patch line length marker: '{marker}'")]
1218    InvalidLineLength {
1219        /// The marker character as written.
1220        marker: char,
1221    },
1222    /// A payload line's base85 body is truncated, has bytes outside the alphabet, or does not
1223    /// decode to its declared length.
1224    #[error("invalid binary patch base85")]
1225    InvalidBase85,
1226    /// The zlib payload of a section could not be inflated.
1227    #[error("failed to inflate binary patch payload: {detail}")]
1228    Inflate {
1229        /// The zlib library's description of the failure.
1230        detail: String,
1231    },
1232    /// A literal section inflated to a different size than its header declared.
1233    #[error("binary patch literal size {actual} != declared {declared}")]
1234    SizeMismatch {
1235        /// Bytes after inflating.
1236        actual: usize,
1237        /// Size from the section header.
1238        declared: usize,
1239    },
1240    /// A delta section was applied without the preimage blob it is relative to.
1241    #[error("binary patch delta requires a base blob")]
1242    DeltaWithoutBase,
1243    /// The patch has a forward section but no reverse section.
1244    #[error("binary patch has no reverse section")]
1245    NoReverseSection,
1246}
1247
1248/// `--pathspec-from-file` / `--pathspec-file-nul` parse failure.
1249#[derive(Debug, Error, Clone, PartialEq, Eq)]
1250#[non_exhaustive]
1251pub enum PathspecFromFileParseError {
1252    /// A NUL-separated entry is not valid UTF-8.
1253    #[error("invalid UTF-8 in pathspec-from-file (NUL mode)")]
1254    InvalidUtf8InNulRecord,
1255    /// A NUL-terminated entry used C-style quoting (forbidden in NUL mode).
1256    #[error("pathspec-from-file: line is not NUL terminated: {line}")]
1257    QuotedLineInNulMode {
1258        /// Offending entry text.
1259        line: String,
1260    },
1261    /// A line-mode entry had invalid double-quote wrapping.
1262    #[error("invalid C-style quoting: {line}")]
1263    InvalidCStyleQuoting {
1264        /// Raw line from the file.
1265        line: String,
1266    },
1267    /// Backslash escape at end of a quoted line.
1268    #[error("invalid escape at end of string")]
1269    InvalidEscapeAtEnd,
1270    /// Octal escape shorter than three digits.
1271    #[error("truncated octal escape")]
1272    TruncatedOctalEscape,
1273    /// Octal escape bytes are not valid UTF-8.
1274    #[error("invalid octal bytes")]
1275    InvalidOctalBytes,
1276    /// Octal digits do not form a valid byte value.
1277    #[error("invalid octal escape value")]
1278    InvalidOctalValue,
1279    /// Unknown escape after backslash in a quoted line.
1280    #[error("invalid escape sequence \\{escape}")]
1281    InvalidEscapeSequence {
1282        /// Character after the backslash.
1283        escape: char,
1284    },
1285    /// Quoted line decoded to invalid UTF-8.
1286    #[error("invalid UTF-8 in quoted pathspec")]
1287    InvalidUtf8InQuotedLine,
1288}
1289
1290/// Failure while resolving argv and `--pathspec-from-file` pathspecs against a work tree.
1291#[derive(Debug, Error, Clone, PartialEq, Eq)]
1292#[non_exhaustive]
1293pub enum PathspecResolveError {
1294    /// An argv pathspec was the empty string.
1295    #[error("invalid path ''")]
1296    EmptyPathspec,
1297    /// Resolved path lies outside the repository work tree.
1298    #[error("{elt}: '{path}' is outside repository at '{work_tree}'")]
1299    OutsideRepository {
1300        /// User-facing pathspec token (argv element).
1301        elt: String,
1302        /// Resolved absolute path outside the work tree.
1303        path: String,
1304        /// Canonical work tree root.
1305        work_tree: String,
1306    },
1307    /// `--pathspec-from-file` bytes could not be parsed.
1308    #[error(transparent)]
1309    FromFile(#[from] PathspecFromFileParseError),
1310    /// Command requires a working tree but the repository is bare.
1311    #[error("this operation needs a working tree")]
1312    NeedsWorkTree,
1313    /// Incompatible `GIT_*_PATHSPECS` global flags.
1314    #[error(transparent)]
1315    InvalidGlobals(#[from] crate::pathspec::PathspecGlobalsError),
1316}
1317
1318/// Why a `:(attr:...)` pathspec clause was rejected.
1319#[derive(Debug, Error, Clone, PartialEq, Eq)]
1320#[non_exhaustive]
1321pub enum AttrPathspecError {
1322    /// The clause names no attribute requirement (`:(attr:)`).
1323    #[error("attr requirement list is empty")]
1324    Empty,
1325    /// More than one `attr:` clause appears in one pathspec.
1326    #[error("a pathspec may contain at most one attr clause")]
1327    MultipleAttrClauses,
1328    /// A requirement names an attribute that is not valid (`-a=b`, `bad name`, `bad/name`).
1329    #[error("'{name}' is not a usable attribute name")]
1330    InvalidName {
1331        /// The attribute name as written.
1332        name: String,
1333    },
1334    /// A `\` escape ends the value or precedes whitespace.
1335    #[error("attr value ends with a dangling escape")]
1336    DanglingEscape,
1337    /// A `\` escape precedes something other than `,`.
1338    #[error("attr values may only escape ','")]
1339    UnsupportedEscape,
1340}
1341
1342/// Path outside the repository during pathspec or transport resolution.
1343#[derive(Debug, Error, Clone, PartialEq, Eq)]
1344#[non_exhaustive]
1345pub enum PathOutsideRepoError {
1346    /// A resolved path escapes the repository work tree or git directory.
1347    #[error("'{subpath}' is outside repository at '{repo_root}'")]
1348    OutsideRepository {
1349        /// Repository-relative or filesystem path related to the failure.
1350        path: String,
1351        /// Path component that lies outside the repository root.
1352        subpath: String,
1353        /// Canonical repository root used for the outside-path check.
1354        repo_root: String,
1355    },
1356}
1357
1358/// Why a path could not be opened as a Git repository; carried by [`RepositoryError::NotARepository`].
1359#[derive(Debug, Error)]
1360#[non_exhaustive]
1361pub enum NotARepositoryReason {
1362    /// No usable git directory exists at `path`, or discovery found none at or above it.
1363    #[error("{}", crate::git_path::path_for_error_message(path))]
1364    NoRepositoryAt {
1365        /// Directory, git directory, or `.git` path that was probed.
1366        path: std::path::PathBuf,
1367    },
1368    /// A `.git` entry is a FIFO, socket or device rather than a regular file or directory.
1369    #[error(
1370        "invalid gitfile format: {} is not a regular file",
1371        crate::git_path::path_for_error_message(path)
1372    )]
1373    GitfileNotRegularFile {
1374        /// The offending `.git` entry.
1375        path: std::path::PathBuf,
1376    },
1377    /// A gitfile has no `gitdir: <path>` line.
1378    #[error("invalid gitfile format")]
1379    GitfileMissingGitdir {
1380        /// The gitfile that was parsed.
1381        path: std::path::PathBuf,
1382    },
1383    /// A gitfile exists but could not be read (permissions, invalid UTF-8, ...).
1384    #[error("{error}")]
1385    GitfileUnreadable {
1386        /// The gitfile that could not be read.
1387        path: std::path::PathBuf,
1388        /// The underlying read failure.
1389        error: std::io::Error,
1390    },
1391}
1392
1393pub(crate) fn maintenance_running_message(holder: &crate::maintenance::GcLockHolder) -> String {
1394    match (holder.pid, holder.host.as_deref()) {
1395        (Some(pid), Some(host)) => {
1396            format!("repository maintenance is already running (process {pid} on {host})")
1397        }
1398        (Some(pid), None) => format!("repository maintenance is already running (process {pid})"),
1399        _ => "repository maintenance is already running".to_owned(),
1400    }
1401}
1402
1403pub(crate) fn restore_unmerged_message(paths: &[String]) -> String {
1404    match paths {
1405        [path] => format!("path '{path}' is unmerged"),
1406        _ => format!(
1407            "paths are unmerged: {}",
1408            paths
1409                .iter()
1410                .map(|p| format!("'{p}'"))
1411                .collect::<Vec<_>>()
1412                .join(", ")
1413        ),
1414    }
1415}
1416
1417/// Failure decoding object bytes from loose storage or a pack entry.
1418///
1419/// Used as the `source` of [`ObjectError::CorruptLoose`] and [`ObjectError::CorruptPacked`]
1420/// so object-read layers do not store a recursive [`enum@Error`].
1421#[derive(Debug, Error)]
1422#[non_exhaustive]
1423pub enum ObjectReadFailure {
1424    /// Filesystem read failed while loading object bytes.
1425    #[error("I/O error: {0}")]
1426    Io(#[from] std::io::Error),
1427    /// zlib inflate/deflate failure on object payload bytes.
1428    #[error("zlib error: {detail}")]
1429    Zlib {
1430        /// The zlib library's description of the failure.
1431        detail: String,
1432    },
1433    /// Object header or payload failed structural checks (see [`ObjectError::Corrupt`]).
1434    #[error("corrupt object: {detail}")]
1435    CorruptObject {
1436        /// What is wrong with the object bytes.
1437        detail: String,
1438    },
1439    /// Declared size did not match bytes read from a stream.
1440    #[error("object stream ended after {actual} of {expected} bytes")]
1441    ObjectStreamTruncated {
1442        /// Payload size the reader expected.
1443        expected: u64,
1444        /// Bytes read before EOF.
1445        actual: u64,
1446    },
1447    /// Object type token in a header was not recognized.
1448    #[error("unknown object type '{name}'")]
1449    UnknownObjectType {
1450        /// The type token as read.
1451        name: String,
1452    },
1453    /// Loose object header type field exceeds Git's limit.
1454    #[error("header for {oid} too long, exceeds 32 bytes")]
1455    ObjectHeaderTooLong {
1456        /// Object id (hex) of the loose object with an oversized header.
1457        oid: String,
1458    },
1459    /// Delta chain exceeded the read-side depth limit.
1460    #[error("delta chain too deep (limit {limit})")]
1461    DeltaChainTooDeep {
1462        /// Configured maximum chain depth.
1463        limit: usize,
1464    },
1465    /// Payload failed the same checks used when refusing writes (`git fsck` rules).
1466    #[error("refusing to write invalid {kind} object: {}", .check.report_line())]
1467    InvalidObject {
1468        /// Kind the bytes were parsed as.
1469        kind: crate::objects::ObjectKind,
1470        /// First broken rule.
1471        check: crate::fsck_standalone::FsckError,
1472    },
1473}
1474
1475impl ObjectReadFailure {
1476    /// Maps the [`ObjectError`] decode failures that may appear while reading stored object
1477    /// bytes.
1478    ///
1479    /// Returns `Err(err)` when `err` is not one of those failures (callers must not wrap
1480    /// unrelated failures as object corruption). Used only by
1481    /// [`Error::wrap_loose_read_failure`] and [`Error::wrap_packed_read_failure`].
1482    pub(crate) fn try_from_object_read_error(err: Error) -> std::result::Result<Self, Error> {
1483        match err {
1484            Error::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(Self::Io(e)),
1485            Error::Object(ObjectError::Zlib { detail }) => Ok(Self::Zlib { detail }),
1486            Error::Object(ObjectError::Corrupt { detail }) => Ok(Self::CorruptObject { detail }),
1487            Error::Object(ObjectError::StreamTruncated { expected, actual }) => {
1488                Ok(Self::ObjectStreamTruncated { expected, actual })
1489            }
1490            Error::Object(ObjectError::UnknownType { name }) => {
1491                Ok(Self::UnknownObjectType { name })
1492            }
1493            Error::Object(ObjectError::HeaderTooLong { oid }) => {
1494                Ok(Self::ObjectHeaderTooLong { oid })
1495            }
1496            Error::Object(ObjectError::DeltaChainTooDeep { limit }) => {
1497                Ok(Self::DeltaChainTooDeep { limit })
1498            }
1499            Error::Object(ObjectError::Invalid { kind, check }) => {
1500                Ok(Self::InvalidObject { kind, check })
1501            }
1502            other => Err(other),
1503        }
1504    }
1505}
1506
1507/// The top-level error type for all grit-lib operations.
1508///
1509/// Every variant is one functional area (plus the cross-cutting [`Self::Io`],
1510/// [`Self::LockHeld`] and [`Self::Cancelled`]). Each area enum carries that area's specific
1511/// failures with structured fields; match on the area first, then on its enum.
1512///
1513/// # Examples
1514///
1515/// ```
1516/// use grit_lib::error::{Error, ObjectError};
1517///
1518/// let err = Error::Object(ObjectError::NotFound { name: "1234abcd".into() });
1519/// assert_eq!(err.area(), "object");
1520/// assert_eq!(err.kind_name(), "object_not_found");
1521/// assert!(matches!(err, Error::Object(ObjectError::NotFound { .. })));
1522/// ```
1523#[derive(Debug, Error)]
1524#[non_exhaustive]
1525pub enum Error {
1526    /// Repository discovery, layout, format, and maintenance-lock failures.
1527    #[error(transparent)]
1528    Repository(#[from] RepositoryError),
1529
1530    /// Object database, pack, commit-graph, multi-pack-index, and promisor failures.
1531    #[error(transparent)]
1532    Object(#[from] ObjectError),
1533
1534    /// Index read, write, extension, or write-tree failure.
1535    #[error(transparent)]
1536    Index(crate::index::IndexError),
1537
1538    /// Reference, reflog, ref store, and `HEAD` state failures.
1539    #[error(transparent)]
1540    Ref(#[from] RefError),
1541
1542    /// Revision lookup, parsing, and walk failures.
1543    #[error(transparent)]
1544    Revision(#[from] RevisionError),
1545
1546    /// Configuration parse, validation, and write failures.
1547    #[error(transparent)]
1548    Config(#[from] ConfigError),
1549
1550    /// Work tree, path, pathspec, checkout, filter, submodule, and linked worktree failures.
1551    #[error(transparent)]
1552    Worktree(#[from] crate::worktree::WorktreeError),
1553
1554    /// Patch application, hunk selection, and blame failures.
1555    #[error(transparent)]
1556    Diff(#[from] DiffError),
1557
1558    /// Commit, identity, signing, and patch-scoped commit failures.
1559    #[error(transparent)]
1560    Commit(crate::porcelain::commit_error::CommitError),
1561
1562    /// Merge, cherry-pick, revert, and in-progress operation failures.
1563    #[error(transparent)]
1564    Merge(crate::porcelain::merge_error::MergeError),
1565
1566    /// History rewrite (`grit history`, rebase) failures.
1567    #[error(transparent)]
1568    History(crate::history::HistoryError),
1569
1570    /// Stash push, apply, and stack failures.
1571    #[error(transparent)]
1572    Stash(crate::porcelain::stash_error::StashError),
1573
1574    /// Branch create, delete, lookup, and upstream configuration failures.
1575    #[error(transparent)]
1576    Branch(#[from] crate::porcelain::branch_error::BranchError),
1577
1578    /// Tag create, delete, and verification failures.
1579    #[error(transparent)]
1580    Tag(#[from] crate::porcelain::tag::TagError),
1581
1582    /// Notes ref, notes tree, and notes merge failures.
1583    #[error(transparent)]
1584    Notes(#[from] NotesError),
1585
1586    /// Remote transport, fetch, push, and clone failures.
1587    #[error(transparent)]
1588    Remote(crate::remote::RemoteError),
1589
1590    /// A Git hook subprocess failed or could not be started.
1591    #[error(transparent)]
1592    Hook(crate::hooks::HookError),
1593
1594    /// An I/O error from the underlying filesystem.
1595    #[error("I/O error: {0}")]
1596    Io(#[from] std::io::Error),
1597
1598    /// A lock file (for example `.git/index.lock` or `refs/heads/main.lock`) already exists, so
1599    /// another process is updating the same file or a crashed one left the lock behind.
1600    ///
1601    /// Operations that return this before changing anything leave the repository untouched.
1602    /// The lock file belongs to whoever created it and is never removed. Retry once the other
1603    /// process finishes, or delete the lock path when no process owns it (a `holder` with
1604    /// `running: false` means the lock is stale).
1605    #[error(transparent)]
1606    LockHeld(#[from] LockHeldError),
1607
1608    /// A long-running library operation stopped at a cancellation checkpoint.
1609    ///
1610    /// Use [`Error::is_cancelled`] to test for it, including cancellations recorded inside
1611    /// area errors.
1612    #[error("operation cancelled")]
1613    Cancelled,
1614}
1615
1616impl Error {
1617    /// Stable snake_case name of this error's specific failure (for example
1618    /// `"not_a_repository"`), for scripts and serialized output that must branch on the
1619    /// failure kind.
1620    ///
1621    /// The names are the leaf failure names and change only when a failure is renamed.
1622    /// Match on the error value itself in Rust code.
1623    ///
1624    /// # Examples
1625    ///
1626    /// ```
1627    /// use grit_lib::error::Error;
1628    /// use grit_lib::porcelain::CommitError;
1629    ///
1630    /// assert_eq!(
1631    ///     Error::Commit(CommitError::NothingToCommit).kind_name(),
1632    ///     "nothing_to_commit"
1633    /// );
1634    /// assert_eq!(Error::Cancelled.kind_name(), "cancelled");
1635    /// ```
1636    #[must_use]
1637    pub fn kind_name(&self) -> &'static str {
1638        match self {
1639            Self::Repository(e) => e.kind_name(),
1640            Self::Object(e) => e.kind_name(),
1641            Self::Index(e) => e.kind_name(),
1642            Self::Ref(e) => e.kind_name(),
1643            Self::Revision(e) => e.kind_name(),
1644            Self::Config(..) => "config",
1645            Self::Worktree(e) => e.kind_name(),
1646            Self::Diff(e) => e.kind_name(),
1647            Self::Commit(e) => e.kind_name(),
1648            Self::Merge(e) => e.kind_name(),
1649            Self::History(..) => "history",
1650            Self::Stash(e) => e.kind_name(),
1651            Self::Branch(e) => e.kind_name(),
1652            Self::Tag(e) => e.kind_name(),
1653            Self::Notes(e) => e.kind_name(),
1654            Self::Remote(e) => e.kind_name(),
1655            Self::Hook(..) => "hook",
1656            Self::Io(..) => "io",
1657            Self::LockHeld(..) => "lock_held",
1658            Self::Cancelled => "cancelled",
1659        }
1660    }
1661
1662    /// Functional area of this error: the snake_case name of its umbrella variant
1663    /// (`"repository"`, `"object"`, `"index"`, `"ref"`, …).
1664    ///
1665    /// # Examples
1666    ///
1667    /// ```
1668    /// use grit_lib::error::Error;
1669    ///
1670    /// assert_eq!(Error::Cancelled.area(), "cancelled");
1671    /// ```
1672    #[must_use]
1673    pub fn area(&self) -> &'static str {
1674        match self {
1675            Self::Repository(..) => "repository",
1676            Self::Object(..) => "object",
1677            Self::Index(..) => "index",
1678            Self::Ref(..) => "ref",
1679            Self::Revision(..) => "revision",
1680            Self::Config(..) => "config",
1681            Self::Worktree(..) => "worktree",
1682            Self::Diff(..) => "diff",
1683            Self::Commit(..) => "commit",
1684            Self::Merge(..) => "merge",
1685            Self::History(..) => "history",
1686            Self::Stash(..) => "stash",
1687            Self::Branch(..) => "branch",
1688            Self::Tag(..) => "tag",
1689            Self::Notes(..) => "notes",
1690            Self::Remote(..) => "remote",
1691            Self::Hook(..) => "hook",
1692            Self::Io(..) => "io",
1693            Self::LockHeld(..) => "lock_held",
1694            Self::Cancelled => "cancelled",
1695        }
1696    }
1697
1698    /// Build [`WorktreeError::DirtyWorktree`](crate::worktree::WorktreeError::DirtyWorktree),
1699    /// sorting and deduplicating `paths`.
1700    #[must_use]
1701    pub fn dirty_worktree(operation: WorktreeOperation, mut affected_paths: Vec<String>) -> Self {
1702        affected_paths.sort();
1703        affected_paths.dedup();
1704        Self::Worktree(crate::worktree::WorktreeError::DirtyWorktree {
1705            operation,
1706            paths: affected_paths,
1707        })
1708    }
1709
1710    /// Build [`WorktreeError::WouldOverwrite`](crate::worktree::WorktreeError::WouldOverwrite)
1711    /// for switch and similar tree transitions.
1712    #[must_use]
1713    pub fn would_overwrite(reason: OverwriteReason, mut affected_paths: Vec<String>) -> Self {
1714        affected_paths.sort();
1715        affected_paths.dedup();
1716        let message = match reason {
1717            OverwriteReason::LocalChanges => {
1718                "you have uncommitted changes — commit them before switching".into()
1719            }
1720            OverwriteReason::Untracked => {
1721                let first = affected_paths
1722                    .first()
1723                    .map(String::as_str)
1724                    .unwrap_or("<path>");
1725                format!("untracked file '{first}' would be overwritten — move or remove it first")
1726            }
1727        };
1728        Self::Worktree(crate::worktree::WorktreeError::WouldOverwrite {
1729            reason,
1730            paths: affected_paths,
1731            message,
1732        })
1733    }
1734
1735    /// Build [`crate::remote::RemoteError::Unreadable`] for `url`.
1736    #[must_use]
1737    pub fn remote_unreadable(url: impl Into<String>, reason: RemoteUnreadableReason) -> Self {
1738        Self::Remote(crate::remote::RemoteError::unreadable(url, reason))
1739    }
1740
1741    /// Whether this is an unreadable remote failure (see [`crate::remote::RemoteError::is_remote_unreadable`]).
1742    #[must_use]
1743    pub fn is_remote_unreadable(&self) -> bool {
1744        match self {
1745            Self::Remote(e) => e.is_remote_unreadable(),
1746            _ => false,
1747        }
1748    }
1749
1750    /// When this is [`Error::LockHeld`], returns the structured lock failure.
1751    #[must_use]
1752    pub fn lock_held(&self) -> Option<&LockHeldError> {
1753        match self {
1754            Self::LockHeld(err) => Some(err),
1755            _ => None,
1756        }
1757    }
1758
1759    /// When this is a worktree or git-dir path I/O failure, returns the shared leaf shape.
1760    #[must_use]
1761    pub fn path_io(&self) -> Option<PathIoError> {
1762        let io = match self {
1763            Self::Worktree(crate::worktree::WorktreeError::PathIo(io)) => io,
1764            Self::Repository(RepositoryError::GitDirPathIo(io)) => io,
1765            _ => return None,
1766        };
1767        Some(PathIoError {
1768            operation: io.operation,
1769            path: io.path.clone(),
1770            source: preserve_io_error(&io.source),
1771        })
1772    }
1773
1774    /// Whether this is a work-tree path I/O failure caused by another process holding the
1775    /// file open (a Windows sharing or lock violation, `EBUSY`, or would-block), so retrying
1776    /// after closing that program can succeed.
1777    #[must_use]
1778    pub fn is_worktree_file_in_use(&self) -> bool {
1779        matches!(
1780            self,
1781            Self::Worktree(crate::worktree::WorktreeError::PathIo(io))
1782                if matches!(io.operation, PathIoOperation::Worktree(_))
1783                    && crate::worktree::io_error::is_file_in_use(&io.source)
1784        )
1785    }
1786
1787    /// Whether this is [`RepositoryError::git_dir_path_io`] caused by another process holding a git-dir file
1788    /// open (Windows sharing or access-denied during replace, `EBUSY`, …).
1789    #[must_use]
1790    pub fn is_git_dir_file_in_use(&self) -> bool {
1791        match self {
1792            Self::Repository(RepositoryError::GitDirPathIo(io)) => match io.operation {
1793                PathIoOperation::GitDir(operation) => {
1794                    crate::git_dir::io_error::is_git_dir_transient_contention(operation, &io.source)
1795                }
1796                PathIoOperation::Worktree(_) => false,
1797            },
1798            _ => false,
1799        }
1800    }
1801
1802    /// Whether this is [`Error::Cancelled`] or an area failure recording a cancellation.
1803    #[must_use]
1804    pub fn is_cancelled(&self) -> bool {
1805        match self {
1806            Self::Cancelled => true,
1807            Self::History(e) => e.is_cancelled(),
1808            Self::Worktree(e) => e.is_cancelled(),
1809            Self::Io(err)
1810                if err.to_string() == crate::transport::stateless_http::TRANSPORT_IO_CANCELLED =>
1811            {
1812                true
1813            }
1814            _ => false,
1815        }
1816    }
1817
1818    /// Whether an object read failed because a stored copy is damaged (zlib/header/truncation),
1819    /// so composite stores may consult the next backend.
1820    #[must_use]
1821    pub fn is_damaged_object(&self) -> bool {
1822        match self {
1823            Self::Object(
1824                ObjectError::Zlib { .. }
1825                | ObjectError::Corrupt { .. }
1826                | ObjectError::CorruptLoose { .. }
1827                | ObjectError::CorruptPacked { .. },
1828            ) => true,
1829            Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
1830            _ => false,
1831        }
1832    }
1833
1834    pub(crate) fn is_object_read_wrap_source(&self) -> bool {
1835        match self {
1836            Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
1837            Self::Object(
1838                ObjectError::Zlib { .. }
1839                | ObjectError::Corrupt { .. }
1840                | ObjectError::StreamTruncated { .. }
1841                | ObjectError::UnknownType { .. }
1842                | ObjectError::HeaderTooLong { .. }
1843                | ObjectError::DeltaChainTooDeep { .. }
1844                | ObjectError::Invalid { .. },
1845            ) => true,
1846            _ => false,
1847        }
1848    }
1849
1850    /// Attach loose-object path context to low-level read failures at the ODB boundary.
1851    #[must_use]
1852    pub(crate) fn wrap_loose_read_failure(
1853        oid: crate::objects::ObjectId,
1854        path: std::path::PathBuf,
1855        err: Error,
1856    ) -> Error {
1857        if matches!(err, Self::Object(ObjectError::CorruptLoose { .. })) {
1858            return err;
1859        }
1860        if !err.is_object_read_wrap_source() {
1861            return err;
1862        }
1863        match ObjectReadFailure::try_from_object_read_error(err) {
1864            Ok(source) => Self::Object(ObjectError::CorruptLoose {
1865                oid,
1866                path,
1867                source: Box::new(source),
1868            }),
1869            Err(err) => err,
1870        }
1871    }
1872
1873    /// Attach pack location context to low-level read failures at the ODB boundary.
1874    #[must_use]
1875    pub(crate) fn wrap_packed_read_failure(
1876        oid: crate::objects::ObjectId,
1877        pack: std::path::PathBuf,
1878        offset: u64,
1879        err: Error,
1880    ) -> Error {
1881        if matches!(err, Self::Object(ObjectError::CorruptPacked { .. })) {
1882            return err;
1883        }
1884        if !err.is_object_read_wrap_source() {
1885            return err;
1886        }
1887        match ObjectReadFailure::try_from_object_read_error(err) {
1888            Ok(source) => Self::Object(ObjectError::CorruptPacked {
1889                oid,
1890                pack,
1891                offset,
1892                source: Box::new(source),
1893            }),
1894            Err(err) => err,
1895        }
1896    }
1897
1898    /// Build [`WorktreeError::InvalidPathComponent`](crate::worktree::WorktreeError::InvalidPathComponent).
1899    #[must_use]
1900    pub fn invalid_path_component(
1901        path: impl Into<String>,
1902        reason: crate::path_validate::PathComponentError,
1903    ) -> Self {
1904        Self::Worktree(crate::worktree::WorktreeError::InvalidPathComponent {
1905            path: path.into(),
1906            reason,
1907        })
1908    }
1909
1910    /// When set, the CLI should prefix stderr with `fatal: ` for Git-compatible commands.
1911    #[must_use]
1912    pub fn wants_fatal_prefix(&self) -> bool {
1913        use crate::worktree::WorktreeError;
1914        matches!(
1915            self,
1916            Error::Config(_)
1917                | Error::Worktree(
1918                    WorktreeError::Submodule(_)
1919                        | WorktreeError::Filter(_)
1920                        | WorktreeError::OutsideRepo(_)
1921                )
1922                | Error::Ref(RefError::Lock(_))
1923        )
1924    }
1925
1926    /// Format for Git-style stderr (adds `fatal:` / `error:` when appropriate).
1927    #[must_use]
1928    pub fn git_stderr_message(&self) -> String {
1929        match self {
1930            Error::Diff(DiffError::Apply(ApplyError::CorruptPatch { .. })) => {
1931                crate::diagnostics::error_line(&self.to_string())
1932            }
1933            Error::Worktree(crate::worktree::WorktreeError::WouldOverwrite { message, .. }) => {
1934                message.clone()
1935            }
1936            e if e.wants_fatal_prefix() => crate::diagnostics::fatal_line(&e.to_string()),
1937            other => other.to_string(),
1938        }
1939    }
1940}
1941
1942impl From<crate::hooks::HookError> for Error {
1943    fn from(err: crate::hooks::HookError) -> Self {
1944        Self::Hook(err)
1945    }
1946}
1947
1948impl From<crate::porcelain::commit_error::CommitError> for Error {
1949    fn from(err: crate::porcelain::commit_error::CommitError) -> Self {
1950        Self::Commit(err)
1951    }
1952}
1953
1954impl From<crate::porcelain::merge_error::MergeError> for Error {
1955    fn from(err: crate::porcelain::merge_error::MergeError) -> Self {
1956        Self::Merge(err)
1957    }
1958}
1959
1960impl From<crate::history::HistoryError> for Error {
1961    fn from(err: crate::history::HistoryError) -> Self {
1962        Self::History(err)
1963    }
1964}
1965
1966impl From<crate::porcelain::stash_error::StashError> for Error {
1967    fn from(err: crate::porcelain::stash_error::StashError) -> Self {
1968        Self::Stash(err)
1969    }
1970}
1971
1972impl From<crate::remote::RemoteError> for Error {
1973    fn from(err: crate::remote::RemoteError) -> Self {
1974        Self::Remote(err)
1975    }
1976}
1977
1978impl From<crate::ident::CommitIdentityError> for Error {
1979    fn from(err: crate::ident::CommitIdentityError) -> Self {
1980        crate::porcelain::commit_error::CommitError::from(err).into()
1981    }
1982}
1983
1984impl From<crate::refs::store::RefStoreError> for Error {
1985    fn from(err: crate::refs::store::RefStoreError) -> Self {
1986        match err {
1987            crate::refs::store::RefStoreError::GitDirPathIo {
1988                path,
1989                operation,
1990                os_error,
1991            } => RepositoryError::git_dir_path_io(
1992                path,
1993                operation,
1994                crate::refs::store::RefStoreError::git_dir_io_source(os_error),
1995            )
1996            .into(),
1997            crate::refs::store::RefStoreError::Hook(hook) => Error::Hook(hook.into_hook_error()),
1998            other => Error::Ref(RefError::Store(other)),
1999        }
2000    }
2001}
2002
2003impl From<RefLockError> for Error {
2004    fn from(err: RefLockError) -> Self {
2005        Self::Ref(RefError::Lock(err))
2006    }
2007}
2008
2009impl From<crate::reftable::ReftableError> for Error {
2010    fn from(err: crate::reftable::ReftableError) -> Self {
2011        Self::Ref(RefError::Reftable(err))
2012    }
2013}
2014
2015impl From<crate::rev_parse_error::RevParseError> for Error {
2016    fn from(err: crate::rev_parse_error::RevParseError) -> Self {
2017        Self::Revision(RevisionError::Parse(err))
2018    }
2019}
2020
2021impl From<crate::rev_list_error::RevListError> for Error {
2022    fn from(err: crate::rev_list_error::RevListError) -> Self {
2023        Self::Revision(RevisionError::List(err))
2024    }
2025}
2026
2027impl From<ApplyError> for Error {
2028    fn from(err: ApplyError) -> Self {
2029        match err {
2030            ApplyError::Cancelled => Self::Cancelled,
2031            other => Self::Diff(DiffError::Apply(other)),
2032        }
2033    }
2034}
2035
2036impl From<crate::userdiff::FuncnamePatternError> for Error {
2037    fn from(err: crate::userdiff::FuncnamePatternError) -> Self {
2038        Self::Diff(DiffError::FuncnamePattern(err))
2039    }
2040}
2041
2042impl From<crate::porcelain::hunk_select::HunkSelectError> for Error {
2043    fn from(err: crate::porcelain::hunk_select::HunkSelectError) -> Self {
2044        Self::Diff(DiffError::HunkSelection(err))
2045    }
2046}
2047
2048impl From<FilterError> for Error {
2049    fn from(err: FilterError) -> Self {
2050        Self::Worktree(crate::worktree::WorktreeError::Filter(err))
2051    }
2052}
2053
2054impl From<SubmoduleError> for Error {
2055    fn from(err: SubmoduleError) -> Self {
2056        Self::Worktree(crate::worktree::WorktreeError::Submodule(err))
2057    }
2058}
2059
2060impl From<PathOutsideRepoError> for Error {
2061    fn from(err: PathOutsideRepoError) -> Self {
2062        Self::Worktree(crate::worktree::WorktreeError::OutsideRepo(err))
2063    }
2064}
2065
2066impl From<PathspecFromFileParseError> for Error {
2067    fn from(err: PathspecFromFileParseError) -> Self {
2068        Self::Worktree(crate::worktree::WorktreeError::PathspecFromFile(err))
2069    }
2070}
2071
2072impl From<crate::bitmap_walk::BitmapWalkError> for Error {
2073    fn from(err: crate::bitmap_walk::BitmapWalkError) -> Self {
2074        Self::Object(ObjectError::BitmapWalk(err))
2075    }
2076}
2077
2078impl From<crate::bitmap_walk::BitmapWalkUnsupported> for Error {
2079    fn from(err: crate::bitmap_walk::BitmapWalkUnsupported) -> Self {
2080        Self::Object(ObjectError::BitmapWalk(err.into()))
2081    }
2082}
2083
2084impl From<crate::pack_bitmap::BitmapError> for Error {
2085    fn from(err: crate::pack_bitmap::BitmapError) -> Self {
2086        Self::Object(ObjectError::BitmapWalk(err.into()))
2087    }
2088}
2089
2090impl From<crate::object_inspect::ResolveError> for Error {
2091    fn from(err: crate::object_inspect::ResolveError) -> Self {
2092        Self::Revision(RevisionError::Resolve(err))
2093    }
2094}
2095
2096impl From<MidxError> for Error {
2097    fn from(err: MidxError) -> Self {
2098        Self::Object(ObjectError::Midx(err))
2099    }
2100}
2101
2102impl From<crate::offload::OffloadError> for Error {
2103    fn from(err: crate::offload::OffloadError) -> Self {
2104        Self::Object(ObjectError::Offload(err))
2105    }
2106}
2107
2108impl From<crate::objects::TreeEntryError> for Error {
2109    fn from(err: crate::objects::TreeEntryError) -> Self {
2110        Self::Object(ObjectError::InvalidTreeEntry(err))
2111    }
2112}
2113
2114impl From<crate::ident::SignatureError> for Error {
2115    fn from(err: crate::ident::SignatureError) -> Self {
2116        Self::Object(ObjectError::InvalidSignature(err))
2117    }
2118}
2119
2120impl From<crate::config::ident_resolve::IdentityError> for Error {
2121    fn from(err: crate::config::ident_resolve::IdentityError) -> Self {
2122        Self::Commit(crate::porcelain::commit_error::CommitError::Identity(err))
2123    }
2124}
2125
2126impl From<crate::ident::AuthorArgError> for Error {
2127    fn from(err: crate::ident::AuthorArgError) -> Self {
2128        Self::History(crate::history::HistoryError::InvalidAuthor(err))
2129    }
2130}
2131
2132impl From<crate::change_id::ChangeIdError> for Error {
2133    fn from(err: crate::change_id::ChangeIdError) -> Self {
2134        Self::Commit(crate::porcelain::commit_error::CommitError::ChangeId(err))
2135    }
2136}
2137
2138impl From<crate::tree_sha256::TreeSha256ClaimError> for Error {
2139    fn from(err: crate::tree_sha256::TreeSha256ClaimError) -> Self {
2140        Self::Tag(crate::porcelain::tag::TagError::TreeSha256Claim(err))
2141    }
2142}
2143
2144impl From<Cancelled> for Error {
2145    fn from(_: Cancelled) -> Self {
2146        Self::Cancelled
2147    }
2148}
2149
2150impl From<crate::worktree::LinkedWorktreeError> for Error {
2151    fn from(value: crate::worktree::LinkedWorktreeError) -> Self {
2152        Self::Worktree(value.into())
2153    }
2154}
2155
2156impl From<PathIoError> for Error {
2157    fn from(value: PathIoError) -> Self {
2158        match value.operation {
2159            PathIoOperation::Worktree(_) => {
2160                Self::Worktree(crate::worktree::WorktreeError::PathIo(value))
2161            }
2162            PathIoOperation::GitDir(_) => Self::Repository(RepositoryError::GitDirPathIo(value)),
2163        }
2164    }
2165}
2166
2167impl From<crate::lockfile::LockError> for Error {
2168    /// [`LockError::Held`](crate::lockfile::LockError::Held) becomes [`Error::LockHeld`] with the
2169    /// recorded [`LockHolder`](crate::lockfile::LockHolder), and I/O failures become [`Error::Io`].
2170    #[cold]
2171    fn from(err: crate::lockfile::LockError) -> Self {
2172        use crate::lockfile::{LockError, LockHolder};
2173        match err {
2174            LockError::Held { path } => Self::LockHeld(LockHeldError {
2175                holder: LockHolder::read(&path),
2176                path,
2177            }),
2178            LockError::Io { source, .. } => Self::Io(source),
2179        }
2180    }
2181}
2182
2183impl From<crate::serve::ServeError> for Error {
2184    fn from(err: crate::serve::ServeError) -> Self {
2185        Self::Remote(crate::remote::RemoteError::Serve(err))
2186    }
2187}
2188
2189impl From<crate::snapshot_checkout::CheckoutError> for Error {
2190    fn from(err: crate::snapshot_checkout::CheckoutError) -> Self {
2191        Self::Remote(crate::remote::RemoteError::Snapshot(err))
2192    }
2193}
2194
2195impl From<crate::clone::CloneError> for Error {
2196    fn from(err: crate::clone::CloneError) -> Self {
2197        Self::Remote(crate::remote::RemoteError::Clone(Box::new(err)))
2198    }
2199}
2200
2201impl From<crate::porcelain::pull::PullError> for Error {
2202    fn from(err: crate::porcelain::pull::PullError) -> Self {
2203        Self::Merge(crate::porcelain::merge_error::MergeError::Pull(err))
2204    }
2205}
2206
2207impl From<crate::remote::push_plan::PushPlanError> for Error {
2208    fn from(err: crate::remote::push_plan::PushPlanError) -> Self {
2209        Self::Remote(crate::remote::RemoteError::PushPlan(err))
2210    }
2211}
2212
2213impl From<crate::history::RebaseSessionError> for Error {
2214    fn from(err: crate::history::RebaseSessionError) -> Self {
2215        match err {
2216            crate::history::RebaseSessionError::NothingToCommit => {
2217                Self::Commit(crate::porcelain::commit_error::CommitError::NothingToCommit)
2218            }
2219            other => Self::History(crate::history::HistoryError::RebaseSession(Box::new(other))),
2220        }
2221    }
2222}
2223
2224impl From<crate::porcelain::stash_error::StashPushValidationError> for Error {
2225    fn from(err: crate::porcelain::stash_error::StashPushValidationError) -> Self {
2226        Self::Stash(crate::porcelain::stash_error::StashError::PushValidation(
2227            err,
2228        ))
2229    }
2230}
2231
2232impl From<crate::bundle::BundleError> for Error {
2233    fn from(err: crate::bundle::BundleError) -> Self {
2234        use crate::bundle::BundleError;
2235        match err {
2236            BundleError::Cancelled => Self::Cancelled,
2237            BundleError::ObjectNotFound { name } => Self::Object(ObjectError::NotFound { name }),
2238            other => Self::Remote(crate::remote::RemoteError::Bundle(other)),
2239        }
2240    }
2241}
2242
2243impl From<crate::fetch_request::FetchRefspecError> for Error {
2244    fn from(e: crate::fetch_request::FetchRefspecError) -> Self {
2245        Self::Remote(crate::remote::RemoteError::FetchRefspec(e))
2246    }
2247}
2248
2249/// Convenience alias for `Result<T, Error>`.
2250pub type Result<T> = std::result::Result<T, Error>;
2251
2252/// Serializes as `{"kind": <Error::kind_name>, "area": <Error::area>, "message": <Display text>}`,
2253/// plus structured fields for lock, overwrite, dirty-worktree, and conflict-marker failures.
2254#[cfg(feature = "serde-models")]
2255impl serde::Serialize for Error {
2256    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2257    where
2258        S: serde::Serializer,
2259    {
2260        use crate::worktree::WorktreeError;
2261        use serde::ser::SerializeStruct;
2262
2263        match self {
2264            Self::LockHeld(lock) => {
2265                let mut out = serializer.serialize_struct("Error", 5)?;
2266                out.serialize_field("kind", self.kind_name())?;
2267                out.serialize_field("area", self.area())?;
2268                out.serialize_field("message", &self.to_string())?;
2269                out.serialize_field(
2270                    "path",
2271                    &crate::git_path::user_display_path(lock.path.as_path()),
2272                )?;
2273                if let Some(holder) = lock.holder {
2274                    out.serialize_field(
2275                        "holder",
2276                        &LockHolderSerde {
2277                            pid: holder.pid,
2278                            running: holder.running,
2279                        },
2280                    )?;
2281                }
2282                out.end()
2283            }
2284            Self::Worktree(WorktreeError::WouldOverwrite { reason, paths, .. }) => {
2285                let mut out = serializer.serialize_struct("Error", 5)?;
2286                out.serialize_field("kind", self.kind_name())?;
2287                out.serialize_field("area", self.area())?;
2288                out.serialize_field("message", &self.to_string())?;
2289                out.serialize_field("reason", &reason.to_string())?;
2290                out.serialize_field("paths", paths)?;
2291                out.end()
2292            }
2293            Self::Worktree(WorktreeError::DirtyWorktree { operation, paths }) => {
2294                let mut out = serializer.serialize_struct("Error", 5)?;
2295                out.serialize_field("kind", self.kind_name())?;
2296                out.serialize_field("area", self.area())?;
2297                out.serialize_field("message", &self.to_string())?;
2298                out.serialize_field("operation", &operation.to_string())?;
2299                out.serialize_field("paths", paths)?;
2300                out.end()
2301            }
2302            Self::Worktree(WorktreeError::UnmergedConflictMarkers { paths }) => {
2303                let mut out = serializer.serialize_struct("Error", 4)?;
2304                out.serialize_field("kind", self.kind_name())?;
2305                out.serialize_field("area", self.area())?;
2306                out.serialize_field("message", &self.to_string())?;
2307                out.serialize_field("paths", paths)?;
2308                out.end()
2309            }
2310            Self::Stash(stash) => stash.serialize(serializer),
2311            _ => {
2312                let mut out = serializer.serialize_struct("Error", 3)?;
2313                out.serialize_field("kind", self.kind_name())?;
2314                out.serialize_field("area", self.area())?;
2315                out.serialize_field("message", &self.to_string())?;
2316                out.end()
2317            }
2318        }
2319    }
2320}
2321
2322#[cfg(test)]
2323mod object_read_failure_tests {
2324    use super::{Error, ObjectError, ObjectReadFailure};
2325
2326    #[test]
2327    fn try_from_object_read_error_rejects_unrelated_umbrella_variants() {
2328        assert!(matches!(
2329            ObjectReadFailure::try_from_object_read_error(Error::Cancelled),
2330            Err(Error::Cancelled)
2331        ));
2332    }
2333
2334    #[test]
2335    fn try_from_object_read_error_maps_decode_variants() {
2336        assert!(matches!(
2337            ObjectReadFailure::try_from_object_read_error(Error::Object(ObjectError::Zlib {
2338                detail: "bad".into()
2339            })),
2340            Ok(ObjectReadFailure::Zlib { .. })
2341        ));
2342    }
2343}
2344
2345#[cfg(test)]
2346mod umbrella_area_tests {
2347    use super::{
2348        ConfigError, DiffError, Error, ErrorSummary, LockHeldError, NotesError, ObjectError,
2349        RefError, RepositoryError, RevisionError,
2350    };
2351    use crate::history::HistoryError;
2352    use crate::hooks::{HookError, HookOutput};
2353    use crate::index::IndexError;
2354    use crate::porcelain::branch_error::BranchError;
2355    use crate::porcelain::commit_error::CommitError;
2356    use crate::porcelain::merge_error::MergeError;
2357    use crate::porcelain::stash_error::StashError;
2358    use crate::porcelain::tag::TagError;
2359    use crate::remote::RemoteError;
2360    use crate::worktree::WorktreeError;
2361
2362    /// Area name for each umbrella variant, written without a wildcard arm so a new variant
2363    /// fails to compile here until it is listed in [`AREAS`].
2364    fn area_by_variant(err: &Error) -> &'static str {
2365        match err {
2366            Error::Repository(_) => "repository",
2367            Error::Object(_) => "object",
2368            Error::Index(_) => "index",
2369            Error::Ref(_) => "ref",
2370            Error::Revision(_) => "revision",
2371            Error::Config(_) => "config",
2372            Error::Worktree(_) => "worktree",
2373            Error::Diff(_) => "diff",
2374            Error::Commit(_) => "commit",
2375            Error::Merge(_) => "merge",
2376            Error::History(_) => "history",
2377            Error::Stash(_) => "stash",
2378            Error::Branch(_) => "branch",
2379            Error::Tag(_) => "tag",
2380            Error::Notes(_) => "notes",
2381            Error::Remote(_) => "remote",
2382            Error::Hook(_) => "hook",
2383            Error::Io(_) => "io",
2384            Error::LockHeld(_) => "lock_held",
2385            Error::Cancelled => "cancelled",
2386        }
2387    }
2388
2389    const AREAS: &[&str] = &[
2390        "repository",
2391        "object",
2392        "index",
2393        "ref",
2394        "revision",
2395        "config",
2396        "worktree",
2397        "diff",
2398        "commit",
2399        "merge",
2400        "history",
2401        "stash",
2402        "branch",
2403        "tag",
2404        "notes",
2405        "remote",
2406        "hook",
2407        "io",
2408        "lock_held",
2409        "cancelled",
2410    ];
2411
2412    fn one_error_per_area() -> Vec<Error> {
2413        vec![
2414            Error::Repository(RepositoryError::RequiresWorkTree),
2415            Error::Object(ObjectError::InvalidId {
2416                input: "xyz".into(),
2417            }),
2418            Error::Index(IndexError::CacheTreeCorrupt),
2419            Error::Ref(RefError::UnbornHead),
2420            Error::Revision(RevisionError::NotFound {
2421                spec: "nope".into(),
2422            }),
2423            Error::Config(ConfigError::ConfigCacheLockPoisoned),
2424            Error::Worktree(WorktreeError::RemovePathsRequired),
2425            Error::Diff(DiffError::BlameWorktreeBareRepository),
2426            Error::Commit(CommitError::EmptyCommitMessage),
2427            Error::Merge(MergeError::NotFastForward),
2428            Error::History(HistoryError::EmptyMessage),
2429            Error::Stash(StashError::NoInitialCommit),
2430            Error::Branch(BranchError::NoPreviousBranch),
2431            Error::Tag(TagError::EmptyMessage),
2432            Error::Notes(NotesError::AlreadyExists {
2433                object: crate::objects::ObjectId::zero(),
2434            }),
2435            Error::Remote(RemoteError::HttpUnavailable),
2436            Error::Hook(HookError::Failed {
2437                hook_name: "pre-commit".into(),
2438                status: 1,
2439                output: HookOutput::default(),
2440            }),
2441            Error::Io(std::io::Error::other("disk")),
2442            Error::LockHeld(LockHeldError {
2443                path: ".git/index.lock".into(),
2444                holder: None,
2445            }),
2446            Error::Cancelled,
2447        ]
2448    }
2449
2450    #[test]
2451    fn umbrella_error_has_one_variant_per_area() {
2452        let samples = one_error_per_area();
2453        assert_eq!(samples.len(), AREAS.len());
2454        let mut seen = std::collections::HashSet::new();
2455        for (err, expected) in samples.iter().zip(AREAS) {
2456            assert_eq!(area_by_variant(err), *expected);
2457            assert_eq!(err.area(), *expected, "{err:?}");
2458            assert!(seen.insert(err.area()), "area {expected} listed twice");
2459            assert!(!err.kind_name().is_empty());
2460        }
2461    }
2462
2463    #[test]
2464    fn area_errors_convert_into_their_umbrella_variant() {
2465        let cases: Vec<(Error, &str)> = vec![
2466            (RepositoryError::RequiresWorkTree.into(), "repository"),
2467            (RefError::UnbornHead.into(), "ref"),
2468            (
2469                RevisionError::NotFound { spec: "x".into() }.into(),
2470                "revision",
2471            ),
2472            (CommitError::EmptyCommitMessage.into(), "commit"),
2473            (MergeError::NotFastForward.into(), "merge"),
2474            (HistoryError::EmptyMessage.into(), "history"),
2475            (StashError::NoInitialCommit.into(), "stash"),
2476            (BranchError::NoPreviousBranch.into(), "branch"),
2477            (TagError::EmptyMessage.into(), "tag"),
2478            (RemoteError::HttpUnavailable.into(), "remote"),
2479            (IndexError::CacheTreeCorrupt.into(), "index"),
2480            (WorktreeError::RemovePathsRequired.into(), "worktree"),
2481        ];
2482        for (err, area) in cases {
2483            assert_eq!(err.area(), area, "{err:?}");
2484        }
2485    }
2486
2487    #[test]
2488    fn error_summary_keeps_kind_area_message_and_cancellation() {
2489        let summary = ErrorSummary::from(&Error::Ref(RefError::UnbornHead));
2490        assert_eq!(summary.kind(), Error::Ref(RefError::UnbornHead).kind_name());
2491        assert_eq!(summary.area(), "ref");
2492        assert_eq!(
2493            summary.message(),
2494            Error::Ref(RefError::UnbornHead).to_string()
2495        );
2496        assert_eq!(summary.to_string(), summary.message());
2497        assert!(!summary.is_cancelled());
2498
2499        let cancelled = ErrorSummary::from(Error::Cancelled);
2500        assert!(cancelled.is_cancelled());
2501        assert_eq!(cancelled.kind(), "cancelled");
2502        assert_eq!(cancelled.area(), "cancelled");
2503        assert_eq!(cancelled.clone(), cancelled);
2504        assert_eq!(
2505            std::mem::size_of::<ErrorSummary>(),
2506            std::mem::size_of::<usize>()
2507        );
2508    }
2509}
2510
2511#[cfg(feature = "serde-models")]
2512#[derive(serde::Serialize)]
2513struct LockHolderSerde {
2514    pid: u64,
2515    running: bool,
2516}