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::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 existing entry must already belong to `kind`: refreshing an entry of another kind
535    /// fails closed instead of silently replacing its ID with a digest of a different
536    /// algorithm.
537    pub fn refresh_with_hash_kind(
538        &mut self,
539        kind: HashKind,
540        file: impl AsRef<Path>,
541        workdir: &Path,
542    ) -> Result<bool, GitError> {
543        let path = file.as_ref();
544        let name = path
545            .to_str()
546            .ok_or(GitError::InvalidPathError(format!("{path:?}")))?;
547
548        if let Some(entry) = self.entries.get_mut(&(name.to_string(), 0)) {
549            entry.hash.ensure_kind(kind)?;
550            let abs_path = workdir.join(path);
551            let meta = fs::symlink_metadata(&abs_path)?;
552            let new_ctime = Time::from_system_time(index_ctime(&meta));
553            let new_mtime = Time::from_system_time(index_mtime(&meta));
554            let new_size = meta.len() as u32;
555
556            // re-calculate the content hash with the repository kind
557            let mut file = File::open(&abs_path)?;
558            let mut hasher = HashAlgorithm::new_for_kind(kind);
559            io::copy(&mut file, &mut hasher)?;
560            let new_hash = hasher.finalize_object_hash();
561
562            // refresh index
563            if entry.ctime != new_ctime
564                || entry.mtime != new_mtime
565                || entry.size != new_size
566                || entry.hash != new_hash
567            {
568                entry.ctime = new_ctime;
569                entry.mtime = new_mtime;
570                entry.size = new_size;
571                entry.hash = new_hash;
572                return Ok(true);
573            }
574        }
575        Ok(false)
576    }
577}
578
579impl Default for Index {
580    fn default() -> Self {
581        Self::new()
582    }
583}
584
585impl Index {
586    /// Load index. If it does not exist, return an empty index.
587    ///
588    /// Uses the thread-local [`HashKind`]; see [`Index::load_with_hash_kind`].
589    pub fn load(index_file: impl AsRef<Path>) -> Result<Self, GitError> {
590        Self::load_with_hash_kind(get_hash_kind(), index_file)
591    }
592
593    /// Load index for an explicit repository `kind`. If it does not exist, return an empty index.
594    pub fn load_with_hash_kind(
595        kind: HashKind,
596        index_file: impl AsRef<Path>,
597    ) -> Result<Self, GitError> {
598        let path = index_file.as_ref();
599        if !path.exists() {
600            return Ok(Index::new());
601        }
602        Index::from_file_with_hash_kind(kind, path)
603    }
604
605    pub fn update(&mut self, entry: IndexEntry) {
606        self.add(entry)
607    }
608
609    pub fn add(&mut self, entry: IndexEntry) {
610        self.entries
611            .insert((entry.name.clone(), entry.flags.stage), entry);
612    }
613
614    pub fn remove(&mut self, name: &str, stage: u8) -> Option<IndexEntry> {
615        self.entries.remove(&(name.to_string(), stage))
616    }
617
618    pub fn get(&self, name: &str, stage: u8) -> Option<&IndexEntry> {
619        self.entries.get(&(name.to_string(), stage))
620    }
621
622    pub fn tracked(&self, name: &str, stage: u8) -> bool {
623        self.entries.contains_key(&(name.to_string(), stage))
624    }
625
626    pub fn get_hash(&self, file: &str, stage: u8) -> Option<ObjectHash> {
627        self.get(file, stage).map(|entry| entry.hash)
628    }
629
630    pub fn verify_hash(&self, file: &str, stage: u8, hash: &ObjectHash) -> bool {
631        let inner_hash = self.get_hash(file, stage);
632        if let Some(inner_hash) = inner_hash {
633            &inner_hash == hash
634        } else {
635            false
636        }
637    }
638    /// is file modified after last `add` (need hash to confirm content change)
639    /// - `workdir` is used to rebuild absolute file path
640    pub fn is_modified(&self, file: &str, stage: u8, workdir: &Path) -> bool {
641        if let Some(entry) = self.get(file, stage) {
642            let path_abs = workdir.join(file);
643            let meta = path_abs.symlink_metadata().unwrap();
644            // TODO more fields
645            let same = entry.ctime == Time::from_system_time(index_ctime(&meta))
646                && entry.mtime == Time::from_system_time(index_mtime(&meta))
647                && entry.size == meta.len() as u32;
648
649            !same
650        } else {
651            panic!("File not found in index");
652        }
653    }
654
655    /// Get all entries with the same stage
656    pub fn tracked_entries(&self, stage: u8) -> Vec<&IndexEntry> {
657        // ? should use stage or not
658        self.entries
659            .iter()
660            .filter(|(_, entry)| entry.flags.stage == stage)
661            .map(|(_, entry)| entry)
662            .collect()
663    }
664
665    /// Get all tracked files(stage = 0)
666    pub fn tracked_files(&self) -> Vec<PathBuf> {
667        self.tracked_entries(0)
668            .iter()
669            .map(|entry| PathBuf::from(&entry.name))
670            .collect()
671    }
672
673    /// Judge if the file(s) of `dir` is in the index
674    /// - false if `dir` is a file
675    pub fn contains_dir_file(&self, dir: &str) -> bool {
676        let dir = Path::new(dir);
677        self.entries.iter().any(|((name, _), _)| {
678            let path = Path::new(name);
679            path.starts_with(dir) && path != dir // TODO change to is_sub_path!
680        })
681    }
682
683    /// remove all files in `dir` from index
684    /// - do nothing if `dir` is a file
685    pub fn remove_dir_files(&mut self, dir: &str) -> Vec<String> {
686        let dir = Path::new(dir);
687        let mut removed = Vec::new();
688        self.entries.retain(|(name, _), _| {
689            let path = Path::new(name);
690            if path.starts_with(dir) && path != dir {
691                removed.push(name.clone());
692                false
693            } else {
694                true
695            }
696        });
697        removed
698    }
699
700    /// saved to index file (thread-local [`HashKind`]; see [`Index::save_with_hash_kind`])
701    pub fn save(&self, index_file: impl AsRef<Path>) -> Result<(), GitError> {
702        self.to_file(index_file)
703    }
704
705    /// Save to an index file for an explicit repository `kind`.
706    pub fn save_with_hash_kind(
707        &self,
708        kind: HashKind,
709        index_file: impl AsRef<Path>,
710    ) -> Result<(), GitError> {
711        self.to_file_with_hash_kind(kind, index_file)
712    }
713}
714
715#[cfg(test)]
716mod tests {
717    use std::io::Cursor;
718
719    use super::*;
720    use crate::hash::{HashKind, set_hash_kind_for_test};
721
722    /// Test Time conversion
723    #[test]
724    fn test_time() {
725        let time = Time {
726            seconds: 0,
727            nanos: 0,
728        };
729        let system_time = time.to_system_time();
730        let new_time = Time::from_system_time(system_time);
731        assert_eq!(time, new_time);
732    }
733
734    /// Test Flags conversion
735    #[test]
736    fn test_check_header() {
737        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
738        source.push("tests/data/index/index-2");
739
740        let file = File::open(source).unwrap();
741        let (version, entries) = Index::check_header(&mut BufReader::new(file)).unwrap();
742        assert_eq!(version, 2);
743        assert_eq!(entries, 2);
744    }
745
746    /// Test IndexEntry creation
747    #[test]
748    fn test_index() {
749        let _guard = set_hash_kind_for_test(HashKind::Sha1);
750        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
751        source.push("tests/data/index/index-760");
752
753        let index = Index::from_file(source).unwrap();
754        assert_eq!(index.size(), 760);
755        for entry in index.entries.values() {
756            println!("{entry}");
757        }
758    }
759
760    /// Test IndexEntry creation with SHA256
761    #[test]
762    fn test_index_sha256() {
763        let _guard = set_hash_kind_for_test(HashKind::Sha256);
764        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
765        source.push("tests/data/index/index-9-256");
766
767        let index = Index::from_file(source).unwrap();
768        assert_eq!(index.size(), 9);
769        for entry in index.entries.values() {
770            println!("{entry}");
771        }
772    }
773
774    /// Flags bit packing/unpacking covers all fields and enforces name length limit.
775    #[test]
776    fn flags_round_trip_and_length_limit() {
777        let mut flags = Flags {
778            assume_valid: true,
779            extended: true,
780            stage: 2,
781            name_length: 0x0ABC,
782            skip_worktree: false,
783            intent_to_add: false,
784        };
785        let packed: u16 = (&flags).try_into().expect("should pack");
786        let unpacked = Flags::from(packed);
787        assert_eq!(unpacked.assume_valid, flags.assume_valid);
788        assert_eq!(unpacked.extended, flags.extended);
789        assert_eq!(unpacked.stage, flags.stage);
790        assert_eq!(unpacked.name_length, flags.name_length);
791
792        flags.name_length = 0x1FFF;
793        let overflow: Result<u16, _> = (&flags).try_into();
794        assert!(overflow.is_err(), "length overflow should err");
795    }
796
797    /// IndexEntry::new_from_blob populates fields and sets flags length.
798    #[test]
799    fn index_entry_new_from_blob_populates_fields() {
800        let hash = ObjectHash::from_bytes(&[0u8; 20]).unwrap();
801        let entry = IndexEntry::new_from_blob("file.txt".to_string(), hash, 42);
802        assert_eq!(entry.name, "file.txt");
803        assert_eq!(entry.size, 42);
804        assert_eq!(entry.hash, hash);
805        assert_eq!(entry.flags.name_length, "file.txt".len() as u16);
806        assert_eq!(entry.mode, 0o100644);
807    }
808
809    /// Index container operations: add/get/tracked/dir helpers.
810    #[test]
811    fn index_add_and_query_helpers() {
812        let _guard = set_hash_kind_for_test(HashKind::Sha1);
813        let mut index = Index::new();
814        let hash = ObjectHash::from_bytes(&[1u8; 20]).unwrap();
815        let entry = IndexEntry::new_from_blob("a/b.txt".to_string(), hash, 10);
816        index.add(entry);
817
818        // get finds stage-0 by name
819        let got = index.get("a/b.txt", 0).expect("entry exists");
820        assert_eq!(got.hash, hash);
821
822        // tracked_entries/files return stage-0 paths
823        let tracked = index.tracked_entries(0);
824        assert_eq!(tracked.len(), 1);
825        let files = index.tracked_files();
826        assert_eq!(files, vec![PathBuf::from("a/b.txt")]);
827
828        // contains_dir_file true for subpath, false for exact file
829        assert!(index.contains_dir_file("a"));
830        assert!(!index.contains_dir_file("a/b.txt"));
831
832        // remove_dir_files removes under dir and returns removed names
833        let removed = index.remove_dir_files("a");
834        assert_eq!(removed, vec!["a/b.txt".to_string()]);
835        assert!(index.get("a/b.txt", 0).is_none());
836    }
837
838    /// check_header should reject bad magic/versions and accept valid headers.
839    #[test]
840    fn check_header_validation() {
841        // valid header: "DIRC" + version 2 + 0 entries
842        let mut valid = Cursor::new(b"DIRC\0\0\0\x02\0\0\0\0".to_vec());
843        let (version, entries) = Index::check_header(&mut valid).expect("valid header");
844        assert_eq!(version, 2);
845        assert_eq!(entries, 0);
846
847        // v3 is accepted: it only adds an optional per-entry extended flags word
848        let mut v3 = Cursor::new(b"DIRC\0\0\0\x03\0\0\0\0".to_vec());
849        let (version, entries) = Index::check_header(&mut v3).expect("v3 header");
850        assert_eq!(version, 3);
851        assert_eq!(entries, 0);
852
853        // bad magic
854        let mut bad_magic = Cursor::new(b"XXXX\0\0\0\x02\0\0\0\0".to_vec());
855        assert!(Index::check_header(&mut bad_magic).is_err());
856
857        // unsupported versions (1 and 4) fail closed
858        let mut bad_version = Cursor::new(b"DIRC\0\0\0\x01\0\0\0\0".to_vec());
859        assert!(Index::check_header(&mut bad_version).is_err());
860        let mut v4 = Cursor::new(b"DIRC\0\0\0\x04\0\0\0\0".to_vec());
861        assert!(Index::check_header(&mut v4).is_err());
862    }
863
864    /// Test saving Index to file
865    #[test]
866    fn test_index_to_file() {
867        let temp_dir = tempfile::tempdir().unwrap();
868        let temp_path = temp_dir.path().join("index-760");
869
870        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
871        source.push("tests/data/index/index-760");
872
873        let index = Index::from_file(source).unwrap();
874        index.to_file(&temp_path).unwrap();
875        let new_index = Index::from_file(temp_path).unwrap();
876        assert_eq!(index.size(), new_index.size());
877    }
878
879    /// A real index v3 generated by git 2.55.0 (SHA-1) with one skip-worktree
880    /// entry (`a.txt`): header v3, entry flags `0x4005`, extended word `0x4000`.
881    const GIT_V3_SKIP_WORKTREE_FIXTURE: [u8; 104] = [
882        0x44, 0x49, 0x52, 0x43, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x6a, 0xaf, 0x4a,
883        0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x6a, 0xaf, 0x4a, 0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x00, 0x00,
884        0x00, 0x3a, 0x06, 0x98, 0x73, 0xd9, 0x00, 0x00, 0x81, 0xa4, 0x00, 0x00, 0x03, 0xe8, 0x00,
885        0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x03, 0x45, 0xb9, 0x83, 0xbe, 0x36, 0xb7, 0x3c, 0x07,
886        0x88, 0xdc, 0x9c, 0xbc, 0xb7, 0x6c, 0xbb, 0x80, 0xfc, 0x7b, 0xb0, 0x57, 0x40, 0x05, 0x40,
887        0x00, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x00, 0x00, 0x32, 0xd2, 0xa6, 0x5d, 0x73, 0x12,
888        0x16, 0x5a, 0x7f, 0x63, 0xda, 0x76, 0xd4, 0xd0, 0xaa, 0xc8, 0xab, 0xc4, 0xc0, 0x06,
889    ];
890
891    /// A git-generated v3 index with `CE_SKIP_WORKTREE` reads back with the bit set.
892    #[test]
893    fn index_reads_git_v3_skip_worktree_fixture() {
894        let _guard = set_hash_kind_for_test(HashKind::Sha1);
895        let temp_dir = tempfile::tempdir().unwrap();
896        let path = temp_dir.path().join("index-v3-git");
897        std::fs::write(&path, GIT_V3_SKIP_WORKTREE_FIXTURE).unwrap();
898
899        let index = Index::from_file(&path).unwrap();
900        assert_eq!(index.size(), 1);
901        let entry = index.get("a.txt", 0).expect("fixture entry");
902        assert_eq!(entry.mode, 0o100644);
903        assert!(entry.flags.skip_worktree, "CE_SKIP_WORKTREE must be set");
904        assert!(!entry.flags.intent_to_add);
905    }
906
907    /// An unknown extended bit fails closed instead of being silently dropped.
908    #[test]
909    fn index_rejects_unknown_extended_bit() {
910        let _guard = set_hash_kind_for_test(HashKind::Sha1);
911        let temp_dir = tempfile::tempdir().unwrap();
912        let path = temp_dir.path().join("index-bad-extended");
913
914        let mut raw = GIT_V3_SKIP_WORKTREE_FIXTURE.to_vec();
915        raw[74] = 0x10; // extended word 0x4000 -> 0x1000 (unknown bit)
916        raw[75] = 0x00;
917        let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha1);
918        hasher.update(&raw[..raw.len() - 20]);
919        let checksum = hasher.finalize_object_hash();
920        raw.truncate(raw.len() - 20);
921        raw.extend_from_slice(checksum.as_ref());
922        std::fs::write(&path, &raw).unwrap();
923
924        let error = match Index::from_file(&path) {
925            Ok(_) => panic!("an index with an unknown extended bit must fail closed"),
926            Err(error) => error,
927        };
928        assert!(
929            matches!(error, GitError::InvalidIndexFile(_)),
930            "unexpected error: {error:?}"
931        );
932    }
933
934    /// Writing extended flags forces index v3 and survives a round trip.
935    #[test]
936    fn index_v3_round_trip_preserves_extended_flags() {
937        let _guard = set_hash_kind_for_test(HashKind::Sha1);
938        let temp_dir = tempfile::tempdir().unwrap();
939        let path = temp_dir.path().join("index-v3-round-trip");
940
941        let mut index = Index::new();
942        let hash = ObjectHash::from_bytes(&[0x11u8; 20]).unwrap();
943        let mut skip = IndexEntry::new_from_blob("skip.txt".to_string(), hash, 7);
944        skip.flags.skip_worktree = true;
945        index.update(skip);
946        let hash = ObjectHash::from_bytes(&[0x22u8; 20]).unwrap();
947        let mut ita = IndexEntry::new_from_blob("ita.txt".to_string(), hash, 9);
948        ita.flags.intent_to_add = true;
949        index.update(ita);
950
951        index.to_file(&path).unwrap();
952        let raw = std::fs::read(&path).unwrap();
953        assert_eq!(&raw[..4], b"DIRC");
954        assert_eq!(
955            u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]),
956            3,
957            "extended flags must force version 3"
958        );
959
960        let loaded = Index::from_file(&path).unwrap();
961        let skip = loaded.get("skip.txt", 0).unwrap();
962        assert!(skip.flags.skip_worktree);
963        assert!(!skip.flags.intent_to_add);
964        let ita = loaded.get("ita.txt", 0).unwrap();
965        assert!(ita.flags.intent_to_add);
966        assert!(!ita.flags.skip_worktree);
967    }
968
969    /// Without extended bits the writer keeps emitting v2.
970    #[test]
971    fn index_without_extended_flags_stays_v2() {
972        let _guard = set_hash_kind_for_test(HashKind::Sha1);
973        let temp_dir = tempfile::tempdir().unwrap();
974        let path = temp_dir.path().join("index-v2-round-trip");
975
976        let mut index = Index::new();
977        let hash = ObjectHash::from_bytes(&[0x33u8; 20]).unwrap();
978        index.update(IndexEntry::new_from_blob("plain.txt".to_string(), hash, 3));
979        index.to_file(&path).unwrap();
980
981        let raw = std::fs::read(&path).unwrap();
982        assert_eq!(u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]), 2);
983        let loaded = Index::from_file(&path).unwrap();
984        let entry = loaded.get("plain.txt", 0).unwrap();
985        assert!(!entry.flags.skip_worktree);
986        assert!(!entry.flags.intent_to_add);
987    }
988
989    /// Test IndexEntry creation from file
990    #[test]
991    fn test_index_entry_create() {
992        let _guard = set_hash_kind_for_test(HashKind::Sha1);
993        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
994        source.push("Cargo.toml");
995
996        let file = Path::new(source.as_path()); // use as a normal file
997        let hash = ObjectHash::from_bytes(&[0; 20]).unwrap();
998        let workdir = Path::new("../");
999        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
1000        println!("{entry}");
1001    }
1002
1003    /// Test IndexEntry creation from file with SHA256
1004    #[test]
1005    fn test_index_entry_create_sha256() {
1006        let _guard = set_hash_kind_for_test(HashKind::Sha256);
1007        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1008        source.push("Cargo.toml");
1009
1010        let file = Path::new(source.as_path());
1011        let hash = ObjectHash::from_bytes(&[0u8; 32]).unwrap();
1012        let workdir = Path::new("../");
1013        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
1014        println!("{entry}");
1015    }
1016
1017    /// A BLAKE3 index round-trips through `to_file_with_hash_kind` / `from_file_with_hash_kind`
1018    /// with the thread-local kind set to SHA-1, entry lookups return `ObjectHash::Blake3`, and
1019    /// reading the file as SHA-256 (same width) or writing a cross-kind entry fails closed.
1020    #[test]
1021    fn blake3_lookup() {
1022        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1023        let temp_dir = tempfile::tempdir().unwrap();
1024        let path = temp_dir.path().join("index-blake3");
1025
1026        let a = ObjectHash::new_for_kind(HashKind::Blake3, b"a");
1027        let c = ObjectHash::new_for_kind(HashKind::Blake3, b"c");
1028        let mut index = Index::new();
1029        index.add(IndexEntry::new_from_blob("a.txt".to_string(), a, 1));
1030        index.add(IndexEntry::new_from_blob("b/c.txt".to_string(), c, 3));
1031        index
1032            .to_file_with_hash_kind(HashKind::Blake3, &path)
1033            .unwrap();
1034
1035        let loaded = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
1036        assert_eq!(loaded.size(), 2);
1037        let got = loaded.get("a.txt", 0).expect("a.txt");
1038        assert_eq!(got.hash, a);
1039        assert_eq!(got.hash.kind(), HashKind::Blake3);
1040        assert_eq!(loaded.get("b/c.txt", 0).unwrap().hash, c);
1041        assert_eq!(
1042            loaded.tracked_files(),
1043            vec![PathBuf::from("a.txt"), PathBuf::from("b/c.txt")]
1044        );
1045
1046        // Same width, different algorithm: the checksum does not verify.
1047        let err = Index::from_file_with_hash_kind(HashKind::Sha256, &path)
1048            .err()
1049            .expect("same-width SHA-256 read must fail");
1050        assert!(matches!(err, GitError::InvalidIndexFile(_)), "{err:?}");
1051        // The thread-local (SHA-1) legacy reader cannot read a BLAKE3 index either.
1052        assert!(Index::from_file(&path).is_err());
1053
1054        // load/save with explicit kind.
1055        let missing =
1056            Index::load_with_hash_kind(HashKind::Blake3, temp_dir.path().join("none")).unwrap();
1057        assert_eq!(missing.size(), 0);
1058        let again = temp_dir.path().join("index-blake3-2");
1059        loaded
1060            .save_with_hash_kind(HashKind::Blake3, &again)
1061            .unwrap();
1062        assert_eq!(
1063            Index::load_with_hash_kind(HashKind::Blake3, &again)
1064                .unwrap()
1065                .size(),
1066            2
1067        );
1068
1069        // A cross-kind entry is refused when writing.
1070        let mut mixed = Index::new();
1071        mixed.add(IndexEntry::new_from_blob(
1072            "x.txt".to_string(),
1073            ObjectHash::new_for_kind(HashKind::Sha256, b"x"),
1074            1,
1075        ));
1076        let mixed_path = temp_dir.path().join("mixed");
1077        let err = mixed
1078            .to_file_with_hash_kind(HashKind::Blake3, &mixed_path)
1079            .expect_err("cross-kind entry must fail");
1080        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
1081        // ... and the destination is untouched: no partial file, and an existing valid index
1082        // is not truncated.
1083        assert!(!mixed_path.exists());
1084        let before = std::fs::read(&path).unwrap();
1085        assert!(
1086            mixed
1087                .to_file_with_hash_kind(HashKind::Blake3, &path)
1088                .is_err()
1089        );
1090        assert_eq!(std::fs::read(&path).unwrap(), before);
1091
1092        // Refreshing a BLAKE3 entry with another kind is refused and leaves it untouched;
1093        // the same kind recomputes a BLAKE3 content hash.
1094        let work = temp_dir.path().join("work");
1095        std::fs::create_dir_all(&work).unwrap();
1096        std::fs::write(work.join("a.txt"), b"a").unwrap();
1097        let mut refreshed = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
1098        let err = refreshed
1099            .refresh_with_hash_kind(HashKind::Sha256, "a.txt", &work)
1100            .expect_err("cross-kind refresh must fail");
1101        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
1102        assert_eq!(refreshed.get("a.txt", 0).unwrap().hash, a);
1103        refreshed
1104            .refresh_with_hash_kind(HashKind::Blake3, "a.txt", &work)
1105            .unwrap();
1106        let got = refreshed.get("a.txt", 0).unwrap().hash;
1107        assert_eq!(got.kind(), HashKind::Blake3);
1108        assert_eq!(got, a);
1109    }
1110}