git-internal 0.10.3

High-performance Rust library for Git internal objects, Pack files, and AI-assisted development objects (Intent, Plan, Task, Run, Evidence, Decision) with delta compression, streaming I/O, and smart protocol support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
//! Minimal Git index (.git/index) reader/writer that maps working tree metadata to `IndexEntry`
//! records, including POSIX timestamp handling and hash serialization helpers.

#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)]
use std::time::Duration;
use std::{
    collections::BTreeMap,
    fmt::{Display, Formatter},
    fs::{self, File},
    io,
    io::{BufReader, Read, Write},
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

use crate::{
    errors::GitError,
    hash::{HashKind, ObjectHash, get_hash_kind},
    internal::{object::types::ObjectType, pack::wrapper::Wrapper},
    utils::{self, HashAlgorithm},
};

/// POSIX time with seconds and nanoseconds
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Time {
    seconds: u32,
    nanos: u32,
}
impl Time {
    /// Read Time from stream
    pub fn from_stream(stream: &mut impl Read) -> Result<Self, GitError> {
        let seconds = stream.read_u32::<BigEndian>()?;
        let nanos = stream.read_u32::<BigEndian>()?;
        Ok(Time { seconds, nanos })
    }

    /// Convert to SystemTime
    #[allow(dead_code)]
    fn to_system_time(&self) -> SystemTime {
        UNIX_EPOCH + std::time::Duration::new(self.seconds.into(), self.nanos)
    }

    /// Create Time from SystemTime
    pub fn from_system_time(system_time: SystemTime) -> Self {
        match system_time.duration_since(UNIX_EPOCH) {
            Ok(duration) => {
                let seconds = duration
                    .as_secs()
                    .try_into()
                    .expect("Time is too far in the future");
                let nanos = duration.subsec_nanos();
                Time { seconds, nanos }
            }
            Err(_) => panic!("Time is before the UNIX epoch"),
        }
    }
}
impl Display for Time {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.seconds, self.nanos)
    }
}

#[cfg(unix)]
fn index_ctime(meta: &fs::Metadata) -> SystemTime {
    unix_metadata_time(meta.ctime(), meta.ctime_nsec())
}

#[cfg(not(unix))]
fn index_ctime(meta: &fs::Metadata) -> SystemTime {
    meta.created()
        .or_else(|_| meta.modified())
        .unwrap_or(UNIX_EPOCH)
}

#[cfg(unix)]
fn index_mtime(meta: &fs::Metadata) -> SystemTime {
    unix_metadata_time(meta.mtime(), meta.mtime_nsec())
}

#[cfg(not(unix))]
fn index_mtime(meta: &fs::Metadata) -> SystemTime {
    meta.modified()
        .or_else(|_| meta.created())
        .unwrap_or(UNIX_EPOCH)
}

#[cfg(unix)]
fn unix_metadata_time(seconds: i64, nanos: i64) -> SystemTime {
    if seconds < 0 {
        return UNIX_EPOCH;
    }

    let nanos = u32::try_from(nanos)
        .ok()
        .filter(|nanos| *nanos < 1_000_000_000)
        .unwrap_or(0);

    UNIX_EPOCH + Duration::new(seconds as u64, nanos)
}

/// 16 bits
///
/// `skip_worktree` and `intent_to_add` live in the on-disk *extended* flags
/// word (index v3, `CE_EXTENDED`); `extended` records whether that second word
/// is present. The reader fills all three; the writer derives the on-disk
/// `CE_EXTENDED` bit from the extended word (or an explicit `extended`).
#[derive(Debug)]
pub struct Flags {
    pub assume_valid: bool,
    pub extended: bool,   // must be 0 in v2
    pub stage: u8,        // 2-bit during merge
    pub name_length: u16, // 12-bit
    /// `CE_SKIP_WORKTREE` (extended flags bit `0x4000`).
    pub skip_worktree: bool,
    /// `CE_INTENT_TO_ADD` (extended flags bit `0x2000`).
    pub intent_to_add: bool,
}

impl From<u16> for Flags {
    fn from(flags: u16) -> Self {
        Flags {
            assume_valid: flags & 0x8000 != 0,
            extended: flags & 0x4000 != 0,
            stage: ((flags & 0x3000) >> 12) as u8,
            name_length: flags & 0xFFF,
            skip_worktree: false,
            intent_to_add: false,
        }
    }
}

impl TryInto<u16> for &Flags {
    type Error = &'static str;
    fn try_into(self) -> Result<u16, Self::Error> {
        let mut flags = 0u16;
        if self.assume_valid {
            flags |= 0x8000; // 16
        }
        if self.extended {
            flags |= 0x4000; // 15
        }
        flags |= (self.stage as u16) << 12; // 13-14
        if self.name_length > 0xFFF {
            return Err("Name length is too long");
        }
        flags |= self.name_length; // 0-11
        Ok(flags)
    }
}

impl Flags {
    /// The on-disk extended flag `CE_SKIP_WORKTREE`.
    pub const EXTENDED_FLAG_SKIP_WORKTREE: u16 = 0x4000;
    /// The on-disk extended flag `CE_INTENT_TO_ADD`.
    pub const EXTENDED_FLAG_INTENT_TO_ADD: u16 = 0x2000;

    pub fn new(name_len: u16) -> Self {
        Flags {
            assume_valid: true,
            extended: false,
            stage: 0,
            name_length: name_len,
            skip_worktree: false,
            intent_to_add: false,
        }
    }

