Skip to main content

grit_lib/index/
error.rs

1//! Typed failures for index read, write, extensions, and write-tree.
2
3use std::path::{Path, PathBuf};
4
5use crate::error::{GitDirPathOperation, LockHeldError, PathIoError, PathIoOperation};
6use crate::objects::HashAlgo;
7use thiserror::Error;
8
9/// Why index bytes or an extension payload could not be parsed.
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum IndexCorruptReason {
13    /// Header magic is not `DIRC`.
14    BadSignature,
15    /// On-disk version is not supported (2, 3, or 4).
16    UnsupportedVersion {
17        /// Version field read from the header.
18        version: u32,
19    },
20    /// Unexpected end of file while reading required fields.
21    Truncated,
22    /// Trailing checksum does not match file contents.
23    ChecksumMismatch {
24        /// Hash algorithm used for the trailer.
25        algo: HashAlgo,
26    },
27    /// A fixed field or entry could not be decoded.
28    BadEntry,
29    /// File is shorter than header plus checksum.
30    FileTooShortForHeader,
31    /// Version field could not be read.
32    CannotReadVersion,
33    /// Entry count field could not be read.
34    CannotReadEntryCount,
35    /// Parallel load expected EOIE but none was present.
36    ParallelLoadMissingEoie,
37    /// Extension length extends past the index body.
38    ExtensionOverrunsBody,
39    /// Extension signature truncated.
40    ExtensionTruncatedSig,
41    /// Extension size field truncated.
42    ExtensionTruncatedSize,
43    /// Bytes remain after the extension region.
44    JunkAfterExtensions,
45    /// Extension fourcc is unsupported (lowercase signature).
46    UnsupportedExtension {
47        /// Extension signature dword.
48        sig: u32,
49    },
50    /// Entry region starts beyond the file end.
51    EntryRegionStartsPastEnd,
52    /// Declared entry count exceeds what fits in the file.
53    EntryCountMismatch {
54        /// Count from the header.
55        declared: u32,
56        /// Maximum entries that fit in remaining bytes.
57        max_fit: usize,
58        /// Remaining byte length for entries.
59        remaining: usize,
60    },
61    /// Entry consumed size overflowed `usize`.
62    EntrySizeOverflow,
63    /// An index entry extends past the body.
64    EntryOverrunsBody,
65    /// Entry fixed portion is too short.
66    EntryTooShort,
67    /// Truncated u32 while reading an entry.
68    TruncatedU32,
69    /// Truncated standard flags.
70    TruncatedFlags,
71    /// Truncated extended flags.
72    TruncatedExtendedFlags,
73    /// Version 4 entry path has no NUL delimiter.
74    V4PathMissingNul,
75    /// Entry path has no NUL terminator.
76    PathMissingNulTerminator,
77    /// Index entry truncated mid-record.
78    TruncatedIndexEntry,
79    /// IEOT block slice is out of range.
80    IeotBlockRangeOutOfBounds,
81    /// IEOT per-block entry count overflow.
82    IeotEntryCountOverflow,
83    /// IEOT block offset is past the index body.
84    IeotBlockOffsetPastBody {
85        /// Block index in the IEOT table.
86        block: usize,
87        /// Byte offset recorded for the block.
88        offset: usize,
89    },
90    /// IEOT block entry overruns the body.
91    IeotBlockEntryOverruns {
92        /// Block index in the IEOT table.
93        block: usize,
94        /// Position within the index body.
95        pos: usize,
96    },
97    /// IEOT table has no blocks.
98    EmptyIeotTable,
99    /// Parallel IEOT load entry count does not match header.
100    IeotEntryCountMismatch {
101        /// Count from the index header.
102        expected: u32,
103        /// Entries assembled from IEOT blocks.
104        got: usize,
105    },
106    /// Cache-tree update during write-tree failed.
107    CacheTreeUpdateFailed,
108    /// write-tree: cache-tree missing after update.
109    WriteTreeMissingCacheTree,
110    /// write-tree: cache-tree root has no oid.
111    WriteTreeCacheTreeRootMissingOid,
112    /// write-tree: invalid path prefix.
113    WriteTreeInvalidPrefix {
114        /// Prefix argument that failed validation.
115        prefix: String,
116    },
117    /// write-tree: cache-tree child metadata missing.
118    WriteTreeCacheTreeChildMissing,
119    /// write-tree: expected a tree object at an oid.
120    WriteTreeExpectedTree {
121        /// Object id that was not a tree.
122        oid: crate::objects::ObjectId,
123    },
124    /// write-tree: missing index entry during traversal.
125    WriteTreeMissingIndexEntry,
126    /// Resolve-undo extension payload truncated (path).
127    ResolveUndoTruncatedPath,
128    /// Resolve-undo mode field truncated.
129    ResolveUndoTruncatedMode,
130    /// Resolve-undo mode is not valid UTF-8.
131    ResolveUndoInvalidModeUtf8,
132    /// Resolve-undo mode is not a valid octal file mode.
133    ResolveUndoInvalidMode {
134        /// Raw mode bytes as lossy UTF-8 for display.
135        mode: String,
136    },
137    /// Resolve-undo path is not valid UTF-8.
138    ResolveUndoInvalidPathUtf8,
139    /// Resolve-undo parse failed for another reason.
140    ResolveUndoCorrupt,
141    /// Resolve-undo object id field truncated.
142    ResolveUndoTruncatedOid,
143    /// Untracked-cache (`UNTR`) payload ends before required fields.
144    UntrackedCacheTruncated,
145    /// Untracked-cache varint could not be decoded.
146    UntrackedCacheInvalidVarint,
147    /// Untracked-cache payload missing trailing NUL.
148    UntrackedCacheMissingNul,
149    /// Untracked-cache string field is not valid UTF-8.
150    UntrackedCacheInvalidUtf8,
151    /// Untracked-cache directory tree could not be parsed.
152    UntrackedCacheDirCorrupt,
153    /// Untracked-cache extension has no root directory.
154    UntrackedCacheNoRoot,
155    /// Split index link or merge failure (detail in message via split variant).
156    SplitIndexCorrupt,
157    /// Index file shorter than minimum for split index.
158    SplitIndexTooShort,
159    /// Checksum worker thread panicked during parallel verify.
160    ChecksumWorkerPanicked,
161    /// Missing index entry during diff tree walk.
162    MissingIndexEntryDuringTreeWalk,
163    /// Missing index entry during hard reset alignment.
164    MissingIndexEntryDuringHardReset,
165    /// Hard-reset cache-tree rebuild: header entry count mismatch.
166    HardResetCacheTreeEntryCountMismatch,
167    /// Hard-reset cache-tree rebuild: index and tree out of sync.
168    HardResetCacheTreeOutOfSync,
169    /// Hard-reset cache-tree rebuild: tree vs index entry kind mismatch.
170    HardResetCacheTreeTypeMismatch,
171}
172
173/// Index file or extension corruption at an optional byte offset.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct IndexCorrupt {
176    /// Repository-relative path when the failure came from a file on disk.
177    pub path: Option<PathBuf>,
178    /// Byte offset into the index file when known.
179    pub offset: Option<usize>,
180    /// Structured reason for the failure.
181    pub reason: IndexCorruptReason,
182}
183
184/// Why [`IndexError::Chmod`] rejected a mode change.
185#[derive(Debug, Clone, PartialEq, Eq, Hash)]
186#[non_exhaustive]
187pub enum IndexChmodReason {
188    /// Conflict stages exist for the path.
189    UnmergedPath,
190    /// Entry is not a regular file (symlink, gitlink, directory, …).
191    NotChmodEligible,
192    /// Target mode is not `100644` or `100755`.
193    InvalidTargetMode {
194        /// Mode the caller requested.
195        mode: u32,
196    },
197}
198
199impl IndexCorrupt {
200    /// Build a corruption error without path or offset.
201    #[must_use]
202    pub fn new(reason: IndexCorruptReason) -> Self {
203        Self {
204            path: None,
205            offset: None,
206            reason,
207        }
208    }
209
210    /// Attach a byte offset.
211    #[must_use]
212    pub fn at_offset(mut self, offset: usize) -> Self {
213        self.offset = Some(offset);
214        self
215    }
216
217    /// Attach the index path being read or written.
218    #[must_use]
219    pub fn at_path(mut self, path: impl Into<PathBuf>) -> Self {
220        self.path = Some(path.into());
221        self
222    }
223}
224
225/// Failures while reading, writing, or deriving trees from the Git index.
226#[derive(Debug, Error)]
227#[non_exhaustive]
228pub enum IndexError {
229    /// On-disk index bytes or an extension could not be parsed.
230    #[error("index error: {detail}")]
231    Corrupt {
232        /// Structured corruption site.
233        corrupt: IndexCorrupt,
234        /// Human detail matching historical `Error::IndexError` messages where needed.
235        detail: String,
236    },
237
238    /// Stage 1/2/3 entries are present; a stage-0 tree cannot be built.
239    #[error("index contains unmerged entries")]
240    Unmerged {
241        /// Repository-relative paths with conflict stages (may be empty when unknown).
242        paths: Vec<String>,
243    },
244
245    /// A file path is a prefix of another index path at the same tree level.
246    #[error(
247        "index path prefix conflict between '{}' and '{}'",
248        directory.display(),
249        file.display()
250    )]
251    PathPrefixConflict {
252        /// Shorter path (treated as the ambiguous directory prefix).
253        directory: PathBuf,
254        /// Longer path that extends the prefix with an additional component.
255        file: PathBuf,
256    },
257
258    /// The `FSMN` index extension ends before its header, token, or EWAH payload.
259    #[error("index fsmonitor extension payload is truncated")]
260    FsmonitorExtensionTruncated,
261
262    /// The `FSMN` extension header version is not supported.
263    #[error("index fsmonitor extension has unsupported header version {0}")]
264    FsmonitorExtensionBadVersion(u32),
265
266    /// The EWAH bitmap embedded in `FSMN` could not be decoded.
267    #[error("index fsmonitor extension EWAH bitmap is invalid")]
268    FsmonitorExtensionEwahInvalid,
269
270    /// The cache-tree extension references more entries than the index contains.
271    #[error("corrupted cache-tree has entries not present in index")]
272    CacheTreeCorrupt,
273
274    /// `.git/index.lock` (or `GIT_INDEX_FILE.lock`) is held by another process.
275    #[error(transparent)]
276    LockHeld(#[from] LockHeldError),
277
278    /// Filesystem I/O on the index or a related git-dir path.
279    #[error(transparent)]
280    PathIo(#[from] PathIoError),
281
282    /// `update-index --chmod` / staging hint rejected the path or mode.
283    #[error("cannot change mode of index path '{path}': {reason:?}")]
284    Chmod {
285        /// Repository-relative path (UTF-8 lossy when stored as bytes).
286        path: String,
287        /// Why the mode change was rejected.
288        reason: IndexChmodReason,
289    },
290
291    /// The `core.fsmonitor` hook exited unsuccessfully.
292    #[error("fsmonitor hook exited with {}", status.map_or_else(|| "a signal".to_owned(), |s| format!("status {s}")))]
293    FsmonitorHookFailed {
294        /// Exit status, when the hook exited normally.
295        status: Option<i32>,
296    },
297
298    /// The `core.fsmonitor` hook (protocol version 2) answered without a token.
299    #[error("fsmonitor hook returned empty token")]
300    FsmonitorHookEmptyToken,
301}
302
303impl IndexError {
304    /// Stable snake_case kind name matching legacy [`crate::error::Error`] slugs.
305    #[must_use]
306    pub fn kind_name(&self) -> &'static str {
307        match self {
308            Self::Corrupt { .. } => "index_error",
309            Self::Unmerged { .. } => "index_unmerged",
310            Self::PathPrefixConflict { .. } => "index_path_prefix_conflict",
311            Self::FsmonitorExtensionTruncated => "index_fsmonitor_extension_truncated",
312            Self::FsmonitorExtensionBadVersion(_) => "index_fsmonitor_extension_bad_version",
313            Self::FsmonitorExtensionEwahInvalid => "index_fsmonitor_extension_ewah_invalid",
314            Self::CacheTreeCorrupt => "cache_tree_corrupt",
315            Self::LockHeld(_) => "lock_held",
316            Self::PathIo(_) => "git_dir_path_io",
317            Self::Chmod { .. } => "message",
318            Self::FsmonitorHookFailed { .. } => "index_fsmonitor_hook_failed",
319            Self::FsmonitorHookEmptyToken => "index_fsmonitor_hook_empty_token",
320        }
321    }
322
323    /// Functional area for analytics and JSON (`area`), matching [`Error::area`](crate::error::Error::area) when wrapped.
324    #[must_use]
325    pub fn area(&self) -> &'static str {
326        match self {
327            Self::LockHeld(_) => "lock",
328            Self::PathIo(_) => "repository",
329            _ => "index",
330        }
331    }
332
333    /// Build a corrupt index error with a generated detail string.
334    pub(crate) fn corrupt(corrupt: IndexCorrupt) -> Self {
335        let detail = corrupt_detail(&corrupt);
336        Self::Corrupt { corrupt, detail }
337    }
338
339    /// Build a corrupt index error with optional file path and byte offset.
340    pub(crate) fn corrupt_at(
341        path: Option<&Path>,
342        offset: Option<usize>,
343        reason: IndexCorruptReason,
344    ) -> Self {
345        let mut corrupt = IndexCorrupt::new(reason);
346        if let Some(p) = path {
347            corrupt = corrupt.at_path(p);
348        }
349        if let Some(o) = offset {
350            corrupt = corrupt.at_offset(o);
351        }
352        Self::corrupt(corrupt)
353    }
354
355    /// Unmerged index with no path list (legacy `IndexUnmerged` shape).
356    #[must_use]
357    pub fn unmerged() -> Self {
358        Self::Unmerged { paths: Vec::new() }
359    }
360}
361
362fn corrupt_detail(corrupt: &IndexCorrupt) -> String {
363    match corrupt.reason {
364        IndexCorruptReason::BadSignature => "bad magic: expected DIRC".to_owned(),
365        IndexCorruptReason::UnsupportedVersion { version } => {
366            format!("unsupported index version {version}")
367        }
368        IndexCorruptReason::Truncated => "truncated".to_owned(),
369        IndexCorruptReason::ChecksumMismatch { algo } => {
370            format!("{} checksum mismatch", algo.name().to_uppercase())
371        }
372        IndexCorruptReason::BadEntry => "bad index entry".to_owned(),
373        IndexCorruptReason::FileTooShortForHeader => {
374            "file too short for index header and checksum".to_owned()
375        }
376        IndexCorruptReason::CannotReadVersion => "cannot read version".to_owned(),
377        IndexCorruptReason::CannotReadEntryCount => "cannot read entry count".to_owned(),
378        IndexCorruptReason::ParallelLoadMissingEoie => {
379            "parallel index load missing EOIE offset".to_owned()
380        }
381        IndexCorruptReason::ExtensionOverrunsBody => "extension overruns index body".to_owned(),
382        IndexCorruptReason::ExtensionTruncatedSig => "truncated extension sig".to_owned(),
383        IndexCorruptReason::ExtensionTruncatedSize => "truncated extension size".to_owned(),
384        IndexCorruptReason::JunkAfterExtensions => "junk after index extensions".to_owned(),
385        IndexCorruptReason::UnsupportedExtension { sig } => {
386            format!("index uses unsupported extension {sig:#010x}")
387        }
388        IndexCorruptReason::EntryRegionStartsPastEnd => {
389            "index entry region starts past end of file".to_owned()
390        }
391        IndexCorruptReason::EntryCountMismatch {
392            declared,
393            max_fit,
394            remaining,
395        } => {
396            format!("index declares {declared} entries but only {max_fit} fit in {remaining} bytes")
397        }
398        IndexCorruptReason::EntrySizeOverflow => "index entry size overflow".to_owned(),
399        IndexCorruptReason::EntryOverrunsBody => "index entry overruns index body".to_owned(),
400        IndexCorruptReason::EntryTooShort => "entry too short".to_owned(),
401        IndexCorruptReason::TruncatedU32 => "truncated u32".to_owned(),
402        IndexCorruptReason::TruncatedFlags => "truncated flags".to_owned(),
403        IndexCorruptReason::TruncatedExtendedFlags => "truncated extended flags".to_owned(),
404        IndexCorruptReason::V4PathMissingNul => "v4 entry path missing NUL".to_owned(),
405        IndexCorruptReason::PathMissingNulTerminator => {
406            "entry path missing NUL terminator".to_owned()
407        }
408        IndexCorruptReason::TruncatedIndexEntry => "truncated index entry".to_owned(),
409        IndexCorruptReason::IeotBlockRangeOutOfBounds => {
410            "IEOT block range out of bounds".to_owned()
411        }
412        IndexCorruptReason::IeotEntryCountOverflow => "IEOT entry count overflow".to_owned(),
413        IndexCorruptReason::IeotBlockOffsetPastBody { block, offset } => {
414            format!("IEOT block {block} offset {offset} past index body")
415        }
416        IndexCorruptReason::IeotBlockEntryOverruns { block, pos } => {
417            format!("IEOT block {block} entry overruns index body at {pos}")
418        }
419        IndexCorruptReason::EmptyIeotTable => "empty IEOT table".to_owned(),
420        IndexCorruptReason::IeotEntryCountMismatch { expected, got } => {
421            format!("IEOT entry count mismatch: expected {expected}, got {got}")
422        }
423        IndexCorruptReason::CacheTreeUpdateFailed => "cache-tree update failed".to_owned(),
424        IndexCorruptReason::WriteTreeMissingCacheTree => {
425            "write-tree: missing cache-tree after update".to_owned()
426        }
427        IndexCorruptReason::WriteTreeCacheTreeRootMissingOid => {
428            "write-tree: cache-tree root has no oid".to_owned()
429        }
430        IndexCorruptReason::WriteTreeInvalidPrefix { ref prefix } => {
431            format!("write-tree: invalid prefix '{prefix}'")
432        }
433        IndexCorruptReason::WriteTreeCacheTreeChildMissing => {
434            "cache-tree child missing oid".to_owned()
435        }
436        IndexCorruptReason::WriteTreeExpectedTree { oid } => {
437            format!("expected tree at {oid}")
438        }
439        IndexCorruptReason::WriteTreeMissingIndexEntry => {
440            "missing index entry during tree walk".to_owned()
441        }
442        IndexCorruptReason::ResolveUndoTruncatedPath => "truncated resolve-undo path".to_owned(),
443        IndexCorruptReason::ResolveUndoTruncatedMode => "truncated resolve-undo mode".to_owned(),
444        IndexCorruptReason::ResolveUndoInvalidModeUtf8 => {
445            "invalid UTF-8 in resolve-undo mode".to_owned()
446        }
447        IndexCorruptReason::ResolveUndoInvalidMode { ref mode } => {
448            format!("invalid resolve-undo mode '{mode}'")
449        }
450        IndexCorruptReason::ResolveUndoInvalidPathUtf8 => {
451            "invalid UTF-8 in resolve-undo path".to_owned()
452        }
453        IndexCorruptReason::ResolveUndoCorrupt => "corrupt resolve-undo extension".to_owned(),
454        IndexCorruptReason::ResolveUndoTruncatedOid => {
455            "truncated resolve-undo object id".to_owned()
456        }
457        IndexCorruptReason::UntrackedCacheTruncated => {
458            "untracked-cache extension truncated".to_owned()
459        }
460        IndexCorruptReason::UntrackedCacheInvalidVarint => {
461            "untracked-cache invalid varint".to_owned()
462        }
463        IndexCorruptReason::UntrackedCacheMissingNul => {
464            "untracked-cache payload missing NUL terminator".to_owned()
465        }
466        IndexCorruptReason::UntrackedCacheInvalidUtf8 => "untracked-cache invalid UTF-8".to_owned(),
467        IndexCorruptReason::UntrackedCacheDirCorrupt => {
468            "untracked-cache directory tree corrupt".to_owned()
469        }
470        IndexCorruptReason::UntrackedCacheNoRoot => "no uc root".to_owned(),
471        IndexCorruptReason::SplitIndexCorrupt => "split index corrupt".to_owned(),
472        IndexCorruptReason::SplitIndexTooShort => "index too short".to_owned(),
473        IndexCorruptReason::ChecksumWorkerPanicked => {
474            "index checksum worker thread panicked".to_owned()
475        }
476        IndexCorruptReason::MissingIndexEntryDuringTreeWalk => {
477            "missing index entry during tree walk".to_owned()
478        }
479        IndexCorruptReason::MissingIndexEntryDuringHardReset => {
480            "missing index entry during hard reset align".to_owned()
481        }
482        IndexCorruptReason::HardResetCacheTreeEntryCountMismatch => {
483            "hard reset cache-tree entry count does not match index".to_owned()
484        }
485        IndexCorruptReason::HardResetCacheTreeOutOfSync => {
486            "hard reset cache-tree rebuild: index out of sync with target tree".to_owned()
487        }
488        IndexCorruptReason::HardResetCacheTreeTypeMismatch => {
489            "hard reset cache-tree rebuild: tree/index type mismatch".to_owned()
490        }
491    }
492}
493
494impl From<crate::lockfile::LockError> for IndexError {
495    fn from(err: crate::lockfile::LockError) -> Self {
496        use crate::lockfile::LockError;
497        match err {
498            LockError::Held { path } => Self::LockHeld(LockHeldError {
499                holder: crate::lockfile::LockHolder::read(&path),
500                path,
501            }),
502            LockError::Io { path, source } => Self::PathIo(PathIoError {
503                operation: PathIoOperation::GitDir(GitDirPathOperation::WriteIndex),
504                path: Some(path),
505                source,
506            }),
507        }
508    }
509}
510
511impl From<IndexError> for crate::error::Error {
512    fn from(err: IndexError) -> Self {
513        match err {
514            IndexError::LockHeld(h) => Self::LockHeld(h),
515            IndexError::PathIo(p) => p.into(),
516            other => Self::Index(other),
517        }
518    }
519}
520
521impl From<std::io::Error> for IndexError {
522    fn from(source: std::io::Error) -> Self {
523        Self::PathIo(PathIoError {
524            operation: crate::error::PathIoOperation::GitDir(
525                crate::error::GitDirPathOperation::WriteIndex,
526            ),
527            path: None,
528            source,
529        })
530    }
531}