girt 0.10.0

An incremental, idiomatic Rust implementation of Git
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
#![warn(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable,
    clippy::indexing_slicing,
    reason = "parses untrusted repository or network input (#103)"
)]
use std::fmt;
use std::hash::Hash;
use std::str::FromStr;

mod id_hash;
pub(crate) use id_hash::{IdMap, IdSet, PeerIdMap, PeerIdSet};

/// The hash format used by a Git object database.
///
/// Object codecs, loose/packed storage, references, index v2/v3/v4, and wire fetch/push support
/// both formats. A repository selects one format from its local configuration; this type does not
/// translate identities between formats.
///
/// Match future formats explicitly rather than assuming the current hashes are the whole set:
///
/// ```
/// use girt::ObjectFormat;
///
/// let description = match ObjectFormat::Sha1 {
///     ObjectFormat::Sha1 => "SHA-1",
///     ObjectFormat::Sha256 => "SHA-256",
///     _ => "another Git hash format",
/// };
/// assert_eq!(description, "SHA-1");
/// ```
///
/// External exhaustive matches are rejected so adding a hash format remains compatible:
///
/// ```compile_fail,E0004
/// use girt::ObjectFormat;
///
/// fn hash_name(format: ObjectFormat) -> &'static str {
///     match format {
///         ObjectFormat::Sha1 => "sha1",
///         ObjectFormat::Sha256 => "sha256",
///     }
/// }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ObjectFormat {
    /// Git's SHA-1 object format, with 20-byte identities.
    Sha1,
    /// Git's SHA-256 object format, with 32-byte identities.
    Sha256,
}

impl fmt::Display for ObjectFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Sha1 => "sha1",
            Self::Sha256 => "sha256",
        })
    }
}

/// A format-bearing Git identity, independent of object existence or kind.
///
/// The variants contain exactly the meaningful digest bytes. Ordering places SHA-1 before SHA-256,
/// then compares bytes lexicographically. Parsing infers the format from exactly 40 or 64 ASCII
/// hexadecimal digits; display is lowercase. Abbreviations are rejected. Hashing does not provide
/// collision detection or translate identities between formats.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum ObjectId {
    /// A SHA-1 digest.
    Sha1([u8; 20]),
    /// A SHA-256 digest.
    Sha256([u8; 32]),
}

/// Hashes exactly the digest bytes, which are unique per format and length.
impl Hash for ObjectId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write(self.as_bytes());
    }
}

impl ObjectId {
    /// Hashes the canonical blob header and exact bytes in the selected format.
    pub fn for_blob(format: ObjectFormat, bytes: &[u8]) -> Self {
        format.hash_object(crate::ObjectKind::Blob, bytes)
    }

    #[cfg(test)]
    pub(crate) fn for_object(kind: &str, bytes: &[u8]) -> Self {
        hash_sha1(kind, bytes)
    }

    /// Constructs an identity from exactly the selected format's raw digest bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when the byte length differs from the selected format.
    pub fn from_bytes(format: ObjectFormat, bytes: &[u8]) -> Result<Self, ParseObjectIdError> {
        match format {
            ObjectFormat::Sha1 => bytes.try_into().map(Self::Sha1),
            ObjectFormat::Sha256 => bytes.try_into().map(Self::Sha256),
        }
        .map_err(|_| ParseObjectIdError)
    }

    /// Parses full hexadecimal digits and requires the selected format.
    ///
    /// # Errors
    ///
    /// Rejects wrong widths, non-ASCII/non-hexadecimal bytes, and the other format.
    pub fn from_hex(format: ObjectFormat, value: &str) -> Result<Self, ParseObjectIdError> {
        let id: Self = value.parse()?;
        if id.format() != format {
            return Err(ParseObjectIdError);
        }
        Ok(id)
    }

    /// Returns the digest format, without inspecting storage.
    pub const fn format(self) -> ObjectFormat {
        match self {
            Self::Sha1(_) => ObjectFormat::Sha1,
            Self::Sha256(_) => ObjectFormat::Sha256,
        }
    }