    /// Decode the 16-bit extended flags word, failing closed on unknown bits.
    pub fn from_extended_word(word: u16) -> Result<(bool, bool), GitError> {
        const KNOWN: u16 = Flags::EXTENDED_FLAG_SKIP_WORKTREE | Flags::EXTENDED_FLAG_INTENT_TO_ADD;
        if word & !KNOWN != 0 {
            return Err(GitError::InvalidIndexFile(format!(
                "index entry has unknown extended flags 0x{word:04x}"
            )));
        }
        Ok((
            word & Flags::EXTENDED_FLAG_SKIP_WORKTREE != 0,
            word & Flags::EXTENDED_FLAG_INTENT_TO_ADD != 0,
        ))
    }

    /// The extended flags word to write, or `None` when no extended bit is set.
    pub fn extended_word(&self) -> Option<u16> {
        let mut word = 0u16;
        if self.skip_worktree {
            word |= Flags::EXTENDED_FLAG_SKIP_WORKTREE;
        }
        if self.intent_to_add {
            word |= Flags::EXTENDED_FLAG_INTENT_TO_ADD;
        }
        (word != 0).then_some(word)
    }
}

/// An entry in the Git index file.
pub struct IndexEntry {
    pub ctime: Time,
    pub mtime: Time,
    pub dev: u32,  // 0 for windows
    pub ino: u32,  // 0 for windows
    pub mode: u32, // 0o100644 // 4-bit object type + 3-bit unused + 9-bit unix permission
    pub uid: u32,  // 0 for windows
    pub gid: u32,  // 0 for windows
    pub size: u32,
    pub hash: ObjectHash,
    pub flags: Flags,
    pub name: String,
}
impl Display for IndexEntry {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "IndexEntry {{ ctime: {}, mtime: {}, dev: {}, ino: {}, mode: {:o}, uid: {}, gid: {}, size: {}, hash: {}, flags: {:?}, name: {} }}",
            self.ctime,
            self.mtime,
            self.dev,
            self.ino,
            self.mode,
            self.uid,
            self.gid,
            self.size,
            self.hash,
            self.flags,
            self.name
        )
    }
}

impl IndexEntry {
    /** Metadata must be got by [fs::symlink_metadata] to avoid following symlink */
    pub fn new(meta: &fs::Metadata, hash: ObjectHash, name: String) -> Self {
        let mut entry = IndexEntry {
            ctime: Time::from_system_time(index_ctime(meta)),
            mtime: Time::from_system_time(index_mtime(meta)),
            dev: 0,
            ino: 0,
            uid: 0,
            gid: 0,
            size: meta.len() as u32,
            hash,
            flags: Flags::new(name.len() as u16),
            name,
            mode: 0o100644,
        };
        #[cfg(unix)]
        {
            entry.dev = meta.dev() as u32;
            entry.ino = meta.ino() as u32;
            entry.uid = meta.uid();
            entry.gid = meta.gid();

            entry.mode = match meta.mode() & 0o170000/* file mode */ {
                0o100000 => {
                    match meta.mode() & 0o111 {
                        0 => 0o100644, // no execute permission
                        _ => 0o100755, // with execute permission
                    }
                }
                0o120000 => 0o120000, // symlink
                _ =>  entry.mode, // keep the original mode
            }
        }
        #[cfg(windows)]
        {
            if meta.is_symlink() {
                entry.mode = 0o120000;
            }
        }
        entry
    }

    /// - `file`: **to workdir path**
    /// - `workdir`: absolute or relative path
    pub fn new_from_file(file: &Path, hash: ObjectHash, workdir: &Path) -> io::Result<Self> {
        let name = file.to_str().unwrap().to_string();
        let file_abs = workdir.join(file);
        let meta = fs::symlink_metadata(file_abs)?; // without following symlink
        let index = IndexEntry::new(&meta, hash, name);
        Ok(index)
    }

    /// Create IndexEntry from blob object
    pub fn new_from_blob(name: String, hash: ObjectHash, size: u32) -> Self {
        IndexEntry {
            ctime: Time {
                seconds: 0,
                nanos: 0,
            },
            mtime: Time {
                seconds: 0,
                nanos: 0,
            },
            dev: 0,
            ino: 0,
            mode: 0o100644,
            uid: 0,
            gid: 0,
            size,
            hash,
            flags: Flags::new(name.len() as u16),
            name,
        }
    }
}

/// see [index-format](https://git-scm.com/docs/index-format)
/// <br> to Working Dir relative path
pub struct Index {
    entries: BTreeMap<(String, u8), IndexEntry>,
}

impl Index {
    pub fn new() -> Self {
        Index {
            entries: BTreeMap::new(),
        }
    }

    /// Parse and validate the `DIRC` header, returning `(version, entry_count)`.
    /// Versions 2 and 3 are accepted; anything else fails closed.
    fn check_header(file: &mut impl Read) -> Result<(u32, u32), GitError> {
        let mut magic = [0; 4];
        file.read_exact(&mut magic)?;
        if magic != *b"DIRC" {
            return Err(GitError::InvalidIndexHeader(
                String::from_utf8_lossy(&magic).to_string(),
            ));
        }

        let version = file.read_u32::<BigEndian>()?;
        // v3 adds the per-entry extended flags word; later versions are unsupported.
        if version != 2 && version != 3 {
            return Err(GitError::InvalidIndexHeader(version.to_string()));
        }

        let entries = file.read_u32::<BigEndian>()?;
        Ok((version, entries))
    }

    pub fn size(&self) -> usize {
        self.entries.len()
    }

