Skip to main content

git_internal/internal/
index.rs

1//! Minimal Git index (.git/index) reader/writer that maps working tree metadata to `IndexEntry`
2//! records, including POSIX timestamp handling and hash serialization helpers.
3
4#[cfg(unix)]
5use std::os::unix::fs::MetadataExt;
6#[cfg(unix)]
7use std::time::Duration;
8use std::{
9    collections::BTreeMap,
10    fmt::{Display, Formatter},
11    fs::{self, File},
12    io,
13    io::{BufReader, Read, Write},
14    path::{Path, PathBuf},
15    time::{SystemTime, UNIX_EPOCH},
16};
17
18use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
19
20use crate::{
21    errors::GitError,
22    hash::{HashKind, ObjectHash, get_hash_kind},
23    internal::{object::types::ObjectType, pack::wrapper::Wrapper},
24    utils::{self, HashAlgorithm},
25};
26
27/// POSIX time with seconds and nanoseconds
28#[derive(PartialEq, Eq, Debug, Clone)]
29pub struct Time {
30    seconds: u32,
31    nanos: u32,
32}
33impl Time {
34    /// Read Time from stream
35    pub fn from_stream(stream: &mut impl Read) -> Result<Self, GitError> {
36        let seconds = stream.read_u32::<BigEndian>()?;
37        let nanos = stream.read_u32::<BigEndian>()?;
38        Ok(Time { seconds, nanos })
39    }
40
41    /// Convert to SystemTime
42    #[allow(dead_code)]
43    fn to_system_time(&self) -> SystemTime {
44        UNIX_EPOCH + std::time::Duration::new(self.seconds.into(), self.nanos)
45    }
46
47    /// Create Time from SystemTime
48    pub fn from_system_time(system_time: SystemTime) -> Self {
49        match system_time.duration_since(UNIX_EPOCH) {
50            Ok(duration) => {
51                let seconds = duration
52                    .as_secs()
53                    .try_into()
54                    .expect("Time is too far in the future");
55                let nanos = duration.subsec_nanos();
56                Time { seconds, nanos }
57            }
58            Err(_) => panic!("Time is before the UNIX epoch"),
59        }
60    }
61}
62impl Display for Time {
63    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
64        write!(f, "{}:{}", self.seconds, self.nanos)
65    }
66}
67
68#[cfg(unix)]
69fn index_ctime(meta: &fs::Metadata) -> SystemTime {
70    unix_metadata_time(meta.ctime(), meta.ctime_nsec())
71}
72
73#[cfg(not(unix))]
74fn index_ctime(meta: &fs::Metadata) -> SystemTime {
75    meta.created()
76        .or_else(|_| meta.modified())
77        .unwrap_or(UNIX_EPOCH)
78}
79
80#[cfg(unix)]
81fn index_mtime(meta: &fs::Metadata) -> SystemTime {
82    unix_metadata_time(meta.mtime(), meta.mtime_nsec())
83}
84
85#[cfg(not(unix))]
86fn index_mtime(meta: &fs::Metadata) -> SystemTime {
87    meta.modified()
88        .or_else(|_| meta.created())
89        .unwrap_or(UNIX_EPOCH)
90}
91
92#[cfg(unix)]
93fn unix_metadata_time(seconds: i64, nanos: i64) -> SystemTime {
94    if seconds < 0 {
95        return UNIX_EPOCH;
96    }
97
98    let nanos = u32::try_from(nanos)
99        .ok()
100        .filter(|nanos| *nanos < 1_000_000_000)
101        .unwrap_or(0);
102
103    UNIX_EPOCH + Duration::new(seconds as u64, nanos)
104}
105
106/// 16 bits
107///
108/// `skip_worktree` and `intent_to_add` live in the on-disk *extended* flags
109/// word (index v3, `CE_EXTENDED`); `extended` records whether that second word
110/// is present. The reader fills all three; the writer derives the on-disk
111/// `CE_EXTENDED` bit from the extended word (or an explicit `extended`).
112#[derive(Debug)]
113pub struct Flags {
114    pub assume_valid: bool,
115    pub extended: bool,   // must be 0 in v2
116    pub stage: u8,        // 2-bit during merge
117    pub name_length: u16, // 12-bit
118    /// `CE_SKIP_WORKTREE` (extended flags bit `0x4000`).
119    pub skip_worktree: bool,
120    /// `CE_INTENT_TO_ADD` (extended flags bit `0x2000`).
121    pub intent_to_add: bool,
122}
123
124impl From<u16> for Flags {
125    fn from(flags: u16) -> Self {
126        Flags {
127            assume_valid: flags & 0x8000 != 0,
128            extended: flags & 0x4000 != 0,
129            stage: ((flags & 0x3000) >> 12) as u8,
130            name_length: flags & 0xFFF,
131            skip_worktree: false,
132            intent_to_add: false,
133        }
134    }
135}
136
137impl TryInto<u16> for &Flags {
138    type Error = &'static str;
139    fn try_into(self) -> Result<u16, Self::Error> {
140        let mut flags = 0u16;
141        if self.assume_valid {
142            flags |= 0x8000; // 16
143        }
144        if self.extended {
145            flags |= 0x4000; // 15
146        }
147        flags |= (self.stage as u16) << 12; // 13-14
148        if self.name_length > 0xFFF {
149            return Err("Name length is too long");
150        }
151        flags |= self.name_length; // 0-11
152        Ok(flags)
153    }
154}
155
156impl Flags {
157    /// The on-disk extended flag `CE_SKIP_WORKTREE`.
158    pub const EXTENDED_FLAG_SKIP_WORKTREE: u16 = 0x4000;
159    /// The on-disk extended flag `CE_INTENT_TO_ADD`.
160    pub const EXTENDED_FLAG_INTENT_TO_ADD: u16 = 0x2000;
161
162    pub fn new(name_len: u16) -> Self {
163        Flags {
164            assume_valid: true,
165            extended: false,
166            stage: 0,
167            name_length: name_len,
168            skip_worktree: false,
169            intent_to_add: false,
170        }
171    }
172
173    /// Decode the 16-bit extended flags word, failing closed on unknown bits.
174    pub fn from_extended_word(word: u16) -> Result<(bool, bool), GitError> {
175        const KNOWN: u16 = Flags::EXTENDED_FLAG_SKIP_WORKTREE | Flags::EXTENDED_FLAG_INTENT_TO_ADD;
176        if word & !KNOWN != 0 {
177            return Err(GitError::InvalidIndexFile(format!(
178                "index entry has unknown extended flags 0x{word:04x}"
179            )));
180        }
181        Ok((
182            word & Flags::EXTENDED_FLAG_SKIP_WORKTREE != 0,
183            word & Flags::EXTENDED_FLAG_INTENT_TO_ADD != 0,
184        ))
185    }
186
187    /// The extended flags word to write, or `None` when no extended bit is set.
188    pub fn extended_word(&self) -> Option<u16> {
189        let mut word = 0u16;
190        if self.skip_worktree {
191            word |= Flags::EXTENDED_FLAG_SKIP_WORKTREE;
192        }
193        if self.intent_to_add {
194            word |= Flags::EXTENDED_FLAG_INTENT_TO_ADD;
195        }
196        (word != 0).then_some(word)
197    }
198}
199
200/// An entry in the Git index file.
201pub struct IndexEntry {
202    pub ctime: Time,
203    pub mtime: Time,
204    pub dev: u32,  // 0 for windows
205    pub ino: u32,  // 0 for windows
206    pub mode: u32, // 0o100644 // 4-bit object type + 3-bit unused + 9-bit unix permission
207    pub uid: u32,  // 0 for windows
208    pub gid: u32,  // 0 for windows
209    pub size: u32,
210    pub hash: ObjectHash,
211    pub flags: Flags,
212    pub name: String,
213}
214impl Display for IndexEntry {
215    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
216        write!(
217            f,
218            "IndexEntry {{ ctime: {}, mtime: {}, dev: {}, ino: {}, mode: {:o}, uid: {}, gid: {}, size: {}, hash: {}, flags: {:?}, name: {} }}",
219            self.ctime,
220            self.mtime,
221            self.dev,
222            self.ino,
223            self.mode,
224            self.uid,
225            self.gid,
226            self.size,
227            self.hash,
228            self.flags,
229            self.name
230        )
231    }
232}
233
234impl IndexEntry {
235    /** Metadata must be got by [fs::symlink_metadata] to avoid following symlink */
236    pub fn new(meta: &fs::Metadata, hash: ObjectHash, name: String) -> Self {
237        let mut entry = IndexEntry {
238            ctime: Time::from_system_time(index_ctime(meta)),
239            mtime: Time::from_system_time(index_mtime(meta)),
240            dev: 0,
241            ino: 0,
242            uid: 0,
243            gid: 0,
244            size: meta.len() as u32,
245            hash,
246            flags: Flags::new(name.len() as u16),
247            name,
248            mode: 0o100644,
249        };
250        #[cfg(unix)]
251        {
252            entry.dev = meta.dev() as u32;
253            entry.ino = meta.ino() as u32;
254            entry.uid = meta.uid();
255            entry.gid = meta.gid();
256
257            entry.mode = match meta.mode() & 0o170000/* file mode */ {
258                0o100000 => {
259                    match meta.mode() & 0o111 {
260                        0 => 0o100644, // no execute permission
261                        _ => 0o100755, // with execute permission
262                    }
263                }
264                0o120000 => 0o120000, // symlink
265                _ =>  entry.mode, // keep the original mode
266            }
267        }
268        #[cfg(windows)]
269        {
270            if meta.is_symlink() {
271                entry.mode = 0o120000;
272            }
273        }
274        entry
275    }
276
277    /// - `file`: **to workdir path**
278    /// - `workdir`: absolute or relative path
279    pub fn new_from_file(file: &Path, hash: ObjectHash, workdir: &Path) -> io::Result<Self> {
280        let name = file.to_str().unwrap().to_string();
281        let file_abs = workdir.join(file);
282        let meta = fs::symlink_metadata(file_abs)?; // without following symlink
283        let index = IndexEntry::new(&meta, hash, name);
284        Ok(index)
285    }
286
287    /// Create IndexEntry from blob object
288    pub fn new_from_blob(name: String, hash: ObjectHash, size: u32) -> Self {
289        IndexEntry {
290            ctime: Time {
291                seconds: 0,
292                nanos: 0,
293            },
294            mtime: Time {
295                seconds: 0,
296                nanos: 0,
297            },
298            dev: 0,
299            ino: 0,
300            mode: 0o100644,
301            uid: 0,
302            gid: 0,
303            size,
304            hash,
305            flags: Flags::new(name.len() as u16),
306            name,
307        }
308    }
309}
310
311/// see [index-format](https://git-scm.com/docs/index-format)
312/// <br> to Working Dir relative path
313pub struct Index {
314    entries: BTreeMap<(String, u8), IndexEntry>,
315}
316
317impl Index {
318    pub fn new() -> Self {
319        Index {
320            entries: BTreeMap::new(),
321        }
322    }
323
324    /// Parse and validate the `DIRC` header, returning `(version, entry_count)`.
325    /// Versions 2 and 3 are accepted; anything else fails closed.
326    fn check_header(file: &mut impl Read) -> Result<(u32, u32), GitError> {
327        let mut magic = [0; 4];
328        file.read_exact(&mut magic)?;
329        if magic != *b"DIRC" {
330            return Err(GitError::InvalidIndexHeader(
331                String::from_utf8_lossy(&magic).to_string(),
332            ));
333        }
334
335        let version = file.read_u32::<BigEndian>()?;
336        // v3 adds the per-entry extended flags word; later versions are unsupported.
337        if version != 2 && version != 3 {
338            return Err(GitError::InvalidIndexHeader(version.to_string()));
339        }
340
341        let entries = file.read_u32::<BigEndian>()?;
342        Ok((version, entries))
343    }
344
345    pub fn size(&self) -> usize {
346        self.entries.len()
347    }
348
349    /// Read an index file using the thread-local [`HashKind`]; compatibility wrapper around
350    /// [`Index::from_file_with_hash_kind`].
351    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, GitError> {
352        Self::from_file_with_hash_kind(get_hash_kind(), path)
353    }
354
355    /// Read an index file whose entry IDs and checksum belong to the explicit repository
356    /// `kind`. The checksum is verified with `kind`, so an index written for another kind
357    /// (even one of the same width) fails closed instead of being misread.
358    pub fn from_file_with_hash_kind(
359        kind: HashKind,
360        path: impl AsRef<Path>,
361    ) -> Result<Self, GitError> {
362        let file = File::open(path.as_ref())?; // read-only
363        let total_size = file.metadata()?.len();
364        let file = &mut Wrapper::new_with_kind(BufReader::new(file), kind); // TODO move Wrapper & utils to a common module
365
366        let (_version, num) = Index::check_header(file)?;
367        let mut index = Index::new();
368
369        for _ in 0..num {
370            let mut entry = IndexEntry {
371                ctime: Time::from_stream(file)?,
372                mtime: Time::from_stream(file)?,
373                dev: file.read_u32::<BigEndian>()?, //utils::read_u32_be(file)?,
374                ino: file.read_u32::<BigEndian>()?,
375                mode: file.read_u32::<BigEndian>()?,
376                uid: file.read_u32::<BigEndian>()?,
377                gid: file.read_u32::<BigEndian>()?,
378                size: file.read_u32::<BigEndian>()?,
379                hash: utils::read_sha_for_kind(kind, file)?,
380                flags: Flags::from(file.read_u16::<BigEndian>()?),
381                name: String::new(),
382            };
383            // v3 entries with CE_EXTENDED carry a second flags word directly
384            // after the main word and before the name (index-format(5)).
385            if entry.flags.extended {
386                let word = file.read_u16::<BigEndian>()?;
387                let (skip_worktree, intent_to_add) = Flags::from_extended_word(word)?;
388                entry.flags.skip_worktree = skip_worktree;
389                entry.flags.intent_to_add = intent_to_add;
390            }
391            let name_len = entry.flags.name_length as usize;
392            let mut name = vec![0; name_len];
393            file.read_exact(&mut name)?;
394            // The exact encoding is undefined, but the '.' and '/' characters are encoded in 7-bit ASCII
395            entry.name =
396                String::from_utf8(name).map_err(|e| GitError::ConversionError(e.to_string()))?; // TODO check the encoding
397            let extended = entry.flags.extended;
398            index
399                .entries
400                .insert((entry.name.clone(), entry.flags.stage), entry);
401
402            // 1-8 nul bytes as necessary to pad the entry to a multiple of eight bytes
403            // while keeping the name NUL-terminated. The extended flags word, when
404            // present, is part of the padded entry length.
405            let hash_len = kind.size();
406            let entry_len = hash_len + 2 + if extended { 2 } else { 0 } + name_len;
407            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
408            utils::read_bytes(file, padding)?;
409        }
410
411        // Extensions
412        while file.bytes_read() + kind.size() < total_size as usize {
413            // The remaining bytes must be the index checksum (size = kind.size())
414            let sign = utils::read_bytes(file, 4)?;
415            println!(
416                "{:?}",
417                String::from_utf8(sign.clone())
418                    .map_err(|e| GitError::ConversionError(e.to_string()))?
419            );
420            // If the first byte is 'A'...'Z' the extension is optional and can be ignored.
421            if sign[0] >= b'A' && sign[0] <= b'Z' {
422                // Optional extension
423                let size = file.read_u32::<BigEndian>()?;
424                utils::read_bytes(file, size as usize)?; // Ignore the extension
425            } else {
426                // 'link' or 'sdir' extension
427                return Err(GitError::InvalidIndexFile(
428                    "Unsupported extension".to_string(),
429                ));
430            }
431        }
432
433        // check sum
434        let file_hash = file.final_hash();
435        let check_sum = utils::read_sha_for_kind(kind, file)?;
436        if file_hash != check_sum {
437            return Err(GitError::InvalidIndexFile("Check sum failed".to_string()));
438        }
439        assert_eq!(index.size(), num as usize);
440        Ok(index)
441    }
442
443    /// Write the index using the thread-local [`HashKind`]; compatibility wrapper around
444    /// [`Index::to_file_with_hash_kind`].
445    pub fn to_file(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
446        self.to_file_with_hash_kind(get_hash_kind(), path)
447    }
448
449    /// Write the index for an explicit repository `kind`: every entry ID must belong to
450    /// `kind` (a cross-kind entry fails closed) and the trailing checksum is computed with it.
451    pub fn to_file_with_hash_kind(
452        &self,
453        kind: HashKind,
454        path: impl AsRef<Path>,
455    ) -> Result<(), GitError> {
456        // Validate every entry before touching the destination, so a cross-kind entry can
457        // neither truncate an existing valid index nor leave a partial file behind.
458        for entry in self.entries.values() {
459            entry.hash.ensure_kind(kind)?;
460        }
461        let mut file = File::create(path)?;
462        let mut hash = HashAlgorithm::new_for_kind(kind);
463
464        // Any entry carrying an extended flags word forces the whole index to v3;
465        // otherwise the output stays byte-identical to the v2 writer.
466        let any_extended = self
467            .entries
468            .values()
469            .any(|entry| entry.flags.extended_word().is_some() || entry.flags.extended);
470
471        let mut header = Vec::new();
472        header.write_all(b"DIRC")?;
473        header.write_u32::<BigEndian>(if any_extended { 3u32 } else { 2u32 })?;
474        header.write_u32::<BigEndian>(self.entries.len() as u32)?;
475        file.write_all(&header)?;
476        hash.update(&header);
477
478        for entry in self.entries.values() {
479            let mut entry_bytes = Vec::new();
480            entry_bytes.write_u32::<BigEndian>(entry.ctime.seconds)?;
481            entry_bytes.write_u32::<BigEndian>(entry.ctime.nanos)?;
482            entry_bytes.write_u32::<BigEndian>(entry.mtime.seconds)?;
483            entry_bytes.write_u32::<BigEndian>(entry.mtime.nanos)?;
484            entry_bytes.write_u32::<BigEndian>(entry.dev)?;
485            entry_bytes.write_u32::<BigEndian>(entry.ino)?;
486            entry_bytes.write_u32::<BigEndian>(entry.mode)?;
487            entry_bytes.write_u32::<BigEndian>(entry.uid)?;
488            entry_bytes.write_u32::<BigEndian>(entry.gid)?;
489            entry_bytes.write_u32::<BigEndian>(entry.size)?;
490            entry_bytes.write_all(entry.hash.as_ref())?;
491            // An explicit `extended` with no known bit still emits a zero word so
492            // the on-disk layout stays self-consistent.
493            let extended_word = entry.flags.extended_word().or(if entry.flags.extended {
494                Some(0u16)
495            } else {
496                None
497            });
498            let mut packed: u16 = (&entry.flags).try_into().map_err(|error| {
499                GitError::InvalidIndexFile(format!("cannot encode index flags: {error}"))
500            })?;
501            if extended_word.is_some() {
502                packed |= 0x4000; // CE_EXTENDED
503            }
504            entry_bytes.write_u16::<BigEndian>(packed)?;
505            if let Some(word) = extended_word {
506                entry_bytes.write_u16::<BigEndian>(word)?;
507            }
508            entry_bytes.write_all(entry.name.as_bytes())?;
509            let hash_len = kind.size();
510            let entry_len =
511                hash_len + 2 + if extended_word.is_some() { 2 } else { 0 } + entry.name.len();
512            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
513            entry_bytes.write_all(&vec![0; padding])?;
514            file.write_all(&entry_bytes)?;
515            hash.update(&entry_bytes);
516        }
517
518        // Extensions
519
520        // check sum
521        let file_hash = hash.finalize_object_hash();
522        file.write_all(file_hash.as_ref())?;
523        Ok(())
524    }
525
526    /// Refresh one entry using the thread-local [`HashKind`]; compatibility wrapper around
527    /// [`Index::refresh_with_hash_kind`].
528    pub fn refresh(&mut self, file: impl AsRef<Path>, workdir: &Path) -> Result<bool, GitError> {
529        self.refresh_with_hash_kind(get_hash_kind(), file, workdir)
530    }
531
532    /// Refresh one entry's stat data and content hash for an explicit repository `kind`.
533    ///
534    /// The recomputed ID is the blob's object ID — the digest of `"<type> <size>\0"` + the
535    /// file contents, exactly what [`ObjectHash::from_type_and_data_for_kind`] produces for
536    /// [`ObjectType::Blob`] — not a digest of the raw file bytes. The header is streamed
537    /// into the hasher before the file, so the file is never buffered in memory.
538    ///
539    /// The existing entry must already belong to `kind`: refreshing an entry of another kind
540    /// fails closed instead of silently replacing its ID with a digest of a different
541    /// algorithm.
542    pub fn refresh_with_hash_kind(
543        &mut self,
544        kind: HashKind,
545        file: impl AsRef<Path>,
546        workdir: &Path,
547    ) -> Result<bool, GitError> {
548        let path = file.as_ref();
549        let name = path
550            .to_str()
551            .ok_or(GitError::InvalidPathError(format!("{path:?}")))?;
552
553        if let Some(entry) = self.entries.get_mut(&(name.to_string(), 0)) {
554            entry.hash.ensure_kind(kind)?;
555            let abs_path = workdir.join(path);
556            let meta = fs::symlink_metadata(&abs_path)?;
557            let new_ctime = Time::from_system_time(index_ctime(&meta));
558            let new_mtime = Time::from_system_time(index_mtime(&meta));
559            let new_size = meta.len() as u32;
560
561            // re-calculate the blob ID with the repository kind: the ID covers
562            // `"<type> <size>\0" + content` (see `ObjectHash::from_type_and_data_for_kind`),
563            // so the header must be hashed before the file contents. Streaming the header
564            // first keeps the file itself out of memory.
565            let type_label = ObjectType::Blob
566                .to_bytes()
567                .ok_or_else(|| GitError::InvalidObjectType("Blob".to_string()))?;
568            let mut hasher = HashAlgorithm::new_for_kind(kind);
569            hasher.update(type_label);
570            hasher.update(b" ");
571            hasher.update(meta.len().to_string().as_bytes());
572            hasher.update(b"\x00");
573            let mut file = File::open(&abs_path)?;
574            io::copy(&mut file, &mut hasher)?;
575            let new_hash = hasher.finalize_object_hash();
576
577            // refresh index
578            if entry.ctime != new_ctime
579                || entry.mtime != new_mtime
580                || entry.size != new_size
581                || entry.hash != new_hash
582            {
583                entry.ctime = new_ctime;
584                entry.mtime = new_mtime;
585                entry.size = new_size;
586                entry.hash = new_hash;
587                return Ok(true);
588            }
589        }
590        Ok(false)
591    }
592}
593
594impl Default for Index {
595    fn default() -> Self {
596        Self::new()
597    }
598}
599
600impl Index {
601    /// Load index. If it does not exist, return an empty index.
602    ///
603    /// Uses the thread-local [`HashKind`]; see [`Index::load_with_hash_kind`].
604    pub fn load(index_file: impl AsRef<Path>) -> Result<Self, GitError> {
605        Self::load_with_hash_kind(get_hash_kind(), index_file)
606    }
607
608    /// Load index for an explicit repository `kind`. If it does not exist, return an empty index.
609    pub fn load_with_hash_kind(
610        kind: HashKind,
611        index_file: impl AsRef<Path>,
612    ) -> Result<Self, GitError> {
613        let path = index_file.as_ref();
614        if !path.exists() {
615            return Ok(Index::new());
616        }
617        Index::from_file_with_hash_kind(kind, path)
618    }
619
620    pub fn update(&mut self, entry: IndexEntry) {
621        self.add(entry)
622    }
623
624    pub fn add(&mut self, entry: IndexEntry) {
625        self.entries
626            .insert((entry.name.clone(), entry.flags.stage), entry);
627    }
628
629    pub fn remove(&mut self, name: &str, stage: u8) -> Option<IndexEntry> {
630        self.entries.remove(&(name.to_string(), stage))
631    }
632
633    pub fn get(&self, name: &str, stage: u8) -> Option<&IndexEntry> {
634        self.entries.get(&(name.to_string(), stage))
635    }
636
637    pub fn tracked(&self, name: &str, stage: u8) -> bool {
638        self.entries.contains_key(&(name.to_string(), stage))
639    }
640
641    pub fn get_hash(&self, file: &str, stage: u8) -> Option<ObjectHash> {
642        self.get(file, stage).map(|entry| entry.hash)
643    }
644
645    pub fn verify_hash(&self, file: &str, stage: u8, hash: &ObjectHash) -> bool {
646        let inner_hash = self.get_hash(file, stage);
647        if let Some(inner_hash) = inner_hash {
648            &inner_hash == hash
649        } else {
650            false
651        }
652    }
653    /// is file modified after last `add` (need hash to confirm content change)
654    /// - `workdir` is used to rebuild absolute file path
655    pub fn is_modified(&self, file: &str, stage: u8, workdir: &Path) -> bool {
656        if let Some(entry) = self.get(file, stage) {
657            let path_abs = workdir.join(file);
658            let meta = path_abs.symlink_metadata().unwrap();
659            // TODO more fields
660            let same = entry.ctime == Time::from_system_time(index_ctime(&meta))
661                && entry.mtime == Time::from_system_time(index_mtime(&meta))
662                && entry.size == meta.len() as u32;
663
664            !same
665        } else {
666            panic!("File not found in index");
667        }
668    }
669
670    /// Get all entries with the same stage
671    pub fn tracked_entries(&self, stage: u8) -> Vec<&IndexEntry> {
672        // ? should use stage or not
673        self.entries
674            .iter()
675            .filter(|(_, entry)| entry.flags.stage == stage)
676            .map(|(_, entry)| entry)
677            .collect()
678    }
679
680    /// Get all tracked files(stage = 0)
681    pub fn tracked_files(&self) -> Vec<PathBuf> {
682        self.tracked_entries(0)
683            .iter()
684            .map(|entry| PathBuf::from(&entry.name))
685            .collect()
686    }
687
688    /// Judge if the file(s) of `dir` is in the index
689    /// - false if `dir` is a file
690    pub fn contains_dir_file(&self, dir: &str) -> bool {
691        let dir = Path::new(dir);
692        self.entries.iter().any(|((name, _), _)| {
693            let path = Path::new(name);
694            path.starts_with(dir) && path != dir // TODO change to is_sub_path!
695        })
696    }
697
698    /// remove all files in `dir` from index
699    /// - do nothing if `dir` is a file
700    pub fn remove_dir_files(&mut self, dir: &str) -> Vec<String> {
701        let dir = Path::new(dir);
702        let mut removed = Vec::new();
703        self.entries.retain(|(name, _), _| {
704            let path = Path::new(name);
705            if path.starts_with(dir) && path != dir {
706                removed.push(name.clone());
707                false
708            } else {
709                true
710            }
711        });
712        removed
713    }
714
715    /// saved to index file (thread-local [`HashKind`]; see [`Index::save_with_hash_kind`])
716    pub fn save(&self, index_file: impl AsRef<Path>) -> Result<(), GitError> {
717        self.to_file(index_file)
718    }
719
720    /// Save to an index file for an explicit repository `kind`.
721    pub fn save_with_hash_kind(
722        &self,
723        kind: HashKind,
724        index_file: impl AsRef<Path>,
725    ) -> Result<(), GitError> {
726        self.to_file_with_hash_kind(kind, index_file)
727    }
728}
729
730#[cfg(test)]
731mod tests {
732    use std::io::Cursor;
733
734    use super::*;
735    use crate::{
736        hash::{HashKind, set_hash_kind_for_test},
737        internal::object::blob::Blob,
738    };
739
740    /// Test Time conversion
741    #[test]
742    fn test_time() {
743        let time = Time {
744            seconds: 0,
745            nanos: 0,
746        };
747        let system_time = time.to_system_time();
748        let new_time = Time::from_system_time(system_time);
749        assert_eq!(time, new_time);
750    }
751
752    /// Test Flags conversion
753    #[test]
754    fn test_check_header() {
755        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
756        source.push("tests/data/index/index-2");
757
758        let file = File::open(source).unwrap();
759        let (version, entries) = Index::check_header(&mut BufReader::new(file)).unwrap();
760        assert_eq!(version, 2);
761        assert_eq!(entries, 2);
762    }
763
764    /// Test IndexEntry creation
765    #[test]
766    fn test_index() {
767        let _guard = set_hash_kind_for_test(HashKind::Sha1);
768        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
769        source.push("tests/data/index/index-760");
770
771        let index = Index::from_file(source).unwrap();
772        assert_eq!(index.size(), 760);
773        for entry in index.entries.values() {
774            println!("{entry}");
775        }
776    }
777
778    /// Test IndexEntry creation with SHA256
779    #[test]
780    fn test_index_sha256() {
781        let _guard = set_hash_kind_for_test(HashKind::Sha256);
782        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
783        source.push("tests/data/index/index-9-256");
784
785        let index = Index::from_file(source).unwrap();
786        assert_eq!(index.size(), 9);
787        for entry in index.entries.values() {
788            println!("{entry}");
789        }
790    }
791
792    /// Flags bit packing/unpacking covers all fields and enforces name length limit.
793    #[test]
794    fn flags_round_trip_and_length_limit() {
795        let mut flags = Flags {
796            assume_valid: true,
797            extended: true,
798            stage: 2,
799            name_length: 0x0ABC,
800            skip_worktree: false,
801            intent_to_add: false,
802        };
803        let packed: u16 = (&flags).try_into().expect("should pack");
804        let unpacked = Flags::from(packed);
805        assert_eq!(unpacked.assume_valid, flags.assume_valid);
806        assert_eq!(unpacked.extended, flags.extended);
807        assert_eq!(unpacked.stage, flags.stage);
808        assert_eq!(unpacked.name_length, flags.name_length);
809
810        flags.name_length = 0x1FFF;
811        let overflow: Result<u16, _> = (&flags).try_into();
812        assert!(overflow.is_err(), "length overflow should err");
813    }
814
815    /// IndexEntry::new_from_blob populates fields and sets flags length.
816    #[test]
817    fn index_entry_new_from_blob_populates_fields() {
818        let hash = ObjectHash::from_bytes(&[0u8; 20]).unwrap();
819        let entry = IndexEntry::new_from_blob("file.txt".to_string(), hash, 42);
820        assert_eq!(entry.name, "file.txt");
821        assert_eq!(entry.size, 42);
822        assert_eq!(entry.hash, hash);
823        assert_eq!(entry.flags.name_length, "file.txt".len() as u16);
824        assert_eq!(entry.mode, 0o100644);
825    }
826
827    /// Index container operations: add/get/tracked/dir helpers.
828    #[test]
829    fn index_add_and_query_helpers() {
830        let _guard = set_hash_kind_for_test(HashKind::Sha1);
831        let mut index = Index::new();
832        let hash = ObjectHash::from_bytes(&[1u8; 20]).unwrap();
833        let entry = IndexEntry::new_from_blob("a/b.txt".to_string(), hash, 10);
834        index.add(entry);
835
836        // get finds stage-0 by name
837        let got = index.get("a/b.txt", 0).expect("entry exists");
838        assert_eq!(got.hash, hash);
839
840        // tracked_entries/files return stage-0 paths
841        let tracked = index.tracked_entries(0);
842        assert_eq!(tracked.len(), 1);
843        let files = index.tracked_files();
844        assert_eq!(files, vec![PathBuf::from("a/b.txt")]);
845
846        // contains_dir_file true for subpath, false for exact file
847        assert!(index.contains_dir_file("a"));
848        assert!(!index.contains_dir_file("a/b.txt"));
849
850        // remove_dir_files removes under dir and returns removed names
851        let removed = index.remove_dir_files("a");
852        assert_eq!(removed, vec!["a/b.txt".to_string()]);
853        assert!(index.get("a/b.txt", 0).is_none());
854    }
855
856    /// check_header should reject bad magic/versions and accept valid headers.
857    #[test]
858    fn check_header_validation() {
859        // valid header: "DIRC" + version 2 + 0 entries
860        let mut valid = Cursor::new(b"DIRC\0\0\0\x02\0\0\0\0".to_vec());
861        let (version, entries) = Index::check_header(&mut valid).expect("valid header");
862        assert_eq!(version, 2);
863        assert_eq!(entries, 0);
864
865        // v3 is accepted: it only adds an optional per-entry extended flags word
866        let mut v3 = Cursor::new(b"DIRC\0\0\0\x03\0\0\0\0".to_vec());
867        let (version, entries) = Index::check_header(&mut v3).expect("v3 header");
868        assert_eq!(version, 3);
869        assert_eq!(entries, 0);
870
871        // bad magic
872        let mut bad_magic = Cursor::new(b"XXXX\0\0\0\x02\0\0\0\0".to_vec());
873        assert!(Index::check_header(&mut bad_magic).is_err());
874
875        // unsupported versions (1 and 4) fail closed
876        let mut bad_version = Cursor::new(b"DIRC\0\0\0\x01\0\0\0\0".to_vec());
877        assert!(Index::check_header(&mut bad_version).is_err());
878        let mut v4 = Cursor::new(b"DIRC\0\0\0\x04\0\0\0\0".to_vec());
879        assert!(Index::check_header(&mut v4).is_err());
880    }
881
882    /// Test saving Index to file
883    #[test]
884    fn test_index_to_file() {
885        let temp_dir = tempfile::tempdir().unwrap();
886        let temp_path = temp_dir.path().join("index-760");
887
888        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
889        source.push("tests/data/index/index-760");
890
891        let index = Index::from_file(source).unwrap();
892        index.to_file(&temp_path).unwrap();
893        let new_index = Index::from_file(temp_path).unwrap();
894        assert_eq!(index.size(), new_index.size());
895    }
896
897    /// A real index v3 generated by git 2.55.0 (SHA-1) with one skip-worktree
898    /// entry (`a.txt`): header v3, entry flags `0x4005`, extended word `0x4000`.
899    const GIT_V3_SKIP_WORKTREE_FIXTURE: [u8; 104] = [
900        0x44, 0x49, 0x52, 0x43, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x6a, 0xaf, 0x4a,
901        0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x6a, 0xaf, 0x4a, 0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x00, 0x00,
902        0x00, 0x3a, 0x06, 0x98, 0x73, 0xd9, 0x00, 0x00, 0x81, 0xa4, 0x00, 0x00, 0x03, 0xe8, 0x00,
903        0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x03, 0x45, 0xb9, 0x83, 0xbe, 0x36, 0xb7, 0x3c, 0x07,
904        0x88, 0xdc, 0x9c, 0xbc, 0xb7, 0x6c, 0xbb, 0x80, 0xfc, 0x7b, 0xb0, 0x57, 0x40, 0x05, 0x40,
905        0x00, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x00, 0x00, 0x32, 0xd2, 0xa6, 0x5d, 0x73, 0x12,
906        0x16, 0x5a, 0x7f, 0x63, 0xda, 0x76, 0xd4, 0xd0, 0xaa, 0xc8, 0xab, 0xc4, 0xc0, 0x06,
907    ];
908
909    /// A git-generated v3 index with `CE_SKIP_WORKTREE` reads back with the bit set.
910    #[test]
911    fn index_reads_git_v3_skip_worktree_fixture() {
912        let _guard = set_hash_kind_for_test(HashKind::Sha1);
913        let temp_dir = tempfile::tempdir().unwrap();
914        let path = temp_dir.path().join("index-v3-git");
915        std::fs::write(&path, GIT_V3_SKIP_WORKTREE_FIXTURE).unwrap();
916
917        let index = Index::from_file(&path).unwrap();
918        assert_eq!(index.size(), 1);
919        let entry = index.get("a.txt", 0).expect("fixture entry");
920        assert_eq!(entry.mode, 0o100644);
921        assert!(entry.flags.skip_worktree, "CE_SKIP_WORKTREE must be set");
922        assert!(!entry.flags.intent_to_add);
923    }
924
925    /// An unknown extended bit fails closed instead of being silently dropped.
926    #[test]
927    fn index_rejects_unknown_extended_bit() {
928        let _guard = set_hash_kind_for_test(HashKind::Sha1);
929        let temp_dir = tempfile::tempdir().unwrap();
930        let path = temp_dir.path().join("index-bad-extended");
931
932        let mut raw = GIT_V3_SKIP_WORKTREE_FIXTURE.to_vec();
933        raw[74] = 0x10; // extended word 0x4000 -> 0x1000 (unknown bit)
934        raw[75] = 0x00;
935        let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha1);
936        hasher.update(&raw[..raw.len() - 20]);
937        let checksum = hasher.finalize_object_hash();
938        raw.truncate(raw.len() - 20);
939        raw.extend_from_slice(checksum.as_ref());
940        std::fs::write(&path, &raw).unwrap();
941
942        let error = match Index::from_file(&path) {
943            Ok(_) => panic!("an index with an unknown extended bit must fail closed"),
944            Err(error) => error,
945        };
946        assert!(
947            matches!(error, GitError::InvalidIndexFile(_)),
948            "unexpected error: {error:?}"
949        );
950    }
951
952    /// Writing extended flags forces index v3 and survives a round trip.
953    #[test]
954    fn index_v3_round_trip_preserves_extended_flags() {
955        let _guard = set_hash_kind_for_test(HashKind::Sha1);
956        let temp_dir = tempfile::tempdir().unwrap();
957        let path = temp_dir.path().join("index-v3-round-trip");
958
959        let mut index = Index::new();
960        let hash = ObjectHash::from_bytes(&[0x11u8; 20]).unwrap();
961        let mut skip = IndexEntry::new_from_blob("skip.txt".to_string(), hash, 7);
962        skip.flags.skip_worktree = true;
963        index.update(skip);
964        let hash = ObjectHash::from_bytes(&[0x22u8; 20]).unwrap();
965        let mut ita = IndexEntry::new_from_blob("ita.txt".to_string(), hash, 9);
966        ita.flags.intent_to_add = true;
967        index.update(ita);
968
969        index.to_file(&path).unwrap();
970        let raw = std::fs::read(&path).unwrap();
971        assert_eq!(&raw[..4], b"DIRC");
972        assert_eq!(
973            u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]),
974            3,
975            "extended flags must force version 3"
976        );
977
978        let loaded = Index::from_file(&path).unwrap();
979        let skip = loaded.get("skip.txt", 0).unwrap();
980        assert!(skip.flags.skip_worktree);
981        assert!(!skip.flags.intent_to_add);
982        let ita = loaded.get("ita.txt", 0).unwrap();
983        assert!(ita.flags.intent_to_add);
984        assert!(!ita.flags.skip_worktree);
985    }
986
987    /// Without extended bits the writer keeps emitting v2.
988    #[test]
989    fn index_without_extended_flags_stays_v2() {
990        let _guard = set_hash_kind_for_test(HashKind::Sha1);
991        let temp_dir = tempfile::tempdir().unwrap();
992        let path = temp_dir.path().join("index-v2-round-trip");
993
994        let mut index = Index::new();
995        let hash = ObjectHash::from_bytes(&[0x33u8; 20]).unwrap();
996        index.update(IndexEntry::new_from_blob("plain.txt".to_string(), hash, 3));
997        index.to_file(&path).unwrap();
998
999        let raw = std::fs::read(&path).unwrap();
1000        assert_eq!(u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]), 2);
1001        let loaded = Index::from_file(&path).unwrap();
1002        let entry = loaded.get("plain.txt", 0).unwrap();
1003        assert!(!entry.flags.skip_worktree);
1004        assert!(!entry.flags.intent_to_add);
1005    }
1006
1007    /// Test IndexEntry creation from file
1008    #[test]
1009    fn test_index_entry_create() {
1010        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1011        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1012        source.push("Cargo.toml");
1013
1014        let file = Path::new(source.as_path()); // use as a normal file
1015        let hash = ObjectHash::from_bytes(&[0; 20]).unwrap();
1016        let workdir = Path::new("../");
1017        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
1018        println!("{entry}");
1019    }
1020
1021    /// Test IndexEntry creation from file with SHA256
1022    #[test]
1023    fn test_index_entry_create_sha256() {
1024        let _guard = set_hash_kind_for_test(HashKind::Sha256);
1025        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1026        source.push("Cargo.toml");
1027
1028        let file = Path::new(source.as_path());
1029        let hash = ObjectHash::from_bytes(&[0u8; 32]).unwrap();
1030        let workdir = Path::new("../");
1031        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
1032        println!("{entry}");
1033    }
1034
1035    /// A BLAKE3 index round-trips through `to_file_with_hash_kind` / `from_file_with_hash_kind`
1036    /// with the thread-local kind set to SHA-1, entry lookups return `ObjectHash::Blake3`, and
1037    /// reading the file as SHA-256 (same width) or writing a cross-kind entry fails closed.
1038    #[test]
1039    fn blake3_lookup() {
1040        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1041        let temp_dir = tempfile::tempdir().unwrap();
1042        let path = temp_dir.path().join("index-blake3");
1043
1044        // Entry IDs are real blob IDs, as a status/commit flow would store them.
1045        let a = ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, b"a")
1046            .unwrap();
1047        let c = ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, b"c")
1048            .unwrap();
1049        let mut index = Index::new();
1050        index.add(IndexEntry::new_from_blob("a.txt".to_string(), a, 1));
1051        index.add(IndexEntry::new_from_blob("b/c.txt".to_string(), c, 3));
1052        index
1053            .to_file_with_hash_kind(HashKind::Blake3, &path)
1054            .unwrap();
1055
1056        let loaded = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
1057        assert_eq!(loaded.size(), 2);
1058        let got = loaded.get("a.txt", 0).expect("a.txt");
1059        assert_eq!(got.hash, a);
1060        assert_eq!(got.hash.kind(), HashKind::Blake3);
1061        assert_eq!(loaded.get("b/c.txt", 0).unwrap().hash, c);
1062        assert_eq!(
1063            loaded.tracked_files(),
1064            vec![PathBuf::from("a.txt"), PathBuf::from("b/c.txt")]
1065        );
1066
1067        // Same width, different algorithm: the checksum does not verify.
1068        let err = Index::from_file_with_hash_kind(HashKind::Sha256, &path)
1069            .err()
1070            .expect("same-width SHA-256 read must fail");
1071        assert!(matches!(err, GitError::InvalidIndexFile(_)), "{err:?}");
1072        // The thread-local (SHA-1) legacy reader cannot read a BLAKE3 index either.
1073        assert!(Index::from_file(&path).is_err());
1074
1075        // load/save with explicit kind.
1076        let missing =
1077            Index::load_with_hash_kind(HashKind::Blake3, temp_dir.path().join("none")).unwrap();
1078        assert_eq!(missing.size(), 0);
1079        let again = temp_dir.path().join("index-blake3-2");
1080        loaded
1081            .save_with_hash_kind(HashKind::Blake3, &again)
1082            .unwrap();
1083        assert_eq!(
1084            Index::load_with_hash_kind(HashKind::Blake3, &again)
1085                .unwrap()
1086                .size(),
1087            2
1088        );
1089
1090        // A cross-kind entry is refused when writing.
1091        let mut mixed = Index::new();
1092        mixed.add(IndexEntry::new_from_blob(
1093            "x.txt".to_string(),
1094            ObjectHash::new_for_kind(HashKind::Sha256, b"x"),
1095            1,
1096        ));
1097        let mixed_path = temp_dir.path().join("mixed");
1098        let err = mixed
1099            .to_file_with_hash_kind(HashKind::Blake3, &mixed_path)
1100            .expect_err("cross-kind entry must fail");
1101        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
1102        // ... and the destination is untouched: no partial file, and an existing valid index
1103        // is not truncated.
1104        assert!(!mixed_path.exists());
1105        let before = std::fs::read(&path).unwrap();
1106        assert!(
1107            mixed
1108                .to_file_with_hash_kind(HashKind::Blake3, &path)
1109                .is_err()
1110        );
1111        assert_eq!(std::fs::read(&path).unwrap(), before);
1112
1113        // Refreshing a BLAKE3 entry with another kind is refused and leaves it untouched;
1114        // the same kind recomputes the BLAKE3 blob ID of the file, which the entry
1115        // already carries, so the ID itself is unchanged.
1116        let work = temp_dir.path().join("work");
1117        std::fs::create_dir_all(&work).unwrap();
1118        std::fs::write(work.join("a.txt"), b"a").unwrap();
1119        let mut refreshed = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
1120        let err = refreshed
1121            .refresh_with_hash_kind(HashKind::Sha256, "a.txt", &work)
1122            .expect_err("cross-kind refresh must fail");
1123        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
1124        assert_eq!(refreshed.get("a.txt", 0).unwrap().hash, a);
1125        refreshed
1126            .refresh_with_hash_kind(HashKind::Blake3, "a.txt", &work)
1127            .unwrap();
1128        let got = refreshed.get("a.txt", 0).unwrap().hash;
1129        assert_eq!(got.kind(), HashKind::Blake3);
1130        assert_eq!(got, a);
1131    }
1132
1133    /// Regression test for <https://github.com/libra-tools/git-internal/issues/183>:
1134    /// `refresh_with_hash_kind` must recompute the blob ID — the digest of
1135    /// `"blob <size>\0" + content` — not the digest of the raw file bytes. An unchanged
1136    /// file whose entry carries the blob's real ID must be reported as unchanged and keep
1137    /// that ID; a modified file must flip to the new blob's ID.
1138    #[test]
1139    fn refresh_recomputes_the_blob_id_not_the_raw_file_hash() {
1140        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1141        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
1142            let temp_dir = tempfile::tempdir().unwrap();
1143            let work = temp_dir.path();
1144            let content = b"hello, git-internal\n".to_vec();
1145            std::fs::write(work.join("a.txt"), &content).unwrap();
1146
1147            let blob = Blob::from_content_bytes_with_kind(kind, content).unwrap();
1148            let mut index = Index::new();
1149            index.add(IndexEntry::new_from_file(Path::new("a.txt"), blob.id, work).unwrap());
1150
1151            // The unchanged file must not flip to "changed", and the entry keeps the blob ID.
1152            let changed = index.refresh_with_hash_kind(kind, "a.txt", work).unwrap();
1153            assert!(!changed, "{kind:?}: unchanged file reported as changed");
1154            let got = index.get("a.txt", 0).unwrap().hash;
1155            assert_eq!(got, blob.id, "{kind:?}: entry hash must stay the blob ID");
1156
1157            // A modified file is detected, and its entry hash becomes the new blob's ID.
1158            let new_content = b"changed\n".to_vec();
1159            std::fs::write(work.join("a.txt"), &new_content).unwrap();
1160            let changed = index.refresh_with_hash_kind(kind, "a.txt", work).unwrap();
1161            assert!(changed, "{kind:?}: modified file not reported as changed");
1162            let new_blob = Blob::from_content_bytes_with_kind(kind, new_content).unwrap();
1163            let got = index.get("a.txt", 0).unwrap().hash;
1164            assert_eq!(
1165                got, new_blob.id,
1166                "{kind:?}: entry hash must be the new blob ID"
1167            );
1168        }
1169    }
1170}