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#[derive(Debug)]
108pub struct Flags {
109    pub assume_valid: bool,
110    pub extended: bool,   // must be 0 in v2
111    pub stage: u8,        // 2-bit during merge
112    pub name_length: u16, // 12-bit
113}
114
115impl From<u16> for Flags {
116    fn from(flags: u16) -> Self {
117        Flags {
118            assume_valid: flags & 0x8000 != 0,
119            extended: flags & 0x4000 != 0,
120            stage: ((flags & 0x3000) >> 12) as u8,
121            name_length: flags & 0xFFF,
122        }
123    }
124}
125
126impl TryInto<u16> for &Flags {
127    type Error = &'static str;
128    fn try_into(self) -> Result<u16, Self::Error> {
129        let mut flags = 0u16;
130        if self.assume_valid {
131            flags |= 0x8000; // 16
132        }
133        if self.extended {
134            flags |= 0x4000; // 15
135        }
136        flags |= (self.stage as u16) << 12; // 13-14
137        if self.name_length > 0xFFF {
138            return Err("Name length is too long");
139        }
140        flags |= self.name_length; // 0-11
141        Ok(flags)
142    }
143}
144
145impl Flags {
146    pub fn new(name_len: u16) -> Self {
147        Flags {
148            assume_valid: true,
149            extended: false,
150            stage: 0,
151            name_length: name_len,
152        }
153    }
154}
155
156/// An entry in the Git index file.
157pub struct IndexEntry {
158    pub ctime: Time,
159    pub mtime: Time,
160    pub dev: u32,  // 0 for windows
161    pub ino: u32,  // 0 for windows
162    pub mode: u32, // 0o100644 // 4-bit object type + 3-bit unused + 9-bit unix permission
163    pub uid: u32,  // 0 for windows
164    pub gid: u32,  // 0 for windows
165    pub size: u32,
166    pub hash: ObjectHash,
167    pub flags: Flags,
168    pub name: String,
169}
170impl Display for IndexEntry {
171    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
172        write!(
173            f,
174            "IndexEntry {{ ctime: {}, mtime: {}, dev: {}, ino: {}, mode: {:o}, uid: {}, gid: {}, size: {}, hash: {}, flags: {:?}, name: {} }}",
175            self.ctime,
176            self.mtime,
177            self.dev,
178            self.ino,
179            self.mode,
180            self.uid,
181            self.gid,
182            self.size,
183            self.hash,
184            self.flags,
185            self.name
186        )
187    }
188}
189
190impl IndexEntry {
191    /** Metadata must be got by [fs::symlink_metadata] to avoid following symlink */
192    pub fn new(meta: &fs::Metadata, hash: ObjectHash, name: String) -> Self {
193        let mut entry = IndexEntry {
194            ctime: Time::from_system_time(index_ctime(meta)),
195            mtime: Time::from_system_time(index_mtime(meta)),
196            dev: 0,
197            ino: 0,
198            uid: 0,
199            gid: 0,
200            size: meta.len() as u32,
201            hash,
202            flags: Flags::new(name.len() as u16),
203            name,
204            mode: 0o100644,
205        };
206        #[cfg(unix)]
207        {
208            entry.dev = meta.dev() as u32;
209            entry.ino = meta.ino() as u32;
210            entry.uid = meta.uid();
211            entry.gid = meta.gid();
212
213            entry.mode = match meta.mode() & 0o170000/* file mode */ {
214                0o100000 => {
215                    match meta.mode() & 0o111 {
216                        0 => 0o100644, // no execute permission
217                        _ => 0o100755, // with execute permission
218                    }
219                }
220                0o120000 => 0o120000, // symlink
221                _ =>  entry.mode, // keep the original mode
222            }
223        }
224        #[cfg(windows)]
225        {
226            if meta.is_symlink() {
227                entry.mode = 0o120000;
228            }
229        }
230        entry
231    }
232
233    /// - `file`: **to workdir path**
234    /// - `workdir`: absolute or relative path
235    pub fn new_from_file(file: &Path, hash: ObjectHash, workdir: &Path) -> io::Result<Self> {
236        let name = file.to_str().unwrap().to_string();
237        let file_abs = workdir.join(file);
238        let meta = fs::symlink_metadata(file_abs)?; // without following symlink
239        let index = IndexEntry::new(&meta, hash, name);
240        Ok(index)
241    }
242
243    /// Create IndexEntry from blob object
244    pub fn new_from_blob(name: String, hash: ObjectHash, size: u32) -> Self {
245        IndexEntry {
246            ctime: Time {
247                seconds: 0,
248                nanos: 0,
249            },
250            mtime: Time {
251                seconds: 0,
252                nanos: 0,
253            },
254            dev: 0,
255            ino: 0,
256            mode: 0o100644,
257            uid: 0,
258            gid: 0,
259            size,
260            hash,
261            flags: Flags::new(name.len() as u16),
262            name,
263        }
264    }
265}
266
267/// see [index-format](https://git-scm.com/docs/index-format)
268/// <br> to Working Dir relative path
269pub struct Index {
270    entries: BTreeMap<(String, u8), IndexEntry>,
271}
272
273impl Index {
274    pub fn new() -> Self {
275        Index {
276            entries: BTreeMap::new(),
277        }
278    }
279
280    fn check_header(file: &mut impl Read) -> Result<u32, GitError> {
281        let mut magic = [0; 4];
282        file.read_exact(&mut magic)?;
283        if magic != *b"DIRC" {
284            return Err(GitError::InvalidIndexHeader(
285                String::from_utf8_lossy(&magic).to_string(),
286            ));
287        }
288
289        let version = file.read_u32::<BigEndian>()?;
290        // only support v2 now
291        if version != 2 {
292            return Err(GitError::InvalidIndexHeader(version.to_string()));
293        }
294
295        let entries = file.read_u32::<BigEndian>()?;
296        Ok(entries)
297    }
298
299    pub fn size(&self) -> usize {
300        self.entries.len()
301    }
302
303    /// Read an index file using the thread-local [`HashKind`]; compatibility wrapper around
304    /// [`Index::from_file_with_hash_kind`].
305    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, GitError> {
306        Self::from_file_with_hash_kind(get_hash_kind(), path)
307    }
308
309    /// Read an index file whose entry IDs and checksum belong to the explicit repository
310    /// `kind`. The checksum is verified with `kind`, so an index written for another kind
311    /// (even one of the same width) fails closed instead of being misread.
312    pub fn from_file_with_hash_kind(
313        kind: HashKind,
314        path: impl AsRef<Path>,
315    ) -> Result<Self, GitError> {
316        let file = File::open(path.as_ref())?; // read-only
317        let total_size = file.metadata()?.len();
318        let file = &mut Wrapper::new_with_kind(BufReader::new(file), kind); // TODO move Wrapper & utils to a common module
319
320        let num = Index::check_header(file)?;
321        let mut index = Index::new();
322
323        for _ in 0..num {
324            let mut entry = IndexEntry {
325                ctime: Time::from_stream(file)?,
326                mtime: Time::from_stream(file)?,
327                dev: file.read_u32::<BigEndian>()?, //utils::read_u32_be(file)?,
328                ino: file.read_u32::<BigEndian>()?,
329                mode: file.read_u32::<BigEndian>()?,
330                uid: file.read_u32::<BigEndian>()?,
331                gid: file.read_u32::<BigEndian>()?,
332                size: file.read_u32::<BigEndian>()?,
333                hash: utils::read_sha_for_kind(kind, file)?,
334                flags: Flags::from(file.read_u16::<BigEndian>()?),
335                name: String::new(),
336            };
337            let name_len = entry.flags.name_length as usize;
338            let mut name = vec![0; name_len];
339            file.read_exact(&mut name)?;
340            // The exact encoding is undefined, but the '.' and '/' characters are encoded in 7-bit ASCII
341            entry.name =
342                String::from_utf8(name).map_err(|e| GitError::ConversionError(e.to_string()))?; // TODO check the encoding
343            index
344                .entries
345                .insert((entry.name.clone(), entry.flags.stage), entry);
346
347            // 1-8 nul bytes as necessary to pad the entry to a multiple of eight bytes
348            // while keeping the name NUL-terminated.
349            let hash_len = kind.size();
350            let entry_len = hash_len + 2 + name_len;
351            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
352            utils::read_bytes(file, padding)?;
353        }
354
355        // Extensions
356        while file.bytes_read() + kind.size() < total_size as usize {
357            // The remaining bytes must be the index checksum (size = kind.size())
358            let sign = utils::read_bytes(file, 4)?;
359            println!(
360                "{:?}",
361                String::from_utf8(sign.clone())
362                    .map_err(|e| GitError::ConversionError(e.to_string()))?
363            );
364            // If the first byte is 'A'...'Z' the extension is optional and can be ignored.
365            if sign[0] >= b'A' && sign[0] <= b'Z' {
366                // Optional extension
367                let size = file.read_u32::<BigEndian>()?;
368                utils::read_bytes(file, size as usize)?; // Ignore the extension
369            } else {
370                // 'link' or 'sdir' extension
371                return Err(GitError::InvalidIndexFile(
372                    "Unsupported extension".to_string(),
373                ));
374            }
375        }
376
377        // check sum
378        let file_hash = file.final_hash();
379        let check_sum = utils::read_sha_for_kind(kind, file)?;
380        if file_hash != check_sum {
381            return Err(GitError::InvalidIndexFile("Check sum failed".to_string()));
382        }
383        assert_eq!(index.size(), num as usize);
384        Ok(index)
385    }
386
387    /// Write the index using the thread-local [`HashKind`]; compatibility wrapper around
388    /// [`Index::to_file_with_hash_kind`].
389    pub fn to_file(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
390        self.to_file_with_hash_kind(get_hash_kind(), path)
391    }
392
393    /// Write the index for an explicit repository `kind`: every entry ID must belong to
394    /// `kind` (a cross-kind entry fails closed) and the trailing checksum is computed with it.
395    pub fn to_file_with_hash_kind(
396        &self,
397        kind: HashKind,
398        path: impl AsRef<Path>,
399    ) -> Result<(), GitError> {
400        // Validate every entry before touching the destination, so a cross-kind entry can
401        // neither truncate an existing valid index nor leave a partial file behind.
402        for entry in self.entries.values() {
403            entry.hash.ensure_kind(kind)?;
404        }
405        let mut file = File::create(path)?;
406        let mut hash = HashAlgorithm::new_for_kind(kind);
407
408        let mut header = Vec::new();
409        header.write_all(b"DIRC")?;
410        header.write_u32::<BigEndian>(2u32)?; // version 2
411        header.write_u32::<BigEndian>(self.entries.len() as u32)?;
412        file.write_all(&header)?;
413        hash.update(&header);
414
415        for entry in self.entries.values() {
416            let mut entry_bytes = Vec::new();
417            entry_bytes.write_u32::<BigEndian>(entry.ctime.seconds)?;
418            entry_bytes.write_u32::<BigEndian>(entry.ctime.nanos)?;
419            entry_bytes.write_u32::<BigEndian>(entry.mtime.seconds)?;
420            entry_bytes.write_u32::<BigEndian>(entry.mtime.nanos)?;
421            entry_bytes.write_u32::<BigEndian>(entry.dev)?;
422            entry_bytes.write_u32::<BigEndian>(entry.ino)?;
423            entry_bytes.write_u32::<BigEndian>(entry.mode)?;
424            entry_bytes.write_u32::<BigEndian>(entry.uid)?;
425            entry_bytes.write_u32::<BigEndian>(entry.gid)?;
426            entry_bytes.write_u32::<BigEndian>(entry.size)?;
427            entry_bytes.write_all(entry.hash.as_ref())?;
428            entry_bytes.write_u16::<BigEndian>((&entry.flags).try_into().unwrap())?;
429            entry_bytes.write_all(entry.name.as_bytes())?;
430            let hash_len = kind.size();
431            let entry_len = hash_len + 2 + entry.name.len();
432            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
433            entry_bytes.write_all(&vec![0; padding])?;
434            file.write_all(&entry_bytes)?;
435            hash.update(&entry_bytes);
436        }
437
438        // Extensions
439
440        // check sum
441        let file_hash = hash.finalize_object_hash();
442        file.write_all(file_hash.as_ref())?;
443        Ok(())
444    }
445
446    /// Refresh one entry using the thread-local [`HashKind`]; compatibility wrapper around
447    /// [`Index::refresh_with_hash_kind`].
448    pub fn refresh(&mut self, file: impl AsRef<Path>, workdir: &Path) -> Result<bool, GitError> {
449        self.refresh_with_hash_kind(get_hash_kind(), file, workdir)
450    }
451
452    /// Refresh one entry's stat data and content hash for an explicit repository `kind`.
453    ///
454    /// The existing entry must already belong to `kind`: refreshing an entry of another kind
455    /// fails closed instead of silently replacing its ID with a digest of a different
456    /// algorithm.
457    pub fn refresh_with_hash_kind(
458        &mut self,
459        kind: HashKind,
460        file: impl AsRef<Path>,
461        workdir: &Path,
462    ) -> Result<bool, GitError> {
463        let path = file.as_ref();
464        let name = path
465            .to_str()
466            .ok_or(GitError::InvalidPathError(format!("{path:?}")))?;
467
468        if let Some(entry) = self.entries.get_mut(&(name.to_string(), 0)) {
469            entry.hash.ensure_kind(kind)?;
470            let abs_path = workdir.join(path);
471            let meta = fs::symlink_metadata(&abs_path)?;
472            let new_ctime = Time::from_system_time(index_ctime(&meta));
473            let new_mtime = Time::from_system_time(index_mtime(&meta));
474            let new_size = meta.len() as u32;
475
476            // re-calculate the content hash with the repository kind
477            let mut file = File::open(&abs_path)?;
478            let mut hasher = HashAlgorithm::new_for_kind(kind);
479            io::copy(&mut file, &mut hasher)?;
480            let new_hash = hasher.finalize_object_hash();
481
482            // refresh index
483            if entry.ctime != new_ctime
484                || entry.mtime != new_mtime
485                || entry.size != new_size
486                || entry.hash != new_hash
487            {
488                entry.ctime = new_ctime;
489                entry.mtime = new_mtime;
490                entry.size = new_size;
491                entry.hash = new_hash;
492                return Ok(true);
493            }
494        }
495        Ok(false)
496    }
497}
498
499impl Default for Index {
500    fn default() -> Self {
501        Self::new()
502    }
503}
504
505impl Index {
506    /// Load index. If it does not exist, return an empty index.
507    ///
508    /// Uses the thread-local [`HashKind`]; see [`Index::load_with_hash_kind`].
509    pub fn load(index_file: impl AsRef<Path>) -> Result<Self, GitError> {
510        Self::load_with_hash_kind(get_hash_kind(), index_file)
511    }
512
513    /// Load index for an explicit repository `kind`. If it does not exist, return an empty index.
514    pub fn load_with_hash_kind(
515        kind: HashKind,
516        index_file: impl AsRef<Path>,
517    ) -> Result<Self, GitError> {
518        let path = index_file.as_ref();
519        if !path.exists() {
520            return Ok(Index::new());
521        }
522        Index::from_file_with_hash_kind(kind, path)
523    }
524
525    pub fn update(&mut self, entry: IndexEntry) {
526        self.add(entry)
527    }
528
529    pub fn add(&mut self, entry: IndexEntry) {
530        self.entries
531            .insert((entry.name.clone(), entry.flags.stage), entry);
532    }
533
534    pub fn remove(&mut self, name: &str, stage: u8) -> Option<IndexEntry> {
535        self.entries.remove(&(name.to_string(), stage))
536    }
537
538    pub fn get(&self, name: &str, stage: u8) -> Option<&IndexEntry> {
539        self.entries.get(&(name.to_string(), stage))
540    }
541
542    pub fn tracked(&self, name: &str, stage: u8) -> bool {
543        self.entries.contains_key(&(name.to_string(), stage))
544    }
545
546    pub fn get_hash(&self, file: &str, stage: u8) -> Option<ObjectHash> {
547        self.get(file, stage).map(|entry| entry.hash)
548    }
549
550    pub fn verify_hash(&self, file: &str, stage: u8, hash: &ObjectHash) -> bool {
551        let inner_hash = self.get_hash(file, stage);
552        if let Some(inner_hash) = inner_hash {
553            &inner_hash == hash
554        } else {
555            false
556        }
557    }
558    /// is file modified after last `add` (need hash to confirm content change)
559    /// - `workdir` is used to rebuild absolute file path
560    pub fn is_modified(&self, file: &str, stage: u8, workdir: &Path) -> bool {
561        if let Some(entry) = self.get(file, stage) {
562            let path_abs = workdir.join(file);
563            let meta = path_abs.symlink_metadata().unwrap();
564            // TODO more fields
565            let same = entry.ctime == Time::from_system_time(index_ctime(&meta))
566                && entry.mtime == Time::from_system_time(index_mtime(&meta))
567                && entry.size == meta.len() as u32;
568
569            !same
570        } else {
571            panic!("File not found in index");
572        }
573    }
574
575    /// Get all entries with the same stage
576    pub fn tracked_entries(&self, stage: u8) -> Vec<&IndexEntry> {
577        // ? should use stage or not
578        self.entries
579            .iter()
580            .filter(|(_, entry)| entry.flags.stage == stage)
581            .map(|(_, entry)| entry)
582            .collect()
583    }
584
585    /// Get all tracked files(stage = 0)
586    pub fn tracked_files(&self) -> Vec<PathBuf> {
587        self.tracked_entries(0)
588            .iter()
589            .map(|entry| PathBuf::from(&entry.name))
590            .collect()
591    }
592
593    /// Judge if the file(s) of `dir` is in the index
594    /// - false if `dir` is a file
595    pub fn contains_dir_file(&self, dir: &str) -> bool {
596        let dir = Path::new(dir);
597        self.entries.iter().any(|((name, _), _)| {
598            let path = Path::new(name);
599            path.starts_with(dir) && path != dir // TODO change to is_sub_path!
600        })
601    }
602
603    /// remove all files in `dir` from index
604    /// - do nothing if `dir` is a file
605    pub fn remove_dir_files(&mut self, dir: &str) -> Vec<String> {
606        let dir = Path::new(dir);
607        let mut removed = Vec::new();
608        self.entries.retain(|(name, _), _| {
609            let path = Path::new(name);
610            if path.starts_with(dir) && path != dir {
611                removed.push(name.clone());
612                false
613            } else {
614                true
615            }
616        });
617        removed
618    }
619
620    /// saved to index file (thread-local [`HashKind`]; see [`Index::save_with_hash_kind`])
621    pub fn save(&self, index_file: impl AsRef<Path>) -> Result<(), GitError> {
622        self.to_file(index_file)
623    }
624
625    /// Save to an index file for an explicit repository `kind`.
626    pub fn save_with_hash_kind(
627        &self,
628        kind: HashKind,
629        index_file: impl AsRef<Path>,
630    ) -> Result<(), GitError> {
631        self.to_file_with_hash_kind(kind, index_file)
632    }
633}
634
635#[cfg(test)]
636mod tests {
637    use std::io::Cursor;
638
639    use super::*;
640    use crate::hash::{HashKind, set_hash_kind_for_test};
641
642    /// Test Time conversion
643    #[test]
644    fn test_time() {
645        let time = Time {
646            seconds: 0,
647            nanos: 0,
648        };
649        let system_time = time.to_system_time();
650        let new_time = Time::from_system_time(system_time);
651        assert_eq!(time, new_time);
652    }
653
654    /// Test Flags conversion
655    #[test]
656    fn test_check_header() {
657        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
658        source.push("tests/data/index/index-2");
659
660        let file = File::open(source).unwrap();
661        let entries = Index::check_header(&mut BufReader::new(file)).unwrap();
662        assert_eq!(entries, 2);
663    }
664
665    /// Test IndexEntry creation
666    #[test]
667    fn test_index() {
668        let _guard = set_hash_kind_for_test(HashKind::Sha1);
669        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
670        source.push("tests/data/index/index-760");
671
672        let index = Index::from_file(source).unwrap();
673        assert_eq!(index.size(), 760);
674        for entry in index.entries.values() {
675            println!("{entry}");
676        }
677    }
678
679    /// Test IndexEntry creation with SHA256
680    #[test]
681    fn test_index_sha256() {
682        let _guard = set_hash_kind_for_test(HashKind::Sha256);
683        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
684        source.push("tests/data/index/index-9-256");
685
686        let index = Index::from_file(source).unwrap();
687        assert_eq!(index.size(), 9);
688        for entry in index.entries.values() {
689            println!("{entry}");
690        }
691    }
692
693    /// Flags bit packing/unpacking covers all fields and enforces name length limit.
694    #[test]
695    fn flags_round_trip_and_length_limit() {
696        let mut flags = Flags {
697            assume_valid: true,
698            extended: true,
699            stage: 2,
700            name_length: 0x0ABC,
701        };
702        let packed: u16 = (&flags).try_into().expect("should pack");
703        let unpacked = Flags::from(packed);
704        assert_eq!(unpacked.assume_valid, flags.assume_valid);
705        assert_eq!(unpacked.extended, flags.extended);
706        assert_eq!(unpacked.stage, flags.stage);
707        assert_eq!(unpacked.name_length, flags.name_length);
708
709        flags.name_length = 0x1FFF;
710        let overflow: Result<u16, _> = (&flags).try_into();
711        assert!(overflow.is_err(), "length overflow should err");
712    }
713
714    /// IndexEntry::new_from_blob populates fields and sets flags length.
715    #[test]
716    fn index_entry_new_from_blob_populates_fields() {
717        let hash = ObjectHash::from_bytes(&[0u8; 20]).unwrap();
718        let entry = IndexEntry::new_from_blob("file.txt".to_string(), hash, 42);
719        assert_eq!(entry.name, "file.txt");
720        assert_eq!(entry.size, 42);
721        assert_eq!(entry.hash, hash);
722        assert_eq!(entry.flags.name_length, "file.txt".len() as u16);
723        assert_eq!(entry.mode, 0o100644);
724    }
725
726    /// Index container operations: add/get/tracked/dir helpers.
727    #[test]
728    fn index_add_and_query_helpers() {
729        let _guard = set_hash_kind_for_test(HashKind::Sha1);
730        let mut index = Index::new();
731        let hash = ObjectHash::from_bytes(&[1u8; 20]).unwrap();
732        let entry = IndexEntry::new_from_blob("a/b.txt".to_string(), hash, 10);
733        index.add(entry);
734
735        // get finds stage-0 by name
736        let got = index.get("a/b.txt", 0).expect("entry exists");
737        assert_eq!(got.hash, hash);
738
739        // tracked_entries/files return stage-0 paths
740        let tracked = index.tracked_entries(0);
741        assert_eq!(tracked.len(), 1);
742        let files = index.tracked_files();
743        assert_eq!(files, vec![PathBuf::from("a/b.txt")]);
744
745        // contains_dir_file true for subpath, false for exact file
746        assert!(index.contains_dir_file("a"));
747        assert!(!index.contains_dir_file("a/b.txt"));
748
749        // remove_dir_files removes under dir and returns removed names
750        let removed = index.remove_dir_files("a");
751        assert_eq!(removed, vec!["a/b.txt".to_string()]);
752        assert!(index.get("a/b.txt", 0).is_none());
753    }
754
755    /// check_header should reject bad magic/versions and accept valid header.
756    #[test]
757    fn check_header_validation() {
758        // valid header: "DIRC" + version 2 + 0 entries
759        let mut valid = Cursor::new(b"DIRC\0\0\0\x02\0\0\0\0".to_vec());
760        let entries = Index::check_header(&mut valid).expect("valid header");
761        assert_eq!(entries, 0);
762
763        // bad magic
764        let mut bad_magic = Cursor::new(b"XXXX\0\0\0\x02\0\0\0\0".to_vec());
765        assert!(Index::check_header(&mut bad_magic).is_err());
766
767        // bad version
768        let mut bad_version = Cursor::new(b"DIRC\0\0\0\x01\0\0\0\0".to_vec());
769        assert!(Index::check_header(&mut bad_version).is_err());
770    }
771
772    /// Test saving Index to file
773    #[test]
774    fn test_index_to_file() {
775        let temp_dir = tempfile::tempdir().unwrap();
776        let temp_path = temp_dir.path().join("index-760");
777
778        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
779        source.push("tests/data/index/index-760");
780
781        let index = Index::from_file(source).unwrap();
782        index.to_file(&temp_path).unwrap();
783        let new_index = Index::from_file(temp_path).unwrap();
784        assert_eq!(index.size(), new_index.size());
785    }
786
787    /// Test IndexEntry creation from file
788    #[test]
789    fn test_index_entry_create() {
790        let _guard = set_hash_kind_for_test(HashKind::Sha1);
791        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
792        source.push("Cargo.toml");
793
794        let file = Path::new(source.as_path()); // use as a normal file
795        let hash = ObjectHash::from_bytes(&[0; 20]).unwrap();
796        let workdir = Path::new("../");
797        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
798        println!("{entry}");
799    }
800
801    /// Test IndexEntry creation from file with SHA256
802    #[test]
803    fn test_index_entry_create_sha256() {
804        let _guard = set_hash_kind_for_test(HashKind::Sha256);
805        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
806        source.push("Cargo.toml");
807
808        let file = Path::new(source.as_path());
809        let hash = ObjectHash::from_bytes(&[0u8; 32]).unwrap();
810        let workdir = Path::new("../");
811        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
812        println!("{entry}");
813    }
814
815    /// A BLAKE3 index round-trips through `to_file_with_hash_kind` / `from_file_with_hash_kind`
816    /// with the thread-local kind set to SHA-1, entry lookups return `ObjectHash::Blake3`, and
817    /// reading the file as SHA-256 (same width) or writing a cross-kind entry fails closed.
818    #[test]
819    fn blake3_lookup() {
820        let _guard = set_hash_kind_for_test(HashKind::Sha1);
821        let temp_dir = tempfile::tempdir().unwrap();
822        let path = temp_dir.path().join("index-blake3");
823
824        let a = ObjectHash::new_for_kind(HashKind::Blake3, b"a");
825        let c = ObjectHash::new_for_kind(HashKind::Blake3, b"c");
826        let mut index = Index::new();
827        index.add(IndexEntry::new_from_blob("a.txt".to_string(), a, 1));
828        index.add(IndexEntry::new_from_blob("b/c.txt".to_string(), c, 3));
829        index
830            .to_file_with_hash_kind(HashKind::Blake3, &path)
831            .unwrap();
832
833        let loaded = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
834        assert_eq!(loaded.size(), 2);
835        let got = loaded.get("a.txt", 0).expect("a.txt");
836        assert_eq!(got.hash, a);
837        assert_eq!(got.hash.kind(), HashKind::Blake3);
838        assert_eq!(loaded.get("b/c.txt", 0).unwrap().hash, c);
839        assert_eq!(
840            loaded.tracked_files(),
841            vec![PathBuf::from("a.txt"), PathBuf::from("b/c.txt")]
842        );
843
844        // Same width, different algorithm: the checksum does not verify.
845        let err = Index::from_file_with_hash_kind(HashKind::Sha256, &path)
846            .err()
847            .expect("same-width SHA-256 read must fail");
848        assert!(matches!(err, GitError::InvalidIndexFile(_)), "{err:?}");
849        // The thread-local (SHA-1) legacy reader cannot read a BLAKE3 index either.
850        assert!(Index::from_file(&path).is_err());
851
852        // load/save with explicit kind.
853        let missing =
854            Index::load_with_hash_kind(HashKind::Blake3, temp_dir.path().join("none")).unwrap();
855        assert_eq!(missing.size(), 0);
856        let again = temp_dir.path().join("index-blake3-2");
857        loaded
858            .save_with_hash_kind(HashKind::Blake3, &again)
859            .unwrap();
860        assert_eq!(
861            Index::load_with_hash_kind(HashKind::Blake3, &again)
862                .unwrap()
863                .size(),
864            2
865        );
866
867        // A cross-kind entry is refused when writing.
868        let mut mixed = Index::new();
869        mixed.add(IndexEntry::new_from_blob(
870            "x.txt".to_string(),
871            ObjectHash::new_for_kind(HashKind::Sha256, b"x"),
872            1,
873        ));
874        let mixed_path = temp_dir.path().join("mixed");
875        let err = mixed
876            .to_file_with_hash_kind(HashKind::Blake3, &mixed_path)
877            .expect_err("cross-kind entry must fail");
878        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
879        // ... and the destination is untouched: no partial file, and an existing valid index
880        // is not truncated.
881        assert!(!mixed_path.exists());
882        let before = std::fs::read(&path).unwrap();
883        assert!(
884            mixed
885                .to_file_with_hash_kind(HashKind::Blake3, &path)
886                .is_err()
887        );
888        assert_eq!(std::fs::read(&path).unwrap(), before);
889
890        // Refreshing a BLAKE3 entry with another kind is refused and leaves it untouched;
891        // the same kind recomputes a BLAKE3 content hash.
892        let work = temp_dir.path().join("work");
893        std::fs::create_dir_all(&work).unwrap();
894        std::fs::write(work.join("a.txt"), b"a").unwrap();
895        let mut refreshed = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
896        let err = refreshed
897            .refresh_with_hash_kind(HashKind::Sha256, "a.txt", &work)
898            .expect_err("cross-kind refresh must fail");
899        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
900        assert_eq!(refreshed.get("a.txt", 0).unwrap().hash, a);
901        refreshed
902            .refresh_with_hash_kind(HashKind::Blake3, "a.txt", &work)
903            .unwrap();
904        let got = refreshed.get("a.txt", 0).unwrap().hash;
905        assert_eq!(got.kind(), HashKind::Blake3);
906        assert_eq!(got, a);
907    }
908}