    /// Read an index file using the thread-local [`HashKind`]; compatibility wrapper around
    /// [`Index::from_file_with_hash_kind`].
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, GitError> {
        Self::from_file_with_hash_kind(get_hash_kind(), path)
    }

    /// Read an index file whose entry IDs and checksum belong to the explicit repository
    /// `kind`. The checksum is verified with `kind`, so an index written for another kind
    /// (even one of the same width) fails closed instead of being misread.
    pub fn from_file_with_hash_kind(
        kind: HashKind,
        path: impl AsRef<Path>,
    ) -> Result<Self, GitError> {
        let file = File::open(path.as_ref())?; // read-only
        let total_size = file.metadata()?.len();
        let file = &mut Wrapper::new_with_kind(BufReader::new(file), kind); // TODO move Wrapper & utils to a common module

        let (_version, num) = Index::check_header(file)?;
        let mut index = Index::new();

        for _ in 0..num {
            let mut entry = IndexEntry {
                ctime: Time::from_stream(file)?,
                mtime: Time::from_stream(file)?,
                dev: file.read_u32::<BigEndian>()?, //utils::read_u32_be(file)?,
                ino: file.read_u32::<BigEndian>()?,
                mode: file.read_u32::<BigEndian>()?,
                uid: file.read_u32::<BigEndian>()?,
                gid: file.read_u32::<BigEndian>()?,
                size: file.read_u32::<BigEndian>()?,
                hash: utils::read_sha_for_kind(kind, file)?,
                flags: Flags::from(file.read_u16::<BigEndian>()?),
                name: String::new(),
            };
            // v3 entries with CE_EXTENDED carry a second flags word directly
            // after the main word and before the name (index-format(5)).
            if entry.flags.extended {
                let word = file.read_u16::<BigEndian>()?;
                let (skip_worktree, intent_to_add) = Flags::from_extended_word(word)?;
                entry.flags.skip_worktree = skip_worktree;
                entry.flags.intent_to_add = intent_to_add;
            }
            let name_len = entry.flags.name_length as usize;
            let mut name = vec![0; name_len];
            file.read_exact(&mut name)?;
            // The exact encoding is undefined, but the '.' and '/' characters are encoded in 7-bit ASCII
            entry.name =
                String::from_utf8(name).map_err(|e| GitError::ConversionError(e.to_string()))?; // TODO check the encoding
            let extended = entry.flags.extended;
            index
                .entries
                .insert((entry.name.clone(), entry.flags.stage), entry);

            // 1-8 nul bytes as necessary to pad the entry to a multiple of eight bytes
            // while keeping the name NUL-terminated. The extended flags word, when
            // present, is part of the padded entry length.
            let hash_len = kind.size();
            let entry_len = hash_len + 2 + if extended { 2 } else { 0 } + name_len;
            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
            utils::read_bytes(file, padding)?;
        }

        // Extensions
        while file.bytes_read() + kind.size() < total_size as usize {
            // The remaining bytes must be the index checksum (size = kind.size())
            let sign = utils::read_bytes(file, 4)?;
            println!(
                "{:?}",
                String::from_utf8(sign.clone())
                    .map_err(|e| GitError::ConversionError(e.to_string()))?
            );
            // If the first byte is 'A'...'Z' the extension is optional and can be ignored.
            if sign[0] >= b'A' && sign[0] <= b'Z' {
                // Optional extension
                let size = file.read_u32::<BigEndian>()?;
                utils::read_bytes(file, size as usize)?; // Ignore the extension
            } else {
                // 'link' or 'sdir' extension
                return Err(GitError::InvalidIndexFile(
                    "Unsupported extension".to_string(),
                ));
            }
        }

        // check sum
        let file_hash = file.final_hash();
        let check_sum = utils::read_sha_for_kind(kind, file)?;
        if file_hash != check_sum {
            return Err(GitError::InvalidIndexFile("Check sum failed".to_string()));
        }
        assert_eq!(index.size(), num as usize);
        Ok(index)
    }

    /// Write the index using the thread-local [`HashKind`]; compatibility wrapper around
    /// [`Index::to_file_with_hash_kind`].
    pub fn to_file(&self, path: impl AsRef<Path>) -> Result<(), GitError> {
        self.to_file_with_hash_kind(get_hash_kind(), path)
    }

