use std::path::{Path, PathBuf};
use crate::error::{GitDirPathOperation, LockHeldError, PathIoError, PathIoOperation};
use crate::objects::HashAlgo;
use thiserror::Error;
pub type IndexResult<T> = std::result::Result<T, IndexError>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IndexCorruptReason {
BadSignature,
UnsupportedVersion {
version: u32,
},
Truncated,
ChecksumMismatch {
algo: HashAlgo,
},
BadEntry,
FileTooShortForHeader,
CannotReadVersion,
CannotReadEntryCount,
ParallelLoadMissingEoie,
ExtensionOverrunsBody,
ExtensionTruncatedSig,
ExtensionTruncatedSize,
JunkAfterExtensions,
UnsupportedExtension {
sig: u32,
},
EntryRegionStartsPastEnd,
EntryCountMismatch {
declared: u32,
max_fit: usize,
remaining: usize,
},
EntrySizeOverflow,
EntryOverrunsBody,
EntryTooShort,
TruncatedU32,
TruncatedFlags,
TruncatedExtendedFlags,
V4PathMissingNul,
PathMissingNulTerminator,
TruncatedIndexEntry,
IeotBlockRangeOutOfBounds,
IeotEntryCountOverflow,
IeotBlockOffsetPastBody {
block: usize,
offset: usize,
},
IeotBlockEntryOverruns {
block: usize,
pos: usize,
},
EmptyIeotTable,
IeotEntryCountMismatch {
expected: u32,
got: usize,
},
CacheTreeUpdateFailed,
WriteTreeMissingCacheTree,
WriteTreeCacheTreeRootMissingOid,
WriteTreeInvalidPrefix {
prefix: String,
},
WriteTreeCacheTreeChildMissing,
WriteTreeExpectedTree {
oid: crate::objects::ObjectId,
},
WriteTreeMissingIndexEntry,
ResolveUndoTruncatedPath,
ResolveUndoTruncatedMode,
ResolveUndoInvalidModeUtf8,
ResolveUndoInvalidMode {
mode: String,
},
ResolveUndoInvalidPathUtf8,
ResolveUndoCorrupt,
ResolveUndoTruncatedOid,
UntrackedCacheTruncated,
UntrackedCacheInvalidVarint,
UntrackedCacheMissingNul,
UntrackedCacheInvalidUtf8,
UntrackedCacheDirCorrupt,
UntrackedCacheNoRoot,
SplitIndexCorrupt,
SplitIndexTooShort,
ChecksumWorkerPanicked,
MissingIndexEntryDuringTreeWalk,
MissingIndexEntryDuringHardReset,
HardResetCacheTreeEntryCountMismatch,
HardResetCacheTreeOutOfSync,
HardResetCacheTreeTypeMismatch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexCorrupt {
pub path: Option<PathBuf>,
pub offset: Option<usize>,
pub reason: IndexCorruptReason,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IndexChmodReason {
UnmergedPath,
NotChmodEligible,
InvalidTargetMode {
mode: u32,
},
}
impl IndexCorrupt {
#[must_use]
pub fn new(reason: IndexCorruptReason) -> Self {
Self {
path: None,
offset: None,
reason,
}
}
#[must_use]
pub fn at_offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
#[must_use]
pub fn at_path(mut self, path: impl Into<PathBuf>) -> Self {
self.path = Some(path.into());
self
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum IndexError {
#[error("index error: {detail}")]
Corrupt {
corrupt: IndexCorrupt,
detail: String,
},
#[error("index contains unmerged entries")]
Unmerged {
paths: Vec<String>,
},
#[error(
"index path prefix conflict between '{}' and '{}'",
directory.display(),
file.display()
)]
PathPrefixConflict {
directory: PathBuf,
file: PathBuf,
},
#[error("index fsmonitor extension payload is truncated")]
FsmonitorExtensionTruncated,
#[error("index fsmonitor extension has unsupported header version {0}")]
FsmonitorExtensionBadVersion(u32),
#[error("index fsmonitor extension EWAH bitmap is invalid")]
FsmonitorExtensionEwahInvalid,
#[error("corrupted cache-tree has entries not present in index")]
CacheTreeCorrupt,
#[error(transparent)]
LockHeld(#[from] LockHeldError),
#[error(transparent)]
PathIo(#[from] PathIoError),
#[error("cannot change mode of index path '{path}': {reason:?}")]
Chmod {
path: String,
reason: IndexChmodReason,
},
#[error("{0}")]
Nested(#[from] Box<crate::error::Error>),
}
impl IndexError {
#[must_use]
pub fn kind_name(&self) -> &'static str {
match self {
Self::Corrupt { .. } => "index_error",
Self::Unmerged { .. } => "index_unmerged",
Self::PathPrefixConflict { .. } => "index_path_prefix_conflict",
Self::FsmonitorExtensionTruncated => "index_fsmonitor_extension_truncated",
Self::FsmonitorExtensionBadVersion(_) => "index_fsmonitor_extension_bad_version",
Self::FsmonitorExtensionEwahInvalid => "index_fsmonitor_extension_ewah_invalid",
Self::CacheTreeCorrupt => "cache_tree_corrupt",
Self::LockHeld(_) => "lock_held",
Self::PathIo(_) => "git_dir_path_io",
Self::Chmod { .. } => "message",
Self::Nested(inner) => inner.kind_name(),
}
}
pub(crate) fn corrupt(corrupt: IndexCorrupt) -> Self {
let detail = corrupt_detail(&corrupt);
Self::Corrupt { corrupt, detail }
}
pub(crate) fn corrupt_at(
path: Option<&Path>,
offset: Option<usize>,
reason: IndexCorruptReason,
) -> Self {
let mut corrupt = IndexCorrupt::new(reason);
if let Some(p) = path {
corrupt = corrupt.at_path(p);
}
if let Some(o) = offset {
corrupt = corrupt.at_offset(o);
}
Self::corrupt(corrupt)
}
#[must_use]
pub fn unmerged() -> Self {
Self::Unmerged { paths: Vec::new() }
}
}
fn corrupt_detail(corrupt: &IndexCorrupt) -> String {
match corrupt.reason {
IndexCorruptReason::BadSignature => "bad magic: expected DIRC".to_owned(),
IndexCorruptReason::UnsupportedVersion { version } => {
format!("unsupported index version {version}")
}
IndexCorruptReason::Truncated => "truncated".to_owned(),
IndexCorruptReason::ChecksumMismatch { algo } => {
format!("{} checksum mismatch", algo.name().to_uppercase())
}
IndexCorruptReason::BadEntry => "bad index entry".to_owned(),
IndexCorruptReason::FileTooShortForHeader => {
"file too short for index header and checksum".to_owned()
}
IndexCorruptReason::CannotReadVersion => "cannot read version".to_owned(),
IndexCorruptReason::CannotReadEntryCount => "cannot read entry count".to_owned(),
IndexCorruptReason::ParallelLoadMissingEoie => {
"parallel index load missing EOIE offset".to_owned()
}
IndexCorruptReason::ExtensionOverrunsBody => "extension overruns index body".to_owned(),
IndexCorruptReason::ExtensionTruncatedSig => "truncated extension sig".to_owned(),
IndexCorruptReason::ExtensionTruncatedSize => "truncated extension size".to_owned(),
IndexCorruptReason::JunkAfterExtensions => "junk after index extensions".to_owned(),
IndexCorruptReason::UnsupportedExtension { sig } => {
format!("index uses unsupported extension {sig:#010x}")
}
IndexCorruptReason::EntryRegionStartsPastEnd => {
"index entry region starts past end of file".to_owned()
}
IndexCorruptReason::EntryCountMismatch {
declared,
max_fit,
remaining,
} => {
format!("index declares {declared} entries but only {max_fit} fit in {remaining} bytes")
}
IndexCorruptReason::EntrySizeOverflow => "index entry size overflow".to_owned(),
IndexCorruptReason::EntryOverrunsBody => "index entry overruns index body".to_owned(),
IndexCorruptReason::EntryTooShort => "entry too short".to_owned(),
IndexCorruptReason::TruncatedU32 => "truncated u32".to_owned(),
IndexCorruptReason::TruncatedFlags => "truncated flags".to_owned(),
IndexCorruptReason::TruncatedExtendedFlags => "truncated extended flags".to_owned(),
IndexCorruptReason::V4PathMissingNul => "v4 entry path missing NUL".to_owned(),
IndexCorruptReason::PathMissingNulTerminator => {
"entry path missing NUL terminator".to_owned()
}
IndexCorruptReason::TruncatedIndexEntry => "truncated index entry".to_owned(),
IndexCorruptReason::IeotBlockRangeOutOfBounds => {
"IEOT block range out of bounds".to_owned()
}
IndexCorruptReason::IeotEntryCountOverflow => "IEOT entry count overflow".to_owned(),
IndexCorruptReason::IeotBlockOffsetPastBody { block, offset } => {
format!("IEOT block {block} offset {offset} past index body")
}
IndexCorruptReason::IeotBlockEntryOverruns { block, pos } => {
format!("IEOT block {block} entry overruns index body at {pos}")
}
IndexCorruptReason::EmptyIeotTable => "empty IEOT table".to_owned(),
IndexCorruptReason::IeotEntryCountMismatch { expected, got } => {
format!("IEOT entry count mismatch: expected {expected}, got {got}")
}
IndexCorruptReason::CacheTreeUpdateFailed => "cache-tree update failed".to_owned(),
IndexCorruptReason::WriteTreeMissingCacheTree => {
"write-tree: missing cache-tree after update".to_owned()
}
IndexCorruptReason::WriteTreeCacheTreeRootMissingOid => {
"write-tree: cache-tree root has no oid".to_owned()
}
IndexCorruptReason::WriteTreeInvalidPrefix { ref prefix } => {
format!("write-tree: invalid prefix '{prefix}'")
}
IndexCorruptReason::WriteTreeCacheTreeChildMissing => {
"cache-tree child missing oid".to_owned()
}
IndexCorruptReason::WriteTreeExpectedTree { oid } => {
format!("expected tree at {oid}")
}
IndexCorruptReason::WriteTreeMissingIndexEntry => {
"missing index entry during tree walk".to_owned()
}
IndexCorruptReason::ResolveUndoTruncatedPath => "truncated resolve-undo path".to_owned(),
IndexCorruptReason::ResolveUndoTruncatedMode => "truncated resolve-undo mode".to_owned(),
IndexCorruptReason::ResolveUndoInvalidModeUtf8 => {
"invalid UTF-8 in resolve-undo mode".to_owned()
}
IndexCorruptReason::ResolveUndoInvalidMode { ref mode } => {
format!("invalid resolve-undo mode '{mode}'")
}
IndexCorruptReason::ResolveUndoInvalidPathUtf8 => {
"invalid UTF-8 in resolve-undo path".to_owned()
}
IndexCorruptReason::ResolveUndoCorrupt => "corrupt resolve-undo extension".to_owned(),
IndexCorruptReason::ResolveUndoTruncatedOid => {
"truncated resolve-undo object id".to_owned()
}
IndexCorruptReason::UntrackedCacheTruncated => {
"untracked-cache extension truncated".to_owned()
}
IndexCorruptReason::UntrackedCacheInvalidVarint => {
"untracked-cache invalid varint".to_owned()
}
IndexCorruptReason::UntrackedCacheMissingNul => {
"untracked-cache payload missing NUL terminator".to_owned()
}
IndexCorruptReason::UntrackedCacheInvalidUtf8 => "untracked-cache invalid UTF-8".to_owned(),
IndexCorruptReason::UntrackedCacheDirCorrupt => {
"untracked-cache directory tree corrupt".to_owned()
}
IndexCorruptReason::UntrackedCacheNoRoot => "no uc root".to_owned(),
IndexCorruptReason::SplitIndexCorrupt => "split index corrupt".to_owned(),
IndexCorruptReason::SplitIndexTooShort => "index too short".to_owned(),
IndexCorruptReason::ChecksumWorkerPanicked => {
"index checksum worker thread panicked".to_owned()
}
IndexCorruptReason::MissingIndexEntryDuringTreeWalk => {
"missing index entry during tree walk".to_owned()
}
IndexCorruptReason::MissingIndexEntryDuringHardReset => {
"missing index entry during hard reset align".to_owned()
}
IndexCorruptReason::HardResetCacheTreeEntryCountMismatch => {
"hard reset cache-tree entry count does not match index".to_owned()
}
IndexCorruptReason::HardResetCacheTreeOutOfSync => {
"hard reset cache-tree rebuild: index out of sync with target tree".to_owned()
}
IndexCorruptReason::HardResetCacheTreeTypeMismatch => {
"hard reset cache-tree rebuild: tree/index type mismatch".to_owned()
}
}
}
impl From<crate::lockfile::LockError> for IndexError {
fn from(err: crate::lockfile::LockError) -> Self {
use crate::lockfile::LockError;
match err {
LockError::Held { path } => Self::LockHeld(LockHeldError {
holder: crate::lockfile::LockHolder::read(&path),
path,
}),
LockError::Io { path, source } => Self::PathIo(PathIoError {
operation: PathIoOperation::GitDir(GitDirPathOperation::WriteIndex),
path: Some(path),
source,
}),
}
}
}
impl From<crate::error::ConfigError> for IndexError {
fn from(err: crate::error::ConfigError) -> Self {
Self::from(crate::error::Error::Config(err))
}
}
impl From<IndexError> for crate::error::Error {
fn from(err: IndexError) -> Self {
match err {
IndexError::LockHeld(h) => Self::LockHeld(h),
IndexError::PathIo(p) => p.into(),
IndexError::Nested(inner) => *inner,
IndexError::Unmerged { .. } => Self::Index(err),
IndexError::PathPrefixConflict { .. } => Self::Index(err),
IndexError::FsmonitorExtensionTruncated => Self::Index(err),
IndexError::FsmonitorExtensionBadVersion(_) => Self::Index(err),
IndexError::FsmonitorExtensionEwahInvalid => Self::Index(err),
IndexError::CacheTreeCorrupt => Self::Index(err),
IndexError::Corrupt { .. } | IndexError::Chmod { .. } => Self::Index(err),
}
}
}
impl From<std::io::Error> for IndexError {
fn from(source: std::io::Error) -> Self {
Self::PathIo(PathIoError {
operation: crate::error::PathIoOperation::GitDir(
crate::error::GitDirPathOperation::WriteIndex,
),
path: None,
source,
})
}
}
impl From<crate::error::Error> for IndexError {
#[allow(deprecated)]
fn from(err: crate::error::Error) -> Self {
match err {
crate::error::Error::IndexError(detail) => Self::Corrupt {
corrupt: IndexCorrupt::new(IndexCorruptReason::Truncated),
detail,
},
crate::error::Error::IndexUnmerged => Self::unmerged(),
crate::error::Error::IndexPathPrefixConflict { directory, file } => {
Self::PathPrefixConflict { directory, file }
}
crate::error::Error::IndexFsmonitorExtensionTruncated => {
Self::FsmonitorExtensionTruncated
}
crate::error::Error::IndexFsmonitorExtensionBadVersion(v) => {
Self::FsmonitorExtensionBadVersion(v)
}
crate::error::Error::IndexFsmonitorExtensionEwahInvalid => {
Self::FsmonitorExtensionEwahInvalid
}
crate::error::Error::CacheTreeCorrupt => Self::CacheTreeCorrupt,
crate::error::Error::Index(index) => index,
crate::error::Error::LockHeld(h) => Self::LockHeld(h),
crate::error::Error::Io(source) => Self::PathIo(PathIoError {
operation: PathIoOperation::GitDir(GitDirPathOperation::WriteIndex),
path: None,
source,
}),
crate::error::Error::Repository(crate::repo::RepositoryError::GitDirPathIo(source)) => {
Self::PathIo(source)
}
crate::error::Error::WorktreePathIo {
operation,
path,
source,
} => Self::PathIo(PathIoError {
operation: PathIoOperation::Worktree(operation),
path: Some(PathBuf::from(path)),
source,
}),
other => IndexError::Nested(Box::new(other)),
}
}
}