1#![allow(unused)]
23use std::path::{Path, PathBuf};
45use memmap2::Mmap;
67use crate::{decode, extension, File, State};
89mod error {
1011/// The error returned by [File::at()][super::File::at()].
12#[derive(Debug, thiserror::Error)]
13 #[allow(missing_docs)]
14pub enum Error {
15#[error("An IO error occurred while opening the index")]
16Io(#[from] std::io::Error),
17#[error(transparent)]
18Decode(#[from] crate::decode::Error),
19#[error(transparent)]
20LinkExtension(#[from] crate::extension::link::decode::Error),
21 }
22}
2324pub use error::Error;
2526/// Initialization
27impl File {
28/// Try to open the index file at `path` with `options`, assuming `object_hash` is used throughout the file, or create a new
29 /// index that merely exists in memory and is empty.
30 ///
31 /// Note that the `path` will not be written if it doesn't exist.
32pub fn at_or_default(
33 path: impl Into<PathBuf>,
34 object_hash: git_hash::Kind,
35 options: decode::Options,
36 ) -> Result<Self, Error> {
37let path = path.into();
38Ok(match Self::at(&path, object_hash, options) {
39Ok(f) => f,
40Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
41 File::from_state(State::new(object_hash), path)
42 }
43Err(err) => return Err(err),
44 })
45 }
4647/// Open an index file at `path` with `options`, assuming `object_hash` is used throughout the file.
48pub fn at(path: impl Into<PathBuf>, object_hash: git_hash::Kind, options: decode::Options) -> Result<Self, Error> {
49let path = path.into();
50let (data, mtime) = {
51// SAFETY: we have to take the risk of somebody changing the file underneath. Git never writes into the same file.
52let file = std::fs::File::open(&path)?;
53#[allow(unsafe_code)]
54let data = unsafe { Mmap::map(&file)? };
55 (data, filetime::FileTime::from_last_modification_time(&file.metadata()?))
56 };
5758let (state, checksum) = State::from_bytes(&data, mtime, object_hash, options)?;
59let mut file = File {
60 state,
61 path,
62 checksum: Some(checksum),
63 };
64if let Some(mut link) = file.link.take() {
65 link.dissolve_into(&mut file, object_hash, options)?;
66 }
6768Ok(file)
69 }
7071/// Consume `state` and pretend it was read from `path`, setting our checksum to `null`.
72 ///
73 /// `File` instances created like that should be written to disk to set the correct checksum via `[File::write()]`.
74pub fn from_state(state: crate::State, path: impl Into<PathBuf>) -> Self {
75 File {
76 state,
77 path: path.into(),
78 checksum: None,
79 }
80 }
81}