    /// Borrows only the meaningful digest bytes (20 or 32 bytes).
    pub const fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Sha1(bytes) => bytes,
            Self::Sha256(bytes) => bytes,
        }
    }

    /// Returns the all-zero sentinel for a selected format; no existence check occurs.
    pub const fn null(format: ObjectFormat) -> Self {
        match format {
            ObjectFormat::Sha1 => Self::Sha1([0; 20]),
            ObjectFormat::Sha256 => Self::Sha256([0; 32]),
        }
    }

    /// Reports whether every meaningful digest byte is zero.
    pub fn is_null(self) -> bool {
        self.as_bytes().iter().all(|&b| b == 0)
    }

    pub(crate) fn require_format(self, expected: ObjectFormat) -> Result<(), ObjectFormatError> {
        if self.format() == expected {
            Ok(())
        } else {
            Err(ObjectFormatError {
                expected,
                actual: self.format(),
            })
        }
    }
}

impl ObjectFormat {
    /// Number of raw bytes in a digest of this format.
    pub const fn digest_len(self) -> usize {
        match self {
            Self::Sha1 => 20,
            Self::Sha256 => 32,
        }
    }

    /// Hashes canonical Git framing and an uninterpreted object payload.
    ///
    /// Does not validate the payload or translate embedded object references. Storage and codecs
    /// support both formats. The caller chooses the format appropriate to the payload.
    ///
    /// ```
    /// use girt::{ObjectFormat, ObjectId, ObjectKind};
    /// let id = ObjectFormat::Sha256.hash_object(ObjectKind::Blob, b"hello\n");
    /// assert_eq!(id.format(), ObjectFormat::Sha256);
    /// assert_eq!(id.to_string().parse::<ObjectId>()?, id);
    /// assert_eq!(id.as_bytes().len(), 32);
    /// # Ok::<(), girt::ParseObjectIdError>(())
    /// ```
    pub fn hash_object(self, kind: crate::ObjectKind, bytes: &[u8]) -> ObjectId {
        #[cfg(test)]
        HASHES.with(|hashes| hashes.set(hashes.get() + 1));
        match self {
            Self::Sha1 => hash_sha1(kind.as_str(), bytes),
            Self::Sha256 => {
                let mut hash = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256);
                hash.update(object_header(kind.as_str(), bytes.len()).as_bytes());
                hash.update(bytes);
                ObjectId::Sha256(digest(hash))
            }
        }
    }
}

/// Incremental checksum in the repository's selected storage format.
#[derive(Clone)]
pub(crate) enum Hasher {
    Sha1(aws_lc_rs::digest::Context),
    Sha256(aws_lc_rs::digest::Context),
}

impl Hasher {
    pub(crate) fn new(format: ObjectFormat) -> Self {
        match format {
            ObjectFormat::Sha1 => Self::Sha1(aws_lc_rs::digest::Context::new(
                &aws_lc_rs::digest::SHA1_FOR_LEGACY_USE_ONLY,
            )),
            ObjectFormat::Sha256 => {
                Self::Sha256(aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256))
            }
        }
    }

    pub(crate) fn update(&mut self, bytes: &[u8]) {
        match self {
            Self::Sha1(hash) => hash.update(bytes),
            Self::Sha256(hash) => hash.update(bytes),
        }
    }

    pub(crate) fn finalize(self) -> ObjectId {
        match self {
            Self::Sha1(hash) => ObjectId::Sha1(digest(hash)),
            Self::Sha256(hash) => ObjectId::Sha256(digest(hash)),
        }
    }
}

impl ObjectFormat {
    pub(crate) fn checksum(self, bytes: &[u8]) -> ObjectId {
        let mut hash = Hasher::new(self);
        hash.update(bytes);
        hash.finalize()
    }
}

fn hash_sha1(kind: &str, bytes: &[u8]) -> ObjectId {
    let mut hash = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA1_FOR_LEGACY_USE_ONLY);
    hash.update(object_header(kind, bytes.len()).as_bytes());
    hash.update(bytes);
    ObjectId::Sha1(digest(hash))
}

/// Finishes a digest whose algorithm was chosen for an `N`-byte identity.
#[expect(
    clippy::expect_used,
    reason = "SHA-1 and SHA-256 contexts always produce 20 and 32 bytes, matching each caller's N"
)]
fn digest<const N: usize>(hash: aws_lc_rs::digest::Context) -> [u8; N] {
    hash.finish()
        .as_ref()
        .try_into()
        .expect("digest length matches the selected algorithm")
}

