use std::path::PathBuf;
use thiserror::Error;
mod diff;
mod notes;
mod object;
mod refs;
mod revision;
mod summary;
pub use diff::DiffError;
pub use notes::NotesError;
pub use object::{ObjectError, PromisorFetchFailure};
pub use refs::RefError;
pub use revision::RevisionError;
pub use summary::ErrorSummary;
pub use crate::git_dir::GitDirPathOperation;
pub use crate::midx_error::MidxError;
pub use crate::repo::RepositoryError;
pub use crate::worktree::io_error::WorktreePathOperation;
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error(
"lock file {} already exists",
crate::git_path::user_display_path(.path.as_path())
)]
pub struct LockHeldError {
pub path: PathBuf,
pub holder: Option<crate::lockfile::LockHolder>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cancelled;
impl std::fmt::Display for Cancelled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("operation cancelled")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PathIoOperation {
GitDir(GitDirPathOperation),
Worktree(WorktreePathOperation),
}
#[derive(Debug)]
pub struct PathIoError {
pub operation: PathIoOperation,
pub path: Option<PathBuf>,
pub source: std::io::Error,
}
fn preserve_io_error(source: &std::io::Error) -> std::io::Error {
if let Some(raw) = source.raw_os_error() {
std::io::Error::from_raw_os_error(raw)
} else {
std::io::Error::new(source.kind(), source.to_string())
}
}
impl std::fmt::Display for PathIoError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message())
}
}
impl std::error::Error for PathIoError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
impl PathIoError {
#[must_use]
pub fn worktree(
path: impl Into<String>,
operation: WorktreePathOperation,
source: std::io::Error,
) -> Self {
Self {
operation: PathIoOperation::Worktree(operation),
path: Some(PathBuf::from(path.into())),
source,
}
}
#[must_use]
pub fn git_dir(
path: impl Into<String>,
operation: GitDirPathOperation,
source: std::io::Error,
) -> Self {
Self {
operation: PathIoOperation::GitDir(operation),
path: Some(PathBuf::from(path.into())),
source,
}
}
#[must_use]
pub fn message(&self) -> String {
let path = self
.path
.as_ref()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default();
match self.operation {
PathIoOperation::Worktree(op) => {
crate::worktree::io_error::format_worktree_path_io_message(&path, op, &self.source)
}
PathIoOperation::GitDir(op) => {
crate::git_dir::io_error::format_git_dir_io_message(&path, op, &self.source)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BadNumericSource {
InvalidUnit,
OutOfRange,
}
impl BadNumericSource {
fn detail(self) -> &'static str {
match self {
Self::InvalidUnit => "invalid unit",
Self::OutOfRange => "out of range",
}
}
}
impl std::fmt::Display for BadNumericSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.detail())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OverwriteReason {
LocalChanges,
Untracked,
}
impl std::fmt::Display for OverwriteReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::LocalChanges => f.write_str("local_changes"),
Self::Untracked => f.write_str("untracked"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RemoteUnreadableReason {
RepositoryNotFound,
Transport {
detail: String,
},
HttpStatus {
status: u16,
},
NotGitServer {
status: u16,
content_type: Option<String>,
},
NoHandshake,
ResponseTruncated,
}
impl RemoteUnreadableReason {
#[must_use]
pub fn slug(&self) -> &'static str {
match self {
Self::RepositoryNotFound => "repository_not_found",
Self::Transport { .. } => "transport",
Self::HttpStatus { .. } => "http_status",
Self::NotGitServer { .. } => "not_git_server",
Self::NoHandshake => "no_handshake",
Self::ResponseTruncated => "response_truncated",
}
}
}
pub(crate) fn remote_unreadable_message(
url: Option<&str>,
reason: &RemoteUnreadableReason,
) -> String {
let target = url.map_or_else(|| "the remote".to_owned(), |u| format!("'{u}'"));
match reason {
RemoteUnreadableReason::RepositoryNotFound => {
format!("could not find repository at {target}")
}
RemoteUnreadableReason::Transport { detail } => {
format!("could not reach {target}: {detail}")
}
RemoteUnreadableReason::HttpStatus { status } => match url {
Some(u) => format!("HTTP {status} from {u}"),
None => format!("HTTP {status} from the remote"),
},
RemoteUnreadableReason::NotGitServer {
status,
content_type,
} => {
let got = match content_type
.as_deref()
.map(|ct| ct.split(';').next().unwrap_or(ct).trim())
.filter(|ct| !ct.is_empty())
{
Some(ct) => format!("{status} {ct}"),
None => status.to_string(),
};
format!("{target} did not answer like a Git server (got {got})")
}
RemoteUnreadableReason::NoHandshake => {
format!("could not read from {target}: no Git protocol response")
}
RemoteUnreadableReason::ResponseTruncated => {
format!("{target} closed the connection before sending the pack")
}
}
}
pub(crate) fn remote_transport_message(url: Option<&str>, detail: &str) -> String {
match url {
Some(u) => format!("could not reach {u}: {detail}"),
None => format!("transport failure: {detail}"),
}
}
pub(crate) fn remote_http_status_message(url: Option<&str>, status: u16) -> String {
match url {
Some(u) => format!("HTTP {status} from {u}"),
None => format!("HTTP {status} from the remote"),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum AuthFailure {
#[error("no credential provider is configured")]
NoCredentialProvider,
#[error("{detail}")]
CredentialsUnavailable {
detail: String,
helpers: Vec<String>,
},
#[error("the credential helper returned no usable username and password")]
UnusableCredentials,
#[error("the URL cannot be described to a credential helper")]
UrlNotDescribable,
#[error("unsupported authentication scheme: {}", schemes.join(", "))]
UnsupportedScheme {
schemes: Vec<String>,
},
#[error("the server rejected the credentials")]
Rejected,
}
impl AuthFailure {
#[must_use]
pub fn is_rejected(&self) -> bool {
matches!(self, Self::Rejected)
}
#[must_use]
pub fn from_fill_error(err: Error) -> Self {
let helpers = match &err {
Error::Remote(crate::remote::RemoteError::CredentialsUnavailable { helpers }) => {
helpers.clone()
}
_ => Vec::new(),
};
Self::CredentialsUnavailable {
detail: err.to_string(),
helpers,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WorktreeOperation {
Switch,
Pick,
Merge,
RebaseExec,
Rebase,
}
impl std::fmt::Display for WorktreeOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Switch => "switching",
Self::Pick => "picking",
Self::Merge => "merging",
Self::RebaseExec => "rebasing with --exec",
Self::Rebase => "rebasing",
})
}
}
#[derive(Debug, Error, Clone, PartialEq)]
#[non_exhaustive]
pub enum ConfigError {
#[error("bad config line {line} in {location}")]
BadConfigLine {
location: String,
line: usize,
},
#[error("bad config line {line} in file '{file}'")]
BadConfigLineInFile {
file: String,
line: usize,
},
#[error("missing value for '{key}'")]
MissingValue {
key: String,
},
#[error("bad config variable '{key}' in file '{file}' at line {line}")]
BadConfigVariable {
key: String,
file: String,
line: usize,
},
#[error("key '{key}' is not set")]
KeyNotSet {
key: String,
},
#[error("bad numeric config value '{value}' for '{key}': {reason}")]
BadNumericValue {
key: String,
value: String,
reason: BadNumericSource,
},
#[error("bad numeric config value '{value}' for '{key}' in file {file}: {reason}")]
BadNumericValueInFile {
key: String,
value: String,
file: String,
reason: BadNumericSource,
},
#[error("bad config variable '{key}' in file '{file}' at line {line}")]
BadConfigVariableAtLine {
key: String,
file: String,
line: usize,
},
#[error("unable to parse '{key}' from command-line config")]
UnableToParseFromCommandLine {
key: String,
},
#[error(
"remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"
)]
RemoteUrlInHasconfigInclude,
#[error("exceeded maximum include depth (depth {depth} exceeds limit {limit})")]
IncludeDepthExceeded {
depth: usize,
limit: usize,
},
#[error("{}", invalid_key_message(key, *reason))]
InvalidKey {
key: String,
reason: InvalidKeyReason,
},
#[error("invalid section name: {section}")]
InvalidSectionName {
section: String,
},
#[error("invalid value-pattern regex '{pattern}': {reason}")]
InvalidValuePattern {
pattern: String,
reason: String,
},
#[error("invalid key pattern '{pattern}': {source}")]
InvalidPattern {
pattern: String,
#[source]
source: regex::Error,
},
#[error("unknown repository format version: {version}")]
UnsupportedRepositoryFormatVersion {
version: u32,
},
#[error("config cache lock poisoned")]
ConfigCacheLockPoisoned,
#[error("config session lock poisoned")]
ConfigSessionLockPoisoned,
#[error("config session missing after refresh")]
ConfigSessionMissingAfterRefresh,
#[error("invalid list prefix '{prefix}'")]
InvalidListPrefix {
prefix: String,
},
#[error("unknown value '{value}' for '{key}'")]
UnknownValue {
key: String,
value: String,
},
#[error("invalid number of threads ({value}) for '{key}'")]
InvalidThreadCount {
key: String,
value: i64,
},
#[error("bogus count in GIT_CONFIG_COUNT: '{value}'")]
InvalidEnvironmentCount {
value: String,
},
#[error("missing config key GIT_CONFIG_KEY_{index}")]
MissingEnvironmentKey {
index: usize,
},
#[error("bogus format in GIT_CONFIG_PARAMETERS")]
MalformedConfigParameters,
#[error("relative config includes must come from files")]
RelativeIncludeOutsideFile,
#[error("not in a git repository")]
RepositoryRequired,
#[error("could not determine global config path")]
NoGlobalConfigPath,
#[error("'{value}' is not a date for '{key}'")]
InvalidDate {
key: String,
value: String,
},
#[error("could not lock config file {path}: File exists")]
ConfigFileLocked {
path: String,
},
#[error("cannot overwrite multiple values with a single value for '{key}'")]
MultipleValues {
key: String,
},
#[error(
"worktree config is only allowed when extensions.worktreeConfig is enabled in the common config"
)]
WorktreeConfigNotEnabled,
#[error("section '{section}' not found")]
SectionNotFound {
section: String,
},
#[error("no multi-line comment allowed")]
MultilineCommentNotAllowed,
#[error(
"invalid value '{value}' for 'status.showUntrackedFiles' (expected no, normal, all, boolean words, or integer 0 vs nonzero)"
)]
InvalidUntrackedFilesMode {
value: String,
},
#[error(
"invalid value '{value}' for 'merge.directoryRenames' (expected true, false or conflict)"
)]
InvalidDirectoryRenames {
value: String,
},
#[error("{source} for '{key}'")]
InvalidValue {
key: String,
#[source]
source: ConfigValueError,
},
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigValueError {
#[error("bad boolean config value '{value}'")]
InvalidBool {
value: String,
},
#[error("empty integer value")]
EmptyInteger,
#[error("invalid integer: '{value}'")]
InvalidInteger {
value: String,
},
#[error("integer overflow: '{value}'")]
IntegerOverflow {
value: String,
},
#[error("bad color value '{value}'")]
InvalidColor {
value: String,
},
}
impl ConfigValueError {
#[must_use]
pub fn for_key(self, key: impl Into<String>) -> ConfigError {
ConfigError::InvalidValue {
key: key.into(),
source: self,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidKeyReason {
LineBreak,
MissingSection,
MissingVariable,
InvalidSection,
InvalidVariable,
}
fn invalid_key_message(key: &str, reason: InvalidKeyReason) -> String {
match reason {
InvalidKeyReason::LineBreak => format!(
"invalid key: '{}'",
key.replace('\n', "\\n").replace('\r', "\\r")
),
InvalidKeyReason::MissingSection => format!("key does not contain a section: '{key}'"),
InvalidKeyReason::MissingVariable => {
format!("key does not contain variable name: '{key}'")
}
InvalidKeyReason::InvalidSection => format!("invalid key (bad section): '{key}'"),
InvalidKeyReason::InvalidVariable => format!("invalid key (bad variable name): '{key}'"),
}
}
impl From<crate::config::GitConfigIntStrictError> for BadNumericSource {
fn from(value: crate::config::GitConfigIntStrictError) -> Self {
match value {
crate::config::GitConfigIntStrictError::InvalidUnit => Self::InvalidUnit,
crate::config::GitConfigIntStrictError::OutOfRange => Self::OutOfRange,
}
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubmoduleError {
#[error("submodule path is empty")]
EmptyPath,
#[error("submodule path '{path}' passes through symbolic link '{component}'")]
SymlinkInPath {
path: String,
component: String,
},
#[error("git dir {} of submodule '{name}' does not end with its name", .git_dir.display())]
GitDirNameMismatch {
name: String,
git_dir: std::path::PathBuf,
},
#[error("git dir of submodule '{name}' lies inside another submodule's git dir")]
GitDirNested {
name: String,
},
#[error("submodule git dir {} has no modules/ segment", .git_dir.display())]
GitDirOutsideModules {
git_dir: std::path::PathBuf,
},
#[error("encoded submodule git dir {} has '/' after modules/", .git_dir.display())]
GitDirSegmentHasSlash {
git_dir: std::path::PathBuf,
},
#[error("git dir {} of submodule '{name}' is already used by another submodule", .git_dir.display())]
GitDirInUse {
name: String,
git_dir: std::path::PathBuf,
},
#[error("git dir {} of submodule '{name}' differs only in case from another submodule's", .git_dir.display())]
GitDirCaseConflict {
name: String,
git_dir: std::path::PathBuf,
},
#[error("could not choose a git dir for submodule '{name}'")]
GitDirUnavailable {
name: String,
},
#[error("submodule.{name}.gitdir is not set (submodulePathConfig is enabled)")]
GitDirNotConfigured {
name: String,
},
#[error("could not read HEAD of submodule '{path}'")]
HeadUnreadable {
path: String,
},
#[error("submodule at '{path}' is not checked out")]
NotCheckedOut {
path: String,
},
#[error("HEAD of submodule '{path}' does not point to a readable commit")]
HeadCommitMissing {
path: String,
},
}
impl ConfigError {
#[must_use]
pub fn message_body(&self) -> String {
self.to_string()
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RefLockError {
#[error(
"cannot lock ref '{refname}': there is a non-empty directory '{path}' blocking reference '{refname}'"
)]
DirectoryInTheWay {
refname: String,
path: String,
},
#[error("Unable to create '{lock_path}': File exists.")]
PackedRefsLockHeld {
lock_path: String,
},
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterError {
#[error("{path}: {phase} filter '{driver}' failed")]
ExternalFilterFailed {
driver: String,
path: String,
phase: FilterPhase,
},
#[error("{path}: cannot start {phase} filter '{driver}' ({program}): {detail}")]
ExternalFilterSpawnFailed {
driver: String,
path: String,
phase: FilterPhase,
program: String,
kind: std::io::ErrorKind,
detail: String,
},
#[error("{path}: {detail}")]
NotFilteredProperly {
path: String,
detail: String,
},
#[error("true/false are no valid working-tree-encodings")]
InvalidWorkingTreeEncoding,
#[error("{detail}")]
LineEndingWouldChange {
detail: String,
},
#[error("{path}: filter delayed the checkout, which this operation does not support")]
DelayedCheckoutUnsupported {
path: String,
},
#[error("filter command exited with status {status}")]
Failed {
status: i32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterPhase {
Smudge,
Clean,
}
impl std::fmt::Display for FilterPhase {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Smudge => f.write_str("smudge"),
Self::Clean => f.write_str("clean"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SparseCheckoutWarning {
UnrecognizedPattern {
pattern: String,
},
UnrecognizedNegativePattern {
pattern: String,
},
RepeatedPattern {
pattern: String,
},
DisablingConePatternMatching,
}
impl SparseCheckoutWarning {
#[must_use]
pub fn body(&self) -> String {
match self {
Self::UnrecognizedPattern { pattern } => {
format!("unrecognized pattern: '{pattern}'")
}
Self::UnrecognizedNegativePattern { pattern } => {
format!("unrecognized negative pattern: '{pattern}'")
}
Self::RepeatedPattern { pattern } => format!(
"your sparse-checkout file may have issues: pattern '{pattern}' is repeated"
),
Self::DisablingConePatternMatching => "disabling cone pattern matching".to_owned(),
}
}
#[must_use]
pub fn format_line(&self) -> String {
crate::diagnostics::warning_line(&self.body())
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApplyError {
#[error("corrupt patch at {input}:{line}")]
CorruptPatch {
input: String,
line: usize,
},
#[error(
"patch failed: context mismatch at hunk {hunk_index} (expected near line {expected_line})"
)]
ContextMismatch {
hunk_index: usize,
expected_line: usize,
},
#[error("patch failed: overlapping hunks at hunk {hunk_index}")]
HunksOverlap {
hunk_index: usize,
},
#[error("patch failed: unexpected end of file at hunk {hunk_index}")]
UnexpectedEof {
hunk_index: usize,
},
#[error("diff path is not valid UTF-8")]
PathNotUtf8,
#[error("unable to find filename in traditional patch")]
MissingFilename,
#[error("malformed {side} path in diff --git header: {path}")]
MalformedHeaderPath {
side: PatchSide,
path: String,
},
#[error("invalid mode on line {line}: {text}")]
InvalidMode {
line: usize,
text: String,
},
#[error("invalid hunk header: {header}")]
InvalidHunkHeader {
header: String,
},
#[error(transparent)]
BinaryPatch(#[from] BinaryPatchError),
#[error("patch failed: {path}:{line}")]
PatchFailed {
path: String,
line: usize,
},
#[error("could not apply patch to {path}: {message}")]
Failed {
path: String,
message: String,
},
#[error("'{path}' is not in the index")]
NotInIndex {
path: String,
},
#[error("binary patch data missing for '{path}'")]
BinaryDataMissing {
path: String,
},
#[error("operation cancelled")]
Cancelled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PatchSide {
Old,
New,
}
impl std::fmt::Display for PatchSide {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Old => "old",
Self::New => "new",
})
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BinaryPatchError {
#[error("unsupported binary patch section: '{header}'")]
UnsupportedSection {
header: String,
},
#[error("invalid binary patch section size: '{size}'")]
InvalidSectionSize {
size: String,
},
#[error("empty binary patch payload line")]
EmptyLine,
#[error("invalid binary patch line length marker: '{marker}'")]
InvalidLineLength {
marker: char,
},
#[error("invalid binary patch base85")]
InvalidBase85,
#[error("failed to inflate binary patch payload: {detail}")]
Inflate {
detail: String,
},
#[error("binary patch literal size {actual} != declared {declared}")]
SizeMismatch {
actual: usize,
declared: usize,
},
#[error("binary patch delta requires a base blob")]
DeltaWithoutBase,
#[error("binary patch has no reverse section")]
NoReverseSection,
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathspecFromFileParseError {
#[error("invalid UTF-8 in pathspec-from-file (NUL mode)")]
InvalidUtf8InNulRecord,
#[error("pathspec-from-file: line is not NUL terminated: {line}")]
QuotedLineInNulMode {
line: String,
},
#[error("invalid C-style quoting: {line}")]
InvalidCStyleQuoting {
line: String,
},
#[error("invalid escape at end of string")]
InvalidEscapeAtEnd,
#[error("truncated octal escape")]
TruncatedOctalEscape,
#[error("invalid octal bytes")]
InvalidOctalBytes,
#[error("invalid octal escape value")]
InvalidOctalValue,
#[error("invalid escape sequence \\{escape}")]
InvalidEscapeSequence {
escape: char,
},
#[error("invalid UTF-8 in quoted pathspec")]
InvalidUtf8InQuotedLine,
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathspecResolveError {
#[error("invalid path ''")]
EmptyPathspec,
#[error("{elt}: '{path}' is outside repository at '{work_tree}'")]
OutsideRepository {
elt: String,
path: String,
work_tree: String,
},
#[error(transparent)]
FromFile(#[from] PathspecFromFileParseError),
#[error("this operation needs a working tree")]
NeedsWorkTree,
#[error(transparent)]
InvalidGlobals(#[from] crate::pathspec::PathspecGlobalsError),
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AttrPathspecError {
#[error("attr requirement list is empty")]
Empty,
#[error("a pathspec may contain at most one attr clause")]
MultipleAttrClauses,
#[error("'{name}' is not a usable attribute name")]
InvalidName {
name: String,
},
#[error("attr value ends with a dangling escape")]
DanglingEscape,
#[error("attr values may only escape ','")]
UnsupportedEscape,
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathOutsideRepoError {
#[error("'{subpath}' is outside repository at '{repo_root}'")]
OutsideRepository {
path: String,
subpath: String,
repo_root: String,
},
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum NotARepositoryReason {
#[error("{}", crate::git_path::path_for_error_message(path))]
NoRepositoryAt {
path: std::path::PathBuf,
},
#[error(
"invalid gitfile format: {} is not a regular file",
crate::git_path::path_for_error_message(path)
)]
GitfileNotRegularFile {
path: std::path::PathBuf,
},
#[error("invalid gitfile format")]
GitfileMissingGitdir {
path: std::path::PathBuf,
},
#[error("{error}")]
GitfileUnreadable {
path: std::path::PathBuf,
error: std::io::Error,
},
}
pub(crate) fn maintenance_running_message(holder: &crate::maintenance::GcLockHolder) -> String {
match (holder.pid, holder.host.as_deref()) {
(Some(pid), Some(host)) => {
format!("repository maintenance is already running (process {pid} on {host})")
}
(Some(pid), None) => format!("repository maintenance is already running (process {pid})"),
_ => "repository maintenance is already running".to_owned(),
}
}
pub(crate) fn restore_unmerged_message(paths: &[String]) -> String {
match paths {
[path] => format!("path '{path}' is unmerged"),
_ => format!(
"paths are unmerged: {}",
paths
.iter()
.map(|p| format!("'{p}'"))
.collect::<Vec<_>>()
.join(", ")
),
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ObjectReadFailure {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("zlib error: {detail}")]
Zlib {
detail: String,
},
#[error("corrupt object: {detail}")]
CorruptObject {
detail: String,
},
#[error("object stream ended after {actual} of {expected} bytes")]
ObjectStreamTruncated {
expected: u64,
actual: u64,
},
#[error("unknown object type '{name}'")]
UnknownObjectType {
name: String,
},
#[error("header for {oid} too long, exceeds 32 bytes")]
ObjectHeaderTooLong {
oid: String,
},
#[error("delta chain too deep (limit {limit})")]
DeltaChainTooDeep {
limit: usize,
},
#[error("refusing to write invalid {kind} object: {}", .check.report_line())]
InvalidObject {
kind: crate::objects::ObjectKind,
check: crate::fsck_standalone::FsckError,
},
}
impl ObjectReadFailure {
pub(crate) fn try_from_object_read_error(err: Error) -> std::result::Result<Self, Error> {
match err {
Error::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(Self::Io(e)),
Error::Object(ObjectError::Zlib { detail }) => Ok(Self::Zlib { detail }),
Error::Object(ObjectError::Corrupt { detail }) => Ok(Self::CorruptObject { detail }),
Error::Object(ObjectError::StreamTruncated { expected, actual }) => {
Ok(Self::ObjectStreamTruncated { expected, actual })
}
Error::Object(ObjectError::UnknownType { name }) => {
Ok(Self::UnknownObjectType { name })
}
Error::Object(ObjectError::HeaderTooLong { oid }) => {
Ok(Self::ObjectHeaderTooLong { oid })
}
Error::Object(ObjectError::DeltaChainTooDeep { limit }) => {
Ok(Self::DeltaChainTooDeep { limit })
}
Error::Object(ObjectError::Invalid { kind, check }) => {
Ok(Self::InvalidObject { kind, check })
}
other => Err(other),
}
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Repository(#[from] RepositoryError),
#[error(transparent)]
Object(#[from] ObjectError),
#[error(transparent)]
Index(crate::index::IndexError),
#[error(transparent)]
Ref(#[from] RefError),
#[error(transparent)]
Revision(#[from] RevisionError),
#[error(transparent)]
Config(#[from] ConfigError),
#[error(transparent)]
Worktree(#[from] crate::worktree::WorktreeError),
#[error(transparent)]
Diff(#[from] DiffError),
#[error(transparent)]
Commit(crate::porcelain::commit_error::CommitError),
#[error(transparent)]
Merge(crate::porcelain::merge_error::MergeError),
#[error(transparent)]
History(crate::history::HistoryError),
#[error(transparent)]
Stash(crate::porcelain::stash_error::StashError),
#[error(transparent)]
Branch(#[from] crate::porcelain::branch_error::BranchError),
#[error(transparent)]
Tag(#[from] crate::porcelain::tag::TagError),
#[error(transparent)]
Notes(#[from] NotesError),
#[error(transparent)]
Remote(crate::remote::RemoteError),
#[error(transparent)]
Hook(crate::hooks::HookError),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error(transparent)]
LockHeld(#[from] LockHeldError),
#[error("operation cancelled")]
Cancelled,
}
impl Error {
#[must_use]
pub fn kind_name(&self) -> &'static str {
match self {
Self::Repository(e) => e.kind_name(),
Self::Object(e) => e.kind_name(),
Self::Index(e) => e.kind_name(),
Self::Ref(e) => e.kind_name(),
Self::Revision(e) => e.kind_name(),
Self::Config(..) => "config",
Self::Worktree(e) => e.kind_name(),
Self::Diff(e) => e.kind_name(),
Self::Commit(e) => e.kind_name(),
Self::Merge(e) => e.kind_name(),
Self::History(..) => "history",
Self::Stash(e) => e.kind_name(),
Self::Branch(e) => e.kind_name(),
Self::Tag(e) => e.kind_name(),
Self::Notes(e) => e.kind_name(),
Self::Remote(e) => e.kind_name(),
Self::Hook(..) => "hook",
Self::Io(..) => "io",
Self::LockHeld(..) => "lock_held",
Self::Cancelled => "cancelled",
}
}
#[must_use]
pub fn area(&self) -> &'static str {
match self {
Self::Repository(..) => "repository",
Self::Object(..) => "object",
Self::Index(..) => "index",
Self::Ref(..) => "ref",
Self::Revision(..) => "revision",
Self::Config(..) => "config",
Self::Worktree(..) => "worktree",
Self::Diff(..) => "diff",
Self::Commit(..) => "commit",
Self::Merge(..) => "merge",
Self::History(..) => "history",
Self::Stash(..) => "stash",
Self::Branch(..) => "branch",
Self::Tag(..) => "tag",
Self::Notes(..) => "notes",
Self::Remote(..) => "remote",
Self::Hook(..) => "hook",
Self::Io(..) => "io",
Self::LockHeld(..) => "lock_held",
Self::Cancelled => "cancelled",
}
}
#[must_use]
pub fn dirty_worktree(operation: WorktreeOperation, mut affected_paths: Vec<String>) -> Self {
affected_paths.sort();
affected_paths.dedup();
Self::Worktree(crate::worktree::WorktreeError::DirtyWorktree {
operation,
paths: affected_paths,
})
}
#[must_use]
pub fn would_overwrite(reason: OverwriteReason, mut affected_paths: Vec<String>) -> Self {
affected_paths.sort();
affected_paths.dedup();
let message = match reason {
OverwriteReason::LocalChanges => {
"you have uncommitted changes — commit them before switching".into()
}
OverwriteReason::Untracked => {
let first = affected_paths
.first()
.map(String::as_str)
.unwrap_or("<path>");
format!("untracked file '{first}' would be overwritten — move or remove it first")
}
};
Self::Worktree(crate::worktree::WorktreeError::WouldOverwrite {
reason,
paths: affected_paths,
message,
})
}
#[must_use]
pub fn remote_unreadable(url: impl Into<String>, reason: RemoteUnreadableReason) -> Self {
Self::Remote(crate::remote::RemoteError::unreadable(url, reason))
}
#[must_use]
pub fn is_remote_unreadable(&self) -> bool {
match self {
Self::Remote(e) => e.is_remote_unreadable(),
_ => false,
}
}
#[must_use]
pub fn lock_held(&self) -> Option<&LockHeldError> {
match self {
Self::LockHeld(err) => Some(err),
_ => None,
}
}
#[must_use]
pub fn path_io(&self) -> Option<PathIoError> {
let io = match self {
Self::Worktree(crate::worktree::WorktreeError::PathIo(io)) => io,
Self::Repository(RepositoryError::GitDirPathIo(io)) => io,
_ => return None,
};
Some(PathIoError {
operation: io.operation,
path: io.path.clone(),
source: preserve_io_error(&io.source),
})
}
#[must_use]
pub fn is_worktree_file_in_use(&self) -> bool {
matches!(
self,
Self::Worktree(crate::worktree::WorktreeError::PathIo(io))
if matches!(io.operation, PathIoOperation::Worktree(_))
&& crate::worktree::io_error::is_file_in_use(&io.source)
)
}
#[must_use]
pub fn is_git_dir_file_in_use(&self) -> bool {
match self {
Self::Repository(RepositoryError::GitDirPathIo(io)) => match io.operation {
PathIoOperation::GitDir(operation) => {
crate::git_dir::io_error::is_git_dir_transient_contention(operation, &io.source)
}
PathIoOperation::Worktree(_) => false,
},
_ => false,
}
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
match self {
Self::Cancelled => true,
Self::History(e) => e.is_cancelled(),
Self::Worktree(e) => e.is_cancelled(),
Self::Io(err)
if err.to_string() == crate::transport::stateless_http::TRANSPORT_IO_CANCELLED =>
{
true
}
_ => false,
}
}
#[must_use]
pub fn is_damaged_object(&self) -> bool {
match self {
Self::Object(
ObjectError::Zlib { .. }
| ObjectError::Corrupt { .. }
| ObjectError::CorruptLoose { .. }
| ObjectError::CorruptPacked { .. },
) => true,
Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
_ => false,
}
}
pub(crate) fn is_object_read_wrap_source(&self) -> bool {
match self {
Self::Io(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => true,
Self::Object(
ObjectError::Zlib { .. }
| ObjectError::Corrupt { .. }
| ObjectError::StreamTruncated { .. }
| ObjectError::UnknownType { .. }
| ObjectError::HeaderTooLong { .. }
| ObjectError::DeltaChainTooDeep { .. }
| ObjectError::Invalid { .. },
) => true,
_ => false,
}
}
#[must_use]
pub(crate) fn wrap_loose_read_failure(
oid: crate::objects::ObjectId,
path: std::path::PathBuf,
err: Error,
) -> Error {
if matches!(err, Self::Object(ObjectError::CorruptLoose { .. })) {
return err;
}
if !err.is_object_read_wrap_source() {
return err;
}
match ObjectReadFailure::try_from_object_read_error(err) {
Ok(source) => Self::Object(ObjectError::CorruptLoose {
oid,
path,
source: Box::new(source),
}),
Err(err) => err,
}
}
#[must_use]
pub(crate) fn wrap_packed_read_failure(
oid: crate::objects::ObjectId,
pack: std::path::PathBuf,
offset: u64,
err: Error,
) -> Error {
if matches!(err, Self::Object(ObjectError::CorruptPacked { .. })) {
return err;
}
if !err.is_object_read_wrap_source() {
return err;
}
match ObjectReadFailure::try_from_object_read_error(err) {
Ok(source) => Self::Object(ObjectError::CorruptPacked {
oid,
pack,
offset,
source: Box::new(source),
}),
Err(err) => err,
}
}
#[must_use]
pub fn invalid_path_component(
path: impl Into<String>,
reason: crate::path_validate::PathComponentError,
) -> Self {
Self::Worktree(crate::worktree::WorktreeError::InvalidPathComponent {
path: path.into(),
reason,
})
}
#[must_use]
pub fn wants_fatal_prefix(&self) -> bool {
use crate::worktree::WorktreeError;
matches!(
self,
Error::Config(_)
| Error::Worktree(
WorktreeError::Submodule(_)
| WorktreeError::Filter(_)
| WorktreeError::OutsideRepo(_)
)
| Error::Ref(RefError::Lock(_))
)
}
#[must_use]
pub fn git_stderr_message(&self) -> String {
match self {
Error::Diff(DiffError::Apply(ApplyError::CorruptPatch { .. })) => {
crate::diagnostics::error_line(&self.to_string())
}
Error::Worktree(crate::worktree::WorktreeError::WouldOverwrite { message, .. }) => {
message.clone()
}
e if e.wants_fatal_prefix() => crate::diagnostics::fatal_line(&e.to_string()),
other => other.to_string(),
}
}
}
impl From<crate::hooks::HookError> for Error {
fn from(err: crate::hooks::HookError) -> Self {
Self::Hook(err)
}
}
impl From<crate::porcelain::commit_error::CommitError> for Error {
fn from(err: crate::porcelain::commit_error::CommitError) -> Self {
Self::Commit(err)
}
}
impl From<crate::porcelain::merge_error::MergeError> for Error {
fn from(err: crate::porcelain::merge_error::MergeError) -> Self {
Self::Merge(err)
}
}
impl From<crate::history::HistoryError> for Error {
fn from(err: crate::history::HistoryError) -> Self {
Self::History(err)
}
}
impl From<crate::porcelain::stash_error::StashError> for Error {
fn from(err: crate::porcelain::stash_error::StashError) -> Self {
Self::Stash(err)
}
}
impl From<crate::remote::RemoteError> for Error {
fn from(err: crate::remote::RemoteError) -> Self {
Self::Remote(err)
}
}
impl From<crate::ident::CommitIdentityError> for Error {
fn from(err: crate::ident::CommitIdentityError) -> Self {
crate::porcelain::commit_error::CommitError::from(err).into()
}
}
impl From<crate::refs::store::RefStoreError> for Error {
fn from(err: crate::refs::store::RefStoreError) -> Self {
match err {
crate::refs::store::RefStoreError::GitDirPathIo {
path,
operation,
os_error,
} => RepositoryError::git_dir_path_io(
path,
operation,
crate::refs::store::RefStoreError::git_dir_io_source(os_error),
)
.into(),
crate::refs::store::RefStoreError::Hook(hook) => Error::Hook(hook.into_hook_error()),
other => Error::Ref(RefError::Store(other)),
}
}
}
impl From<RefLockError> for Error {
fn from(err: RefLockError) -> Self {
Self::Ref(RefError::Lock(err))
}
}
impl From<crate::reftable::ReftableError> for Error {
fn from(err: crate::reftable::ReftableError) -> Self {
Self::Ref(RefError::Reftable(err))
}
}
impl From<crate::rev_parse_error::RevParseError> for Error {
fn from(err: crate::rev_parse_error::RevParseError) -> Self {
Self::Revision(RevisionError::Parse(err))
}
}
impl From<crate::rev_list_error::RevListError> for Error {
fn from(err: crate::rev_list_error::RevListError) -> Self {
Self::Revision(RevisionError::List(err))
}
}
impl From<ApplyError> for Error {
fn from(err: ApplyError) -> Self {
match err {
ApplyError::Cancelled => Self::Cancelled,
other => Self::Diff(DiffError::Apply(other)),
}
}
}
impl From<crate::userdiff::FuncnamePatternError> for Error {
fn from(err: crate::userdiff::FuncnamePatternError) -> Self {
Self::Diff(DiffError::FuncnamePattern(err))
}
}
impl From<crate::porcelain::hunk_select::HunkSelectError> for Error {
fn from(err: crate::porcelain::hunk_select::HunkSelectError) -> Self {
Self::Diff(DiffError::HunkSelection(err))
}
}
impl From<FilterError> for Error {
fn from(err: FilterError) -> Self {
Self::Worktree(crate::worktree::WorktreeError::Filter(err))
}
}
impl From<SubmoduleError> for Error {
fn from(err: SubmoduleError) -> Self {
Self::Worktree(crate::worktree::WorktreeError::Submodule(err))
}
}
impl From<PathOutsideRepoError> for Error {
fn from(err: PathOutsideRepoError) -> Self {
Self::Worktree(crate::worktree::WorktreeError::OutsideRepo(err))
}
}
impl From<PathspecFromFileParseError> for Error {
fn from(err: PathspecFromFileParseError) -> Self {
Self::Worktree(crate::worktree::WorktreeError::PathspecFromFile(err))
}
}
impl From<crate::bitmap_walk::BitmapWalkError> for Error {
fn from(err: crate::bitmap_walk::BitmapWalkError) -> Self {
Self::Object(ObjectError::BitmapWalk(err))
}
}
impl From<crate::bitmap_walk::BitmapWalkUnsupported> for Error {
fn from(err: crate::bitmap_walk::BitmapWalkUnsupported) -> Self {
Self::Object(ObjectError::BitmapWalk(err.into()))
}
}
impl From<crate::pack_bitmap::BitmapError> for Error {
fn from(err: crate::pack_bitmap::BitmapError) -> Self {
Self::Object(ObjectError::BitmapWalk(err.into()))
}
}
impl From<crate::object_inspect::ResolveError> for Error {
fn from(err: crate::object_inspect::ResolveError) -> Self {
Self::Revision(RevisionError::Resolve(err))
}
}
impl From<MidxError> for Error {
fn from(err: MidxError) -> Self {
Self::Object(ObjectError::Midx(err))
}
}
impl From<crate::offload::OffloadError> for Error {
fn from(err: crate::offload::OffloadError) -> Self {
Self::Object(ObjectError::Offload(err))
}
}
impl From<crate::objects::TreeEntryError> for Error {
fn from(err: crate::objects::TreeEntryError) -> Self {
Self::Object(ObjectError::InvalidTreeEntry(err))
}
}
impl From<crate::ident::SignatureError> for Error {
fn from(err: crate::ident::SignatureError) -> Self {
Self::Object(ObjectError::InvalidSignature(err))
}
}
impl From<crate::config::ident_resolve::IdentityError> for Error {
fn from(err: crate::config::ident_resolve::IdentityError) -> Self {
Self::Commit(crate::porcelain::commit_error::CommitError::Identity(err))
}
}
impl From<crate::ident::AuthorArgError> for Error {
fn from(err: crate::ident::AuthorArgError) -> Self {
Self::History(crate::history::HistoryError::InvalidAuthor(err))
}
}
impl From<crate::change_id::ChangeIdError> for Error {
fn from(err: crate::change_id::ChangeIdError) -> Self {
Self::Commit(crate::porcelain::commit_error::CommitError::ChangeId(err))
}
}
impl From<crate::tree_sha256::TreeSha256ClaimError> for Error {
fn from(err: crate::tree_sha256::TreeSha256ClaimError) -> Self {
Self::Tag(crate::porcelain::tag::TagError::TreeSha256Claim(err))
}
}
impl From<Cancelled> for Error {
fn from(_: Cancelled) -> Self {
Self::Cancelled
}
}
impl From<crate::worktree::LinkedWorktreeError> for Error {
fn from(value: crate::worktree::LinkedWorktreeError) -> Self {
Self::Worktree(value.into())
}
}
impl From<PathIoError> for Error {
fn from(value: PathIoError) -> Self {
match value.operation {
PathIoOperation::Worktree(_) => {
Self::Worktree(crate::worktree::WorktreeError::PathIo(value))
}
PathIoOperation::GitDir(_) => Self::Repository(RepositoryError::GitDirPathIo(value)),
}
}
}
impl From<crate::lockfile::LockError> for Error {
#[cold]
fn from(err: crate::lockfile::LockError) -> Self {
use crate::lockfile::{LockError, LockHolder};
match err {
LockError::Held { path } => Self::LockHeld(LockHeldError {
holder: LockHolder::read(&path),
path,
}),
LockError::Io { source, .. } => Self::Io(source),
}
}
}
impl From<crate::serve::ServeError> for Error {
fn from(err: crate::serve::ServeError) -> Self {
Self::Remote(crate::remote::RemoteError::Serve(err))
}
}
impl From<crate::snapshot_checkout::CheckoutError> for Error {
fn from(err: crate::snapshot_checkout::CheckoutError) -> Self {
Self::Remote(crate::remote::RemoteError::Snapshot(err))
}
}
impl From<crate::clone::CloneError> for Error {
fn from(err: crate::clone::CloneError) -> Self {
Self::Remote(crate::remote::RemoteError::Clone(Box::new(err)))
}
}
impl From<crate::porcelain::pull::PullError> for Error {
fn from(err: crate::porcelain::pull::PullError) -> Self {
Self::Merge(crate::porcelain::merge_error::MergeError::Pull(err))
}
}
impl From<crate::remote::push_plan::PushPlanError> for Error {
fn from(err: crate::remote::push_plan::PushPlanError) -> Self {
Self::Remote(crate::remote::RemoteError::PushPlan(err))
}
}
impl From<crate::history::RebaseSessionError> for Error {
fn from(err: crate::history::RebaseSessionError) -> Self {
match err {
crate::history::RebaseSessionError::NothingToCommit => {
Self::Commit(crate::porcelain::commit_error::CommitError::NothingToCommit)
}
other => Self::History(crate::history::HistoryError::RebaseSession(Box::new(other))),
}
}
}
impl From<crate::porcelain::stash_error::StashPushValidationError> for Error {
fn from(err: crate::porcelain::stash_error::StashPushValidationError) -> Self {
Self::Stash(crate::porcelain::stash_error::StashError::PushValidation(
err,
))
}
}
impl From<crate::bundle::BundleError> for Error {
fn from(err: crate::bundle::BundleError) -> Self {
use crate::bundle::BundleError;
match err {
BundleError::Cancelled => Self::Cancelled,
BundleError::ObjectNotFound { name } => Self::Object(ObjectError::NotFound { name }),
other => Self::Remote(crate::remote::RemoteError::Bundle(other)),
}
}
}
impl From<crate::fetch_request::FetchRefspecError> for Error {
fn from(e: crate::fetch_request::FetchRefspecError) -> Self {
Self::Remote(crate::remote::RemoteError::FetchRefspec(e))
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(feature = "serde-models")]
impl serde::Serialize for Error {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use crate::worktree::WorktreeError;
use serde::ser::SerializeStruct;
match self {
Self::LockHeld(lock) => {
let mut out = serializer.serialize_struct("Error", 5)?;
out.serialize_field("kind", self.kind_name())?;
out.serialize_field("area", self.area())?;
out.serialize_field("message", &self.to_string())?;
out.serialize_field(
"path",
&crate::git_path::user_display_path(lock.path.as_path()),
)?;
if let Some(holder) = lock.holder {
out.serialize_field(
"holder",
&LockHolderSerde {
pid: holder.pid,
running: holder.running,
},
)?;
}
out.end()
}
Self::Worktree(WorktreeError::WouldOverwrite { reason, paths, .. }) => {
let mut out = serializer.serialize_struct("Error", 5)?;
out.serialize_field("kind", self.kind_name())?;
out.serialize_field("area", self.area())?;
out.serialize_field("message", &self.to_string())?;
out.serialize_field("reason", &reason.to_string())?;
out.serialize_field("paths", paths)?;
out.end()
}
Self::Worktree(WorktreeError::DirtyWorktree { operation, paths }) => {
let mut out = serializer.serialize_struct("Error", 5)?;
out.serialize_field("kind", self.kind_name())?;
out.serialize_field("area", self.area())?;
out.serialize_field("message", &self.to_string())?;
out.serialize_field("operation", &operation.to_string())?;
out.serialize_field("paths", paths)?;
out.end()
}
Self::Worktree(WorktreeError::UnmergedConflictMarkers { paths }) => {
let mut out = serializer.serialize_struct("Error", 4)?;
out.serialize_field("kind", self.kind_name())?;
out.serialize_field("area", self.area())?;
out.serialize_field("message", &self.to_string())?;
out.serialize_field("paths", paths)?;
out.end()
}
Self::Stash(stash) => stash.serialize(serializer),
_ => {
let mut out = serializer.serialize_struct("Error", 3)?;
out.serialize_field("kind", self.kind_name())?;
out.serialize_field("area", self.area())?;
out.serialize_field("message", &self.to_string())?;
out.end()
}
}
}
}
#[cfg(test)]
mod object_read_failure_tests {
use super::{Error, ObjectError, ObjectReadFailure};
#[test]
fn try_from_object_read_error_rejects_unrelated_umbrella_variants() {
assert!(matches!(
ObjectReadFailure::try_from_object_read_error(Error::Cancelled),
Err(Error::Cancelled)
));
}
#[test]
fn try_from_object_read_error_maps_decode_variants() {
assert!(matches!(
ObjectReadFailure::try_from_object_read_error(Error::Object(ObjectError::Zlib {
detail: "bad".into()
})),
Ok(ObjectReadFailure::Zlib { .. })
));
}
}
#[cfg(test)]
mod umbrella_area_tests {
use super::{
ConfigError, DiffError, Error, ErrorSummary, LockHeldError, NotesError, ObjectError,
RefError, RepositoryError, RevisionError,
};
use crate::history::HistoryError;
use crate::hooks::{HookError, HookOutput};
use crate::index::IndexError;
use crate::porcelain::branch_error::BranchError;
use crate::porcelain::commit_error::CommitError;
use crate::porcelain::merge_error::MergeError;
use crate::porcelain::stash_error::StashError;
use crate::porcelain::tag::TagError;
use crate::remote::RemoteError;
use crate::worktree::WorktreeError;
fn area_by_variant(err: &Error) -> &'static str {
match err {
Error::Repository(_) => "repository",
Error::Object(_) => "object",
Error::Index(_) => "index",
Error::Ref(_) => "ref",
Error::Revision(_) => "revision",
Error::Config(_) => "config",
Error::Worktree(_) => "worktree",
Error::Diff(_) => "diff",
Error::Commit(_) => "commit",
Error::Merge(_) => "merge",
Error::History(_) => "history",
Error::Stash(_) => "stash",
Error::Branch(_) => "branch",
Error::Tag(_) => "tag",
Error::Notes(_) => "notes",
Error::Remote(_) => "remote",
Error::Hook(_) => "hook",
Error::Io(_) => "io",
Error::LockHeld(_) => "lock_held",
Error::Cancelled => "cancelled",
}
}
const AREAS: &[&str] = &[
"repository",
"object",
"index",
"ref",
"revision",
"config",
"worktree",
"diff",
"commit",
"merge",
"history",
"stash",
"branch",
"tag",
"notes",
"remote",
"hook",
"io",
"lock_held",
"cancelled",
];
fn one_error_per_area() -> Vec<Error> {
vec![
Error::Repository(RepositoryError::RequiresWorkTree),
Error::Object(ObjectError::InvalidId {
input: "xyz".into(),
}),
Error::Index(IndexError::CacheTreeCorrupt),
Error::Ref(RefError::UnbornHead),
Error::Revision(RevisionError::NotFound {
spec: "nope".into(),
}),
Error::Config(ConfigError::ConfigCacheLockPoisoned),
Error::Worktree(WorktreeError::RemovePathsRequired),
Error::Diff(DiffError::BlameWorktreeBareRepository),
Error::Commit(CommitError::EmptyCommitMessage),
Error::Merge(MergeError::NotFastForward),
Error::History(HistoryError::EmptyMessage),
Error::Stash(StashError::NoInitialCommit),
Error::Branch(BranchError::NoPreviousBranch),
Error::Tag(TagError::EmptyMessage),
Error::Notes(NotesError::AlreadyExists {
object: crate::objects::ObjectId::zero(),
}),
Error::Remote(RemoteError::HttpUnavailable),
Error::Hook(HookError::Failed {
hook_name: "pre-commit".into(),
status: 1,
output: HookOutput::default(),
}),
Error::Io(std::io::Error::other("disk")),
Error::LockHeld(LockHeldError {
path: ".git/index.lock".into(),
holder: None,
}),
Error::Cancelled,
]
}
#[test]
fn umbrella_error_has_one_variant_per_area() {
let samples = one_error_per_area();
assert_eq!(samples.len(), AREAS.len());
let mut seen = std::collections::HashSet::new();
for (err, expected) in samples.iter().zip(AREAS) {
assert_eq!(area_by_variant(err), *expected);
assert_eq!(err.area(), *expected, "{err:?}");
assert!(seen.insert(err.area()), "area {expected} listed twice");
assert!(!err.kind_name().is_empty());
}
}
#[test]
fn area_errors_convert_into_their_umbrella_variant() {
let cases: Vec<(Error, &str)> = vec![
(RepositoryError::RequiresWorkTree.into(), "repository"),
(RefError::UnbornHead.into(), "ref"),
(
RevisionError::NotFound { spec: "x".into() }.into(),
"revision",
),
(CommitError::EmptyCommitMessage.into(), "commit"),
(MergeError::NotFastForward.into(), "merge"),
(HistoryError::EmptyMessage.into(), "history"),
(StashError::NoInitialCommit.into(), "stash"),
(BranchError::NoPreviousBranch.into(), "branch"),
(TagError::EmptyMessage.into(), "tag"),
(RemoteError::HttpUnavailable.into(), "remote"),
(IndexError::CacheTreeCorrupt.into(), "index"),
(WorktreeError::RemovePathsRequired.into(), "worktree"),
];
for (err, area) in cases {
assert_eq!(err.area(), area, "{err:?}");
}
}
#[test]
fn error_summary_keeps_kind_area_message_and_cancellation() {
let summary = ErrorSummary::from(&Error::Ref(RefError::UnbornHead));
assert_eq!(summary.kind(), Error::Ref(RefError::UnbornHead).kind_name());
assert_eq!(summary.area(), "ref");
assert_eq!(
summary.message(),
Error::Ref(RefError::UnbornHead).to_string()
);
assert_eq!(summary.to_string(), summary.message());
assert!(!summary.is_cancelled());
let cancelled = ErrorSummary::from(Error::Cancelled);
assert!(cancelled.is_cancelled());
assert_eq!(cancelled.kind(), "cancelled");
assert_eq!(cancelled.area(), "cancelled");
assert_eq!(cancelled.clone(), cancelled);
assert_eq!(
std::mem::size_of::<ErrorSummary>(),
std::mem::size_of::<usize>()
);
}
}
#[cfg(feature = "serde-models")]
#[derive(serde::Serialize)]
struct LockHolderSerde {
pid: u64,
running: bool,
}