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