impl fmt::Display for ObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_bytes() {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl FromStr for ObjectId {
    type Err = ParseObjectIdError;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let format = match value.len() {
            40 => ObjectFormat::Sha1,
            64 => ObjectFormat::Sha256,
            _ => return Err(ParseObjectIdError),
        };
        if !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(ParseObjectIdError);
        }
        let mut id = Self::null(format);
        let bytes: &mut [u8] = match &mut id {
            Self::Sha1(bytes) => bytes,
            Self::Sha256(bytes) => bytes,
        };
        for (index, byte) in bytes.iter_mut().enumerate() {
            *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
                .map_err(|_| ParseObjectIdError)?;
        }
        Ok(id)
    }
}

/// Invalid raw digest length or a string other than 40/64 ASCII hexadecimal digits.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("expected a format-sized digest or 40/64 hexadecimal digits")]
pub struct ParseObjectIdError;

/// An identity uses a format unsupported by the selected operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("object format mismatch: expected {expected}, got {actual}")]
pub struct ObjectFormatError {
    /// Format required by the operation.
    pub expected: ObjectFormat,
    /// Format carried by the supplied identity.
    pub actual: ObjectFormat,
}

/// Encodes a blob as `blob <decimal byte length>\0` followed by its unchanged bytes.
///
/// A blob is an uninterpreted byte sequence; filenames and text encodings are not part of it.
/// [`ObjectId::for_blob`] hashes this representation to derive the blob's identity.
///
/// The returned buffer is uncompressed; loose storage adds zlib compression. No text encoding,
/// newline normalization, or Git attributes are applied.
///
/// ```
/// assert_eq!(girt::encode_blob(b"a\0\xff"), b"blob 3\0a\0\xff");
/// ```
pub fn encode_blob(bytes: &[u8]) -> Vec<u8> {
    let mut encoded = object_header("blob", bytes.len()).into_bytes();
    encoded.extend_from_slice(bytes);
    encoded
}

pub(crate) fn object_header(kind: &str, length: usize) -> String {
    format!("{kind} {length}\0")
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    /// Checks exact headers at decimal-length transitions and preservation of all byte values.
    /// Literal identities were independently verified with Python and Git; provenance is in
    /// docs/compatibility.md.
    #[rstest]
    #[case::nine_bytes(vec![b'x'; 9], b"blob 9\0", "aab1169962b9fd16c9465117c12cad0ffd8bffac")]
    #[case::ten_bytes(vec![b'x'; 10], b"blob 10\0", "72035e10b5524757f990eb198acfce358b268c12")]
    #[case::ninety_nine_bytes(vec![b'x'; 99], b"blob 99\0", "9e84ea89f5f5200b6ef0350a87885d5d3f39e453")]
    #[case::one_hundred_bytes(vec![b'x'; 100], b"blob 100\0", "f6be7cae2045aac11912ea642bf7f9d5d261f63b")]
    #[case::all_byte_values((0..=255).collect(), b"blob 256\0", "c86626638e0bc8cf47ca49bb1525b40e9737ee64")]
    fn encodes_and_identifies_blob_bytes(
        #[case] bytes: Vec<u8>,
        #[case] header: &[u8],
        #[case] expected_id: &str,
    ) {
        let expected_encoding = [header, bytes.as_slice()].concat();

        assert_eq!(encode_blob(&bytes), expected_encoding);
        assert_eq!(
            ObjectId::for_blob(crate::ObjectFormat::Sha1, &bytes).to_string(),
            expected_id
        );
    }

    /// Keeps format display names compatible with the names used in Git configuration.
    #[rstest]
    #[case::sha1(ObjectFormat::Sha1, "sha1")]
    #[case::sha256(ObjectFormat::Sha256, "sha256")]
    fn displays_git_object_format_names(#[case] format: ObjectFormat, #[case] expected: &str) {
        assert_eq!(format.to_string(), expected);
    }

    /// Accepts either hexadecimal case as the same full SHA-1 identity.
    #[rstest]
    #[case::lowercase("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391")]
    #[case::uppercase("E69DE29BB2D1D6434B8B29AE775AD8C2E48C5391")]
    fn parses_full_sha1_identifiers(#[case] value: &str) {
        let id = ObjectId::for_blob(crate::ObjectFormat::Sha1, b"");
        assert_eq!(value.parse(), Ok(id));
    }

    /// Checks that raw-byte construction and access preserve all identity bytes.
    #[test]
    fn preserves_raw_identity_bytes() {
        let id = ObjectId::for_blob(crate::ObjectFormat::Sha1, b"");
        assert_eq!(
            ObjectId::from_bytes(id.format(), id.as_bytes()).unwrap(),
            id
        );
    }

    /// Rejects abbreviated, non-hexadecimal, and non-ASCII identity strings.
    #[rstest]
    #[case::abbreviated("abc".to_owned())]
    #[case::non_hexadecimal("g".repeat(40))]
    #[case::non_ascii("é".repeat(20))]
    fn rejects_invalid_sha1_identifiers(#[case] value: String) {
        assert_eq!(value.parse::<ObjectId>(), Err(ParseObjectIdError));
    }
}

