1use std::path::{Path, PathBuf};
4
5use crate::error::{GitDirPathOperation, LockHeldError, PathIoError, PathIoOperation};
6use crate::objects::HashAlgo;
7use thiserror::Error;
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum IndexCorruptReason {
13 BadSignature,
15 UnsupportedVersion {
17 version: u32,
19 },
20 Truncated,
22 ChecksumMismatch {
24 algo: HashAlgo,
26 },
27 BadEntry,
29 FileTooShortForHeader,
31 CannotReadVersion,
33 CannotReadEntryCount,
35 ParallelLoadMissingEoie,
37 ExtensionOverrunsBody,
39 ExtensionTruncatedSig,
41 ExtensionTruncatedSize,
43 JunkAfterExtensions,
45 UnsupportedExtension {
47 sig: u32,
49 },
50 EntryRegionStartsPastEnd,
52 EntryCountMismatch {
54 declared: u32,
56 max_fit: usize,
58 remaining: usize,
60 },
61 EntrySizeOverflow,
63 EntryOverrunsBody,
65 EntryTooShort,
67 TruncatedU32,
69 TruncatedFlags,
71 TruncatedExtendedFlags,
73 V4PathMissingNul,
75 PathMissingNulTerminator,
77 TruncatedIndexEntry,
79 IeotBlockRangeOutOfBounds,
81 IeotEntryCountOverflow,
83 IeotBlockOffsetPastBody {
85 block: usize,
87 offset: usize,
89 },
90 IeotBlockEntryOverruns {
92 block: usize,
94 pos: usize,
96 },
97 EmptyIeotTable,
99 IeotEntryCountMismatch {
101 expected: u32,
103 got: usize,
105 },
106 CacheTreeUpdateFailed,
108 WriteTreeMissingCacheTree,
110 WriteTreeCacheTreeRootMissingOid,
112 WriteTreeInvalidPrefix {
114 prefix: String,
116 },
117 WriteTreeCacheTreeChildMissing,
119 WriteTreeExpectedTree {
121 oid: crate::objects::ObjectId,
123 },
124 WriteTreeMissingIndexEntry,
126 ResolveUndoTruncatedPath,
128 ResolveUndoTruncatedMode,
130 ResolveUndoInvalidModeUtf8,
132 ResolveUndoInvalidMode {
134 mode: String,
136 },
137 ResolveUndoInvalidPathUtf8,
139 ResolveUndoCorrupt,
141 ResolveUndoTruncatedOid,
143 UntrackedCacheTruncated,
145 UntrackedCacheInvalidVarint,
147 UntrackedCacheMissingNul,
149 UntrackedCacheInvalidUtf8,
151 UntrackedCacheDirCorrupt,
153 UntrackedCacheNoRoot,
155 SplitIndexCorrupt,
157 SplitIndexTooShort,
159 ChecksumWorkerPanicked,
161 MissingIndexEntryDuringTreeWalk,
163 MissingIndexEntryDuringHardReset,
165 HardResetCacheTreeEntryCountMismatch,
167 HardResetCacheTreeOutOfSync,
169 HardResetCacheTreeTypeMismatch,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct IndexCorrupt {
176 pub path: Option<PathBuf>,
178 pub offset: Option<usize>,
180 pub reason: IndexCorruptReason,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Hash)]
186#[non_exhaustive]
187pub enum IndexChmodReason {
188 UnmergedPath,
190 NotChmodEligible,
192 InvalidTargetMode {
194 mode: u32,
196 },
197}
198
199impl IndexCorrupt {
200 #[must_use]
202 pub fn new(reason: IndexCorruptReason) -> Self {
203 Self {
204 path: None,
205 offset: None,
206 reason,
207 }
208 }
209
210 #[must_use]
212 pub fn at_offset(mut self, offset: usize) -> Self {
213 self.offset = Some(offset);
214 self
215 }
216
217 #[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#[derive(Debug, Error)]
227#[non_exhaustive]
228pub enum IndexError {
229 #[error("index error: {detail}")]
231 Corrupt {
232 corrupt: IndexCorrupt,
234 detail: String,
236 },
237
238 #[error("index contains unmerged entries")]
240 Unmerged {
241 paths: Vec<String>,
243 },
244
245 #[error(
247 "index path prefix conflict between '{}' and '{}'",
248 directory.display(),
249 file.display()
250 )]
251 PathPrefixConflict {
252 directory: PathBuf,
254 file: PathBuf,
256 },
257
258 #[error("index fsmonitor extension payload is truncated")]
260 FsmonitorExtensionTruncated,
261
262 #[error("index fsmonitor extension has unsupported header version {0}")]
264 FsmonitorExtensionBadVersion(u32),
265
266 #[error("index fsmonitor extension EWAH bitmap is invalid")]
268 FsmonitorExtensionEwahInvalid,
269
270 #[error("corrupted cache-tree has entries not present in index")]
272 CacheTreeCorrupt,
273
274 #[error(transparent)]
276 LockHeld(#[from] LockHeldError),
277
278 #[error(transparent)]
280 PathIo(#[from] PathIoError),
281
282 #[error("cannot change mode of index path '{path}': {reason:?}")]
284 Chmod {
285 path: String,
287 reason: IndexChmodReason,
289 },
290
291 #[error("fsmonitor hook exited with {}", status.map_or_else(|| "a signal".to_owned(), |s| format!("status {s}")))]
293 FsmonitorHookFailed {
294 status: Option<i32>,
296 },
297
298 #[error("fsmonitor hook returned empty token")]
300 FsmonitorHookEmptyToken,
301}
302
303impl IndexError {
304 #[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 #[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 pub(crate) fn corrupt(corrupt: IndexCorrupt) -> Self {
335 let detail = corrupt_detail(&corrupt);
336 Self::Corrupt { corrupt, detail }
337 }
338
339 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 #[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}