    /// Write the index for an explicit repository `kind`: every entry ID must belong to
    /// `kind` (a cross-kind entry fails closed) and the trailing checksum is computed with it.
    pub fn to_file_with_hash_kind(
        &self,
        kind: HashKind,
        path: impl AsRef<Path>,
    ) -> Result<(), GitError> {
        // Validate every entry before touching the destination, so a cross-kind entry can
        // neither truncate an existing valid index nor leave a partial file behind.
        for entry in self.entries.values() {
            entry.hash.ensure_kind(kind)?;
        }
        let mut file = File::create(path)?;
        let mut hash = HashAlgorithm::new_for_kind(kind);

        // Any entry carrying an extended flags word forces the whole index to v3;
        // otherwise the output stays byte-identical to the v2 writer.
        let any_extended = self
            .entries
            .values()
            .any(|entry| entry.flags.extended_word().is_some() || entry.flags.extended);

        let mut header = Vec::new();
        header.write_all(b"DIRC")?;
        header.write_u32::<BigEndian>(if any_extended { 3u32 } else { 2u32 })?;
        header.write_u32::<BigEndian>(self.entries.len() as u32)?;
        file.write_all(&header)?;
        hash.update(&header);

        for entry in self.entries.values() {
            let mut entry_bytes = Vec::new();
            entry_bytes.write_u32::<BigEndian>(entry.ctime.seconds)?;
            entry_bytes.write_u32::<BigEndian>(entry.ctime.nanos)?;
            entry_bytes.write_u32::<BigEndian>(entry.mtime.seconds)?;
            entry_bytes.write_u32::<BigEndian>(entry.mtime.nanos)?;
            entry_bytes.write_u32::<BigEndian>(entry.dev)?;
            entry_bytes.write_u32::<BigEndian>(entry.ino)?;
            entry_bytes.write_u32::<BigEndian>(entry.mode)?;
            entry_bytes.write_u32::<BigEndian>(entry.uid)?;
            entry_bytes.write_u32::<BigEndian>(entry.gid)?;
            entry_bytes.write_u32::<BigEndian>(entry.size)?;
            entry_bytes.write_all(entry.hash.as_ref())?;
            // An explicit `extended` with no known bit still emits a zero word so
            // the on-disk layout stays self-consistent.
            let extended_word = entry.flags.extended_word().or(if entry.flags.extended {
                Some(0u16)
            } else {
                None
            });
            let mut packed: u16 = (&entry.flags).try_into().map_err(|error| {
                GitError::InvalidIndexFile(format!("cannot encode index flags: {error}"))
            })?;
            if extended_word.is_some() {
                packed |= 0x4000; // CE_EXTENDED
            }
            entry_bytes.write_u16::<BigEndian>(packed)?;
            if let Some(word) = extended_word {
                entry_bytes.write_u16::<BigEndian>(word)?;
            }
            entry_bytes.write_all(entry.name.as_bytes())?;
            let hash_len = kind.size();
            let entry_len =
                hash_len + 2 + if extended_word.is_some() { 2 } else { 0 } + entry.name.len();
            let padding = 1 + ((8 - ((entry_len + 1) % 8)) % 8); // at least 1 byte nul
            entry_bytes.write_all(&vec![0; padding])?;
            file.write_all(&entry_bytes)?;
            hash.update(&entry_bytes);
        }

        // Extensions

        // check sum
        let file_hash = hash.finalize_object_hash();
        file.write_all(file_hash.as_ref())?;
        Ok(())
    }

    /// Refresh one entry using the thread-local [`HashKind`]; compatibility wrapper around
    /// [`Index::refresh_with_hash_kind`].
    pub fn refresh(&mut self, file: impl AsRef<Path>, workdir: &Path) -> Result<bool, GitError> {
        self.refresh_with_hash_kind(get_hash_kind(), file, workdir)
    }

    /// Refresh one entry's stat data and content hash for an explicit repository `kind`.
    ///
    /// The recomputed ID is the blob's object ID — the digest of `"<type> <size>\0"` + the
    /// file contents, exactly what [`ObjectHash::from_type_and_data_for_kind`] produces for
    /// [`ObjectType::Blob`] — not a digest of the raw file bytes. The header is streamed
    /// into the hasher before the file, so the file is never buffered in memory.
    ///
    /// The existing entry must already belong to `kind`: refreshing an entry of another kind
    /// fails closed instead of silently replacing its ID with a digest of a different
    /// algorithm.
    pub fn refresh_with_hash_kind(
        &mut self,
        kind: HashKind,
        file: impl AsRef<Path>,
        workdir: &Path,
    ) -> Result<bool, GitError> {
        let path = file.as_ref();
        let name = path
            .to_str()
            .ok_or(GitError::InvalidPathError(format!("{path:?}")))?;

        if let Some(entry) = self.entries.get_mut(&(name.to_string(), 0)) {
            entry.hash.ensure_kind(kind)?;
            let abs_path = workdir.join(path);
            let meta = fs::symlink_metadata(&abs_path)?;
            let new_ctime = Time::from_system_time(index_ctime(&meta));
            let new_mtime = Time::from_system_time(index_mtime(&meta));
            let new_size = meta.len() as u32;

            // re-calculate the blob ID with the repository kind: the ID covers
            // `"<type> <size>\0" + content` (see `ObjectHash::from_type_and_data_for_kind`),
            // so the header must be hashed before the file contents. Streaming the header
            // first keeps the file itself out of memory.
            let type_label = ObjectType::Blob
                .to_bytes()
                .ok_or_else(|| GitError::InvalidObjectType("Blob".to_string()))?;
            let mut hasher = HashAlgorithm::new_for_kind(kind);
            hasher.update(type_label);
            hasher.update(b" ");
            hasher.update(meta.len().to_string().as_bytes());
            hasher.update(b"\x00");
            let mut file = File::open(&abs_path)?;
            io::copy(&mut file, &mut hasher)?;
            let new_hash = hasher.finalize_object_hash();

            // refresh index
            if entry.ctime != new_ctime
                || entry.mtime != new_mtime
                || entry.size != new_size
                || entry.hash != new_hash
            {
                entry.ctime = new_ctime;
                entry.mtime = new_mtime;
                entry.size = new_size;
                entry.hash = new_hash;
                return Ok(true);
            }
        }
        Ok(false)
    }
}

impl Default for Index {
    fn default() -> Self {
        Self::new()
    }
}

impl Index {
    /// Load index. If it does not exist, return an empty index.
    ///
    /// Uses the thread-local [`HashKind`]; see [`Index::load_with_hash_kind`].
    pub fn load(index_file: impl AsRef<Path>) -> Result<Self, GitError> {
        Self::load_with_hash_kind(get_hash_kind(), index_file)
    }

    /// Load index for an explicit repository `kind`. If it does not exist, return an empty index.
    pub fn load_with_hash_kind(
        kind: HashKind,
        index_file: impl AsRef<Path>,
    ) -> Result<Self, GitError> {
        let path = index_file.as_ref();
        if !path.exists() {
            return Ok(Index::new());
        }
        Index::from_file_with_hash_kind(kind, path)
    }

    pub fn update(&mut self, entry: IndexEntry) {
        self.add(entry)
    }

    pub fn add(&mut self, entry: IndexEntry) {
        self.entries
            .insert((entry.name.clone(), entry.flags.stage), entry);
    }

    pub fn remove(&mut self, name: &str, stage: u8) -> Option<IndexEntry> {
        self.entries.remove(&(name.to_string(), stage))
    }

    pub fn get(&self, name: &str, stage: u8) -> Option<&IndexEntry> {
        self.entries.get(&(name.to_string(), stage))
    }

    pub fn tracked(&self, name: &str, stage: u8) -> bool {
        self.entries.contains_key(&(name.to_string(), stage))
    }

    pub fn get_hash(&self, file: &str, stage: u8) -> Option<ObjectHash> {
        self.get(file, stage).map(|entry| entry.hash)
    }

    pub fn verify_hash(&self, file: &str, stage: u8, hash: &ObjectHash) -> bool {
        let inner_hash = self.get_hash(file, stage);
        if let Some(inner_hash) = inner_hash {
            &inner_hash == hash
        } else {
            false
        }
    }
    /// is file modified after last `add` (need hash to confirm content change)
    /// - `workdir` is used to rebuild absolute file path
    pub fn is_modified(&self, file: &str, stage: u8, workdir: &Path) -> bool {
        if let Some(entry) = self.get(file, stage) {
            let path_abs = workdir.join(file);
            let meta = path_abs.symlink_metadata().unwrap();
            // TODO more fields
            let same = entry.ctime == Time::from_system_time(index_ctime(&meta))
                && entry.mtime == Time::from_system_time(index_mtime(&meta))
                && entry.size == meta.len() as u32;

            !same
        } else {
            panic!("File not found in index");
        }
    }

    /// Get all entries with the same stage
    pub fn tracked_entries(&self, stage: u8) -> Vec<&IndexEntry> {
        // ? should use stage or not
        self.entries
            .iter()
            .filter(|(_, entry)| entry.flags.stage == stage)
            .map(|(_, entry)| entry)
            .collect()
    }

    /// Get all tracked files(stage = 0)
    pub fn tracked_files(&self) -> Vec<PathBuf> {
        self.tracked_entries(0)
            .iter()
            .map(|entry| PathBuf::from(&entry.name))
            .collect()
    }

    /// Judge if the file(s) of `dir` is in the index
    /// - false if `dir` is a file
    pub fn contains_dir_file(&self, dir: &str) -> bool {
        let dir = Path::new(dir);
        self.entries.iter().any(|((name, _), _)| {
            let path = Path::new(name);
            path.starts_with(dir) && path != dir // TODO change to is_sub_path!
        })
    }

    /// remove all files in `dir` from index
    /// - do nothing if `dir` is a file
    pub fn remove_dir_files(&mut self, dir: &str) -> Vec<String> {
        let dir = Path::new(dir);
        let mut removed = Vec::new();
        self.entries.retain(|(name, _), _| {
            let path = Path::new(name);
            if path.starts_with(dir) && path != dir {
                removed.push(name.clone());
                false
            } else {
                true
            }
        });
        removed
    }

    /// saved to index file (thread-local [`HashKind`]; see [`Index::save_with_hash_kind`])
    pub fn save(&self, index_file: impl AsRef<Path>) -> Result<(), GitError> {
        self.to_file(index_file)
    }

    /// Save to an index file for an explicit repository `kind`.
    pub fn save_with_hash_kind(
        &self,
        kind: HashKind,
        index_file: impl AsRef<Path>,
    ) -> Result<(), GitError> {
        self.to_file_with_hash_kind(kind, index_file)
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;
    use crate::{
        hash::{HashKind, set_hash_kind_for_test},
        internal::object::blob::Blob,
    };

    /// Test Time conversion
    #[test]
    fn test_time() {
        let time = Time {
            seconds: 0,
            nanos: 0,
        };
        let system_time = time.to_system_time();
        let new_time = Time::from_system_time(system_time);
        assert_eq!(time, new_time);
    }

    /// Test Flags conversion
    #[test]
    fn test_check_header() {
        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("tests/data/index/index-2");

        let file = File::open(source).unwrap();
        let (version, entries) = Index::check_header(&mut BufReader::new(file)).unwrap();
        assert_eq!(version, 2);
        assert_eq!(entries, 2);
    }

    /// Test IndexEntry creation
    #[test]
    fn test_index() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("tests/data/index/index-760");

        let index = Index::from_file(source).unwrap();
        assert_eq!(index.size(), 760);
        for entry in index.entries.values() {
            println!("{entry}");
        }
    }

    /// Test IndexEntry creation with SHA256
    #[test]
    fn test_index_sha256() {
        let _guard = set_hash_kind_for_test(HashKind::Sha256);
        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("tests/data/index/index-9-256");

        let index = Index::from_file(source).unwrap();
        assert_eq!(index.size(), 9);
        for entry in index.entries.values() {
            println!("{entry}");
        }
    }

    /// Flags bit packing/unpacking covers all fields and enforces name length limit.
    #[test]
    fn flags_round_trip_and_length_limit() {
        let mut flags = Flags {
            assume_valid: true,
            extended: true,
            stage: 2,
            name_length: 0x0ABC,
            skip_worktree: false,
            intent_to_add: false,
        };
        let packed: u16 = (&flags).try_into().expect("should pack");
        let unpacked = Flags::from(packed);
        assert_eq!(unpacked.assume_valid, flags.assume_valid);
        assert_eq!(unpacked.extended, flags.extended);
        assert_eq!(unpacked.stage, flags.stage);
        assert_eq!(unpacked.name_length, flags.name_length);

        flags.name_length = 0x1FFF;
        let overflow: Result<u16, _> = (&flags).try_into();
        assert!(overflow.is_err(), "length overflow should err");
    }

    /// IndexEntry::new_from_blob populates fields and sets flags length.
    #[test]
    fn index_entry_new_from_blob_populates_fields() {
        let hash = ObjectHash::from_bytes(&[0u8; 20]).unwrap();
        let entry = IndexEntry::new_from_blob("file.txt".to_string(), hash, 42);
        assert_eq!(entry.name, "file.txt");
        assert_eq!(entry.size, 42);
        assert_eq!(entry.hash, hash);
        assert_eq!(entry.flags.name_length, "file.txt".len() as u16);
        assert_eq!(entry.mode, 0o100644);
    }

    /// Index container operations: add/get/tracked/dir helpers.
    #[test]
    fn index_add_and_query_helpers() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let mut index = Index::new();
        let hash = ObjectHash::from_bytes(&[1u8; 20]).unwrap();
        let entry = IndexEntry::new_from_blob("a/b.txt".to_string(), hash, 10);
        index.add(entry);

        // get finds stage-0 by name
        let got = index.get("a/b.txt", 0).expect("entry exists");
        assert_eq!(got.hash, hash);

        // tracked_entries/files return stage-0 paths
        let tracked = index.tracked_entries(0);
        assert_eq!(tracked.len(), 1);
        let files = index.tracked_files();
        assert_eq!(files, vec![PathBuf::from("a/b.txt")]);

        // contains_dir_file true for subpath, false for exact file
        assert!(index.contains_dir_file("a"));
        assert!(!index.contains_dir_file("a/b.txt"));

        // remove_dir_files removes under dir and returns removed names
        let removed = index.remove_dir_files("a");
        assert_eq!(removed, vec!["a/b.txt".to_string()]);
        assert!(index.get("a/b.txt", 0).is_none());
    }

    /// check_header should reject bad magic/versions and accept valid headers.
    #[test]
    fn check_header_validation() {
        // valid header: "DIRC" + version 2 + 0 entries
        let mut valid = Cursor::new(b"DIRC\0\0\0\x02\0\0\0\0".to_vec());
        let (version, entries) = Index::check_header(&mut valid).expect("valid header");
        assert_eq!(version, 2);
        assert_eq!(entries, 0);

        // v3 is accepted: it only adds an optional per-entry extended flags word
        let mut v3 = Cursor::new(b"DIRC\0\0\0\x03\0\0\0\0".to_vec());
        let (version, entries) = Index::check_header(&mut v3).expect("v3 header");
        assert_eq!(version, 3);
        assert_eq!(entries, 0);

        // bad magic
        let mut bad_magic = Cursor::new(b"XXXX\0\0\0\x02\0\0\0\0".to_vec());
        assert!(Index::check_header(&mut bad_magic).is_err());

        // unsupported versions (1 and 4) fail closed
        let mut bad_version = Cursor::new(b"DIRC\0\0\0\x01\0\0\0\0".to_vec());
        assert!(Index::check_header(&mut bad_version).is_err());
        let mut v4 = Cursor::new(b"DIRC\0\0\0\x04\0\0\0\0".to_vec());
        assert!(Index::check_header(&mut v4).is_err());
    }

    /// Test saving Index to file
    #[test]
    fn test_index_to_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let temp_path = temp_dir.path().join("index-760");

        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("tests/data/index/index-760");

        let index = Index::from_file(source).unwrap();
        index.to_file(&temp_path).unwrap();
        let new_index = Index::from_file(temp_path).unwrap();
        assert_eq!(index.size(), new_index.size());
    }

    /// A real index v3 generated by git 2.55.0 (SHA-1) with one skip-worktree
    /// entry (`a.txt`): header v3, entry flags `0x4005`, extended word `0x4000`.
    const GIT_V3_SKIP_WORKTREE_FIXTURE: [u8; 104] = [
        0x44, 0x49, 0x52, 0x43, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x6a, 0xaf, 0x4a,
        0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x6a, 0xaf, 0x4a, 0x7b, 0x10, 0xbe, 0x36, 0x0a, 0x00, 0x00,
        0x00, 0x3a, 0x06, 0x98, 0x73, 0xd9, 0x00, 0x00, 0x81, 0xa4, 0x00, 0x00, 0x03, 0xe8, 0x00,
        0x00, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x03, 0x45, 0xb9, 0x83, 0xbe, 0x36, 0xb7, 0x3c, 0x07,
        0x88, 0xdc, 0x9c, 0xbc, 0xb7, 0x6c, 0xbb, 0x80, 0xfc, 0x7b, 0xb0, 0x57, 0x40, 0x05, 0x40,
        0x00, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x00, 0x00, 0x32, 0xd2, 0xa6, 0x5d, 0x73, 0x12,
        0x16, 0x5a, 0x7f, 0x63, 0xda, 0x76, 0xd4, 0xd0, 0xaa, 0xc8, 0xab, 0xc4, 0xc0, 0x06,
    ];

    /// A git-generated v3 index with `CE_SKIP_WORKTREE` reads back with the bit set.
    #[test]
    fn index_reads_git_v3_skip_worktree_fixture() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("index-v3-git");
        std::fs::write(&path, GIT_V3_SKIP_WORKTREE_FIXTURE).unwrap();

        let index = Index::from_file(&path).unwrap();
        assert_eq!(index.size(), 1);
        let entry = index.get("a.txt", 0).expect("fixture entry");
        assert_eq!(entry.mode, 0o100644);
        assert!(entry.flags.skip_worktree, "CE_SKIP_WORKTREE must be set");
        assert!(!entry.flags.intent_to_add);
    }

    /// An unknown extended bit fails closed instead of being silently dropped.
    #[test]
    fn index_rejects_unknown_extended_bit() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("index-bad-extended");

        let mut raw = GIT_V3_SKIP_WORKTREE_FIXTURE.to_vec();
        raw[74] = 0x10; // extended word 0x4000 -> 0x1000 (unknown bit)
        raw[75] = 0x00;
        let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha1);
        hasher.update(&raw[..raw.len() - 20]);
        let checksum = hasher.finalize_object_hash();
        raw.truncate(raw.len() - 20);
        raw.extend_from_slice(checksum.as_ref());
        std::fs::write(&path, &raw).unwrap();

        let error = match Index::from_file(&path) {
            Ok(_) => panic!("an index with an unknown extended bit must fail closed"),
            Err(error) => error,
        };
        assert!(
            matches!(error, GitError::InvalidIndexFile(_)),
            "unexpected error: {error:?}"
        );
    }

    /// Writing extended flags forces index v3 and survives a round trip.
    #[test]
    fn index_v3_round_trip_preserves_extended_flags() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("index-v3-round-trip");

        let mut index = Index::new();
        let hash = ObjectHash::from_bytes(&[0x11u8; 20]).unwrap();
        let mut skip = IndexEntry::new_from_blob("skip.txt".to_string(), hash, 7);
        skip.flags.skip_worktree = true;
        index.update(skip);
        let hash = ObjectHash::from_bytes(&[0x22u8; 20]).unwrap();
        let mut ita = IndexEntry::new_from_blob("ita.txt".to_string(), hash, 9);
        ita.flags.intent_to_add = true;
        index.update(ita);

        index.to_file(&path).unwrap();
        let raw = std::fs::read(&path).unwrap();
        assert_eq!(&raw[..4], b"DIRC");
        assert_eq!(
            u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]),
            3,
            "extended flags must force version 3"
        );

        let loaded = Index::from_file(&path).unwrap();
        let skip = loaded.get("skip.txt", 0).unwrap();
        assert!(skip.flags.skip_worktree);
        assert!(!skip.flags.intent_to_add);
        let ita = loaded.get("ita.txt", 0).unwrap();
        assert!(ita.flags.intent_to_add);
        assert!(!ita.flags.skip_worktree);
    }

    /// Without extended bits the writer keeps emitting v2.
    #[test]
    fn index_without_extended_flags_stays_v2() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("index-v2-round-trip");

        let mut index = Index::new();
        let hash = ObjectHash::from_bytes(&[0x33u8; 20]).unwrap();
        index.update(IndexEntry::new_from_blob("plain.txt".to_string(), hash, 3));
        index.to_file(&path).unwrap();

        let raw = std::fs::read(&path).unwrap();
        assert_eq!(u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]), 2);
        let loaded = Index::from_file(&path).unwrap();
        let entry = loaded.get("plain.txt", 0).unwrap();
        assert!(!entry.flags.skip_worktree);
        assert!(!entry.flags.intent_to_add);
    }

    /// Test IndexEntry creation from file
    #[test]
    fn test_index_entry_create() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("Cargo.toml");

        let file = Path::new(source.as_path()); // use as a normal file
        let hash = ObjectHash::from_bytes(&[0; 20]).unwrap();
        let workdir = Path::new("../");
        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
        println!("{entry}");
    }

    /// Test IndexEntry creation from file with SHA256
    #[test]
    fn test_index_entry_create_sha256() {
        let _guard = set_hash_kind_for_test(HashKind::Sha256);
        let mut source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        source.push("Cargo.toml");

        let file = Path::new(source.as_path());
        let hash = ObjectHash::from_bytes(&[0u8; 32]).unwrap();
        let workdir = Path::new("../");
        let entry = IndexEntry::new_from_file(file, hash, workdir).unwrap();
        println!("{entry}");
    }

    /// A BLAKE3 index round-trips through `to_file_with_hash_kind` / `from_file_with_hash_kind`
    /// with the thread-local kind set to SHA-1, entry lookups return `ObjectHash::Blake3`, and
    /// reading the file as SHA-256 (same width) or writing a cross-kind entry fails closed.
    #[test]
    fn blake3_lookup() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("index-blake3");

        // Entry IDs are real blob IDs, as a status/commit flow would store them.
        let a = ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, b"a")
            .unwrap();
        let c = ObjectHash::from_type_and_data_for_kind(HashKind::Blake3, ObjectType::Blob, b"c")
            .unwrap();
        let mut index = Index::new();
        index.add(IndexEntry::new_from_blob("a.txt".to_string(), a, 1));
        index.add(IndexEntry::new_from_blob("b/c.txt".to_string(), c, 3));
        index
            .to_file_with_hash_kind(HashKind::Blake3, &path)
            .unwrap();

        let loaded = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
        assert_eq!(loaded.size(), 2);
        let got = loaded.get("a.txt", 0).expect("a.txt");
        assert_eq!(got.hash, a);
        assert_eq!(got.hash.kind(), HashKind::Blake3);
        assert_eq!(loaded.get("b/c.txt", 0).unwrap().hash, c);
        assert_eq!(
            loaded.tracked_files(),
            vec![PathBuf::from("a.txt"), PathBuf::from("b/c.txt")]
        );

        // Same width, different algorithm: the checksum does not verify.
        let err = Index::from_file_with_hash_kind(HashKind::Sha256, &path)
            .err()
            .expect("same-width SHA-256 read must fail");
        assert!(matches!(err, GitError::InvalidIndexFile(_)), "{err:?}");
        // The thread-local (SHA-1) legacy reader cannot read a BLAKE3 index either.
        assert!(Index::from_file(&path).is_err());

        // load/save with explicit kind.
        let missing =
            Index::load_with_hash_kind(HashKind::Blake3, temp_dir.path().join("none")).unwrap();
        assert_eq!(missing.size(), 0);
        let again = temp_dir.path().join("index-blake3-2");
        loaded
            .save_with_hash_kind(HashKind::Blake3, &again)
            .unwrap();
        assert_eq!(
            Index::load_with_hash_kind(HashKind::Blake3, &again)
                .unwrap()
                .size(),
            2
        );

        // A cross-kind entry is refused when writing.
        let mut mixed = Index::new();
        mixed.add(IndexEntry::new_from_blob(
            "x.txt".to_string(),
            ObjectHash::new_for_kind(HashKind::Sha256, b"x"),
            1,
        ));
        let mixed_path = temp_dir.path().join("mixed");
        let err = mixed
            .to_file_with_hash_kind(HashKind::Blake3, &mixed_path)
            .expect_err("cross-kind entry must fail");
        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
        // ... and the destination is untouched: no partial file, and an existing valid index
        // is not truncated.
        assert!(!mixed_path.exists());
        let before = std::fs::read(&path).unwrap();
        assert!(
            mixed
                .to_file_with_hash_kind(HashKind::Blake3, &path)
                .is_err()
        );
        assert_eq!(std::fs::read(&path).unwrap(), before);

        // Refreshing a BLAKE3 entry with another kind is refused and leaves it untouched;
        // the same kind recomputes the BLAKE3 blob ID of the file, which the entry
        // already carries, so the ID itself is unchanged.
        let work = temp_dir.path().join("work");
        std::fs::create_dir_all(&work).unwrap();
        std::fs::write(work.join("a.txt"), b"a").unwrap();
        let mut refreshed = Index::from_file_with_hash_kind(HashKind::Blake3, &path).unwrap();
        let err = refreshed
            .refresh_with_hash_kind(HashKind::Sha256, "a.txt", &work)
            .expect_err("cross-kind refresh must fail");
        assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
        assert_eq!(refreshed.get("a.txt", 0).unwrap().hash, a);
        refreshed
            .refresh_with_hash_kind(HashKind::Blake3, "a.txt", &work)
            .unwrap();
        let got = refreshed.get("a.txt", 0).unwrap().hash;
        assert_eq!(got.kind(), HashKind::Blake3);
        assert_eq!(got, a);
    }

    /// Regression test for <https://github.com/libra-tools/git-internal/issues/183>:
    /// `refresh_with_hash_kind` must recompute the blob ID — the digest of
    /// `"blob <size>\0" + content` — not the digest of the raw file bytes. An unchanged
    /// file whose entry carries the blob's real ID must be reported as unchanged and keep
    /// that ID; a modified file must flip to the new blob's ID.
    #[test]
    fn refresh_recomputes_the_blob_id_not_the_raw_file_hash() {
        let _guard = set_hash_kind_for_test(HashKind::Sha1);
        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
            let temp_dir = tempfile::tempdir().unwrap();
            let work = temp_dir.path();
            let content = b"hello, git-internal\n".to_vec();
            std::fs::write(work.join("a.txt"), &content).unwrap();

            let blob = Blob::from_content_bytes_with_kind(kind, content).unwrap();
            let mut index = Index::new();
            index.add(IndexEntry::new_from_file(Path::new("a.txt"), blob.id, work).unwrap());

            // The unchanged file must not flip to "changed", and the entry keeps the blob ID.
            let changed = index.refresh_with_hash_kind(kind, "a.txt", work).unwrap();
            assert!(!changed, "{kind:?}: unchanged file reported as changed");
            let got = index.get("a.txt", 0).unwrap().hash;
            assert_eq!(got, blob.id, "{kind:?}: entry hash must stay the blob ID");

            // A modified file is detected, and its entry hash becomes the new blob's ID.
            let new_content = b"changed\n".to_vec();
            std::fs::write(work.join("a.txt"), &new_content).unwrap();
            let changed = index.refresh_with_hash_kind(kind, "a.txt", work).unwrap();
            assert!(changed, "{kind:?}: modified file not reported as changed");
            let new_blob = Blob::from_content_bytes_with_kind(kind, new_content).unwrap();
            let got = index.get("a.txt", 0).unwrap().hash;
            assert_eq!(
                got, new_blob.id,
                "{kind:?}: entry hash must be the new blob ID"
            );
        }
    }
}