#[cfg(test)]
mod format_tests {
    use std::collections::{BTreeMap, HashMap};

    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1, 20)]
    #[case::sha256(ObjectFormat::Sha256, 32)]
    fn preserves_full_digest_and_null(#[case] format: ObjectFormat, #[case] length: usize) {
        let mut bytes = vec![0; length];
        bytes[length - 1] = 0xff;
        let id = ObjectId::from_bytes(format, &bytes).unwrap();
        assert_eq!(id.as_bytes(), bytes);
        assert_eq!(format.digest_len(), length);
        assert!(!id.is_null());
        assert!(ObjectId::null(format).is_null());
        assert_eq!(ObjectId::null(format).to_string(), "0".repeat(length * 2));
        assert_eq!(
            ObjectId::from_hex(format, &id.to_string().to_uppercase()),
            Ok(id)
        );
    }

    #[rstest]
    #[case::sha1_short(ObjectFormat::Sha1, 19)]
    #[case::sha1_long(ObjectFormat::Sha1, 21)]
    #[case::sha1_other(ObjectFormat::Sha1, 32)]
    #[case::sha256_short(ObjectFormat::Sha256, 31)]
    #[case::sha256_long(ObjectFormat::Sha256, 33)]
    #[case::sha256_other(ObjectFormat::Sha256, 20)]
    fn rejects_wrong_raw_width(#[case] format: ObjectFormat, #[case] length: usize) {
        assert_eq!(
            ObjectId::from_bytes(format, &vec![0; length]),
            Err(ParseObjectIdError)
        );
    }

    #[rstest]
    #[case::short_sha1("0".repeat(39))]
    #[case::long_sha1("0".repeat(41))]
    #[case::short_sha256("0".repeat(63))]
    #[case::long_sha256("0".repeat(65))]
    #[case::invalid_sha256("g".repeat(64))]
    #[case::unicode_sha256("é".repeat(32))]
    fn rejects_invalid_hex(#[case] value: String) {
        assert_eq!(value.parse::<ObjectId>(), Err(ParseObjectIdError));
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1, ObjectFormat::Sha256)]
    #[case::sha256(ObjectFormat::Sha256, ObjectFormat::Sha1)]
    fn rejects_other_formats_hex(#[case] expected: ObjectFormat, #[case] actual: ObjectFormat) {
        assert_eq!(
            ObjectId::from_hex(expected, &ObjectId::null(actual).to_string()),
            Err(ParseObjectIdError)
        );
    }

    /// Equal prefixes, nulls and differences in the final byte remain distinct lookup keys.
    #[test]
    fn mixed_format_keys_preserve_all_bytes() {
        let sha1 = ObjectId::null(ObjectFormat::Sha1);
        let sha256 = ObjectId::null(ObjectFormat::Sha256);
        let mut bytes = [0; 32];
        bytes[31] = 1;
        let tail = ObjectId::Sha256(bytes);
        let ordered = BTreeMap::from([(tail, "tail"), (sha256, "sha256"), (sha1, "sha1")]);
        let hashed = HashMap::from([(sha1, 1), (sha256, 2), (tail, 3)]);
        assert_eq!(
            ordered.into_keys().collect::<Vec<_>>(),
            [sha1, sha256, tail]
        );
        assert_eq!(hashed.len(), 3);
        assert_eq!(hashed[&sha1], 1);
        assert_eq!(hashed[&sha256], 2);
        assert_eq!(hashed[&tail], 3);
    }
}

#[cfg(test)]
thread_local! {
    /// Per-thread work observation for identity-verification regression tests.
    pub(crate) static HASHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}