git_index/file/
verify.rs

1use std::sync::atomic::AtomicBool;
2
3use crate::File;
4
5mod error {
6    /// The error returned by [File::verify_integrity()][super::File::verify_integrity()].
7    #[derive(Debug, thiserror::Error)]
8    #[allow(missing_docs)]
9    pub enum Error {
10        #[error("Could not read index file to generate hash")]
11        Io(#[from] std::io::Error),
12        #[error("Index checksum should have been {expected}, but was {actual}")]
13        ChecksumMismatch {
14            actual: git_hash::ObjectId,
15            expected: git_hash::ObjectId,
16        },
17        #[error("Checksum of in-memory index wasn't computed yet")]
18        NoChecksum,
19    }
20}
21pub use error::Error;
22
23impl File {
24    /// Verify the integrity of the index to assure its consistency.
25    pub fn verify_integrity(&self) -> Result<(), Error> {
26        let checksum = self.checksum.ok_or(Error::NoChecksum)?;
27        let num_bytes_to_hash = self.path.metadata()?.len() - checksum.as_bytes().len() as u64;
28        let should_interrupt = AtomicBool::new(false);
29        let actual = git_features::hash::bytes_of_file(
30            &self.path,
31            num_bytes_to_hash as usize,
32            checksum.kind(),
33            &mut git_features::progress::Discard,
34            &should_interrupt,
35        )?;
36        (actual == checksum).then_some(()).ok_or(Error::ChecksumMismatch {
37            actual,
38            expected: checksum,
39        })
40    }
41}