Skip to main content

grit_lib/objects/
core.rs

1//! Git object model: object IDs, kinds, and in-memory representations.
2//!
3//! # Object ID
4//!
5//! [`ObjectId`] is a 20-byte SHA-1 digest.  It implements `Display` as
6//! lowercase hex, `FromStr` from a 40-character hex string, and the standard
7//! ordering traits so it can be used as a map key.
8//!
9//! # Object Kind
10//!
11//! [`ObjectKind`] represents the four Git object types: blob, tree, commit,
12//! and tag.  The raw header byte-slice is parsed with [`ObjectKind::from_bytes`].
13//!
14//! # Parsed objects
15//!
16//! [`Object`] bundles a kind and its raw (decompressed, header-stripped) byte
17//! content.  Higher-level parsed forms (e.g. [`TreeEntry`], [`CommitData`])
18//! live in this module and are produced by fallible `TryFrom<&Object>`
19//! conversions.
20
21use crate::error::ObjectError;
22use std::fmt;
23use std::str::FromStr;
24
25use crate::commit_encoding;
26use crate::error::{Error, Result};
27
28/// A Git hash algorithm.
29///
30/// Git supports two object-id hash functions: the historical SHA-1 (20-byte
31/// digests, 40 hex chars) and the newer SHA-256 (32-byte digests, 64 hex
32/// chars). A repository's algorithm is recorded in `extensions.objectformat`.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
34pub enum HashAlgo {
35    /// SHA-1 — 20-byte digests.
36    #[default]
37    Sha1,
38    /// SHA-256 — 32-byte digests.
39    Sha256,
40}
41
42impl HashAlgo {
43    /// The raw digest length in bytes (20 for SHA-1, 32 for SHA-256).
44    #[must_use]
45    pub const fn len(self) -> usize {
46        match self {
47            Self::Sha1 => 20,
48            Self::Sha256 => 32,
49        }
50    }
51
52    /// Always false — every hash algorithm has a non-zero digest length.
53    #[must_use]
54    pub const fn is_empty(self) -> bool {
55        false
56    }
57
58    /// The hex-encoded digest length (40 for SHA-1, 64 for SHA-256).
59    #[must_use]
60    pub const fn hex_len(self) -> usize {
61        self.len() * 2
62    }
63
64    /// The lowercase name as written in `extensions.objectformat`.
65    #[must_use]
66    pub const fn name(self) -> &'static str {
67        match self {
68            Self::Sha1 => "sha1",
69            Self::Sha256 => "sha256",
70        }
71    }
72
73    /// The `oid_version` byte used in `.idx`/multi-pack-index headers
74    /// (SHA-1 → 1, SHA-256 → 2).
75    #[must_use]
76    pub const fn oid_version(self) -> u8 {
77        match self {
78            Self::Sha1 => 1,
79            Self::Sha256 => 2,
80        }
81    }
82
83    /// Parse from the name used in `extensions.objectformat` config.
84    #[must_use]
85    pub fn from_name(name: &str) -> Option<Self> {
86        match name.trim() {
87            v if v.eq_ignore_ascii_case("sha1") => Some(Self::Sha1),
88            v if v.eq_ignore_ascii_case("sha256") => Some(Self::Sha256),
89            _ => None,
90        }
91    }
92
93    /// The algorithm implied by a raw digest length, if recognised.
94    #[must_use]
95    pub const fn from_len(len: usize) -> Option<Self> {
96        match len {
97            20 => Some(Self::Sha1),
98            32 => Some(Self::Sha256),
99            _ => None,
100        }
101    }
102}
103
104/// Error when converting an on-disk hash-version byte to [`HashAlgo`].
105#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
106#[error("unknown Git hash version byte {0} (expected 1 for SHA-1 or 2 for SHA-256)")]
107pub struct HashVersionError(pub u8);
108
109impl From<HashAlgo> for u8 {
110    fn from(algo: HashAlgo) -> Self {
111        algo.oid_version()
112    }
113}
114
115impl TryFrom<u8> for HashAlgo {
116    type Error = HashVersionError;
117
118    fn try_from(version: u8) -> std::result::Result<Self, Self::Error> {
119        match version {
120            1 => Ok(Self::Sha1),
121            2 => Ok(Self::Sha256),
122            other => Err(HashVersionError(other)),
123        }
124    }
125}
126
127/// Maximum raw digest length across supported hash algorithms (SHA-256).
128const MAX_OID_LEN: usize = 32;
129
130#[cold]
131fn invalid_oid_bytes(bytes: &[u8]) -> Error {
132    Error::Object(ObjectError::InvalidId {
133        input: hex::encode(bytes),
134    })
135}
136
137/// Number of hex digits in the fixed-width short form of an object id.
138pub const SHORT_HEX_LEN: usize = 7;
139
140/// The first [`SHORT_HEX_LEN`] characters of a hex object id, or all of `hex`
141/// when it is shorter.
142///
143/// Use this for display labels when only the hex string is at hand; with an
144/// [`ObjectId`], call [`ObjectId::to_short_hex`]. The result is not guaranteed to
145/// be unique in the repository.
146///
147/// # Parameters
148///
149/// - `hex`: a full or partial hex object id.
150///
151/// # Returns
152///
153/// A prefix borrowed from `hex`; never panics, even on non-ASCII input.
154#[must_use]
155pub fn short_hex(hex: &str) -> &str {
156    hex.get(..SHORT_HEX_LEN).unwrap_or(hex)
157}
158
159/// Canonical SHA-1 empty tree digest (`4b825dc642cb6eb9a060e54bf8d69288fbee4904`).
160const WELL_KNOWN_EMPTY_TREE_CANON: [u8; 20] = [
161    0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60, 0xe5, 0x4b, 0xf8, 0xd6, 0x92, 0x88,
162    0xfb, 0xee, 0x49, 0x04,
163];
164/// Legacy typo empty tree digest still referenced by some tests (`…899d69f7c6948d4`).
165const WELL_KNOWN_EMPTY_TREE_LEGACY: [u8; 20] = [
166    0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60, 0xe5, 0x4b, 0xf8, 0x99, 0xd6, 0x9f,
167    0x7c, 0x69, 0x48, 0xd4,
168];
169/// SHA-256 empty tree digest (`6ef19b41…decc5321`).
170const EMPTY_TREE_SHA256: [u8; 32] = [
171    0x6e, 0xf1, 0x9b, 0x41, 0x22, 0x5c, 0x53, 0x69, 0xf1, 0xc1, 0x04, 0xd4, 0x5d, 0x8d, 0x85, 0xef,
172    0xa9, 0xb0, 0x57, 0xb5, 0x3b, 0x14, 0xb4, 0xb9, 0xb9, 0x39, 0xdd, 0x74, 0xde, 0xcc, 0x53, 0x21,
173];
174/// SHA-1 digest of the empty blob (`e69de29bb2d1d6434b8b29ae775ad8c2e48c5391`).
175const EMPTY_BLOB_SHA1: [u8; 20] = [
176    0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a, 0xd8, 0xc2,
177    0xe4, 0x8c, 0x53, 0x91,
178];
179/// SHA-256 digest of the empty blob (`473a0f4c…303721813`).
180const EMPTY_BLOB_SHA256: [u8; 32] = [
181    0x47, 0x3a, 0x0f, 0x4c, 0x3b, 0xe8, 0xa9, 0x36, 0x81, 0xa2, 0x67, 0xe3, 0xb1, 0xe9, 0xa7, 0xdc,
182    0xda, 0x11, 0x85, 0x43, 0x6f, 0xe1, 0x41, 0xf7, 0x74, 0x91, 0x20, 0xa3, 0x03, 0x72, 0x18, 0x13,
183];
184
185/// A Git object identifier: a SHA-1 (20-byte) or SHA-256 (32-byte) digest.
186///
187/// The digest is stored in a fixed 32-byte buffer with an explicit length;
188/// bytes beyond `len` are always zero, so the derived `Eq`/`Ord`/`Hash`
189/// remain correct. The hash algorithm is inferred from the length.
190///
191/// # Examples
192///
193/// ```
194/// use grit_lib::objects::ObjectId;
195///
196/// # fn main() -> grit_lib::error::Result<()> {
197/// let id = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904")?;
198/// assert_eq!(id.to_hex(), "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
199/// # Ok(())
200/// # }
201/// ```
202#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
203pub struct ObjectId {
204    bytes: [u8; MAX_OID_LEN],
205    len: u8,
206}
207
208impl ObjectId {
209    /// The all-zero SHA-1 object id (Git's "null" OID).
210    ///
211    /// Used for index placeholders such as intent-to-add entries and for
212    /// special cases in plumbing output. For an algorithm-specific null OID
213    /// (e.g. 64 zeros in a SHA-256 repo) use [`ObjectId::null`].
214    #[must_use]
215    pub const fn zero() -> Self {
216        Self {
217            bytes: [0u8; MAX_OID_LEN],
218            len: 20,
219        }
220    }
221
222    /// The all-zero ("null") object id for a given hash algorithm.
223    #[must_use]
224    pub const fn null(algo: HashAlgo) -> Self {
225        Self {
226            bytes: [0u8; MAX_OID_LEN],
227            len: algo.len() as u8,
228        }
229    }
230
231    /// Construct from a raw digest slice (20 bytes for SHA-1, 32 for SHA-256).
232    ///
233    /// # Errors
234    ///
235    /// Returns [`crate::error::ObjectError::InvalidId`] when `bytes` is not a recognised
236    /// digest length.
237    #[inline]
238    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
239        let mut buf = [0u8; MAX_OID_LEN];
240        // Fixed-size copies, so tree and index parsers get no `memcpy` call per id.
241        match HashAlgo::from_len(bytes.len()) {
242            Some(HashAlgo::Sha1) => buf[..20].copy_from_slice(bytes),
243            Some(HashAlgo::Sha256) => buf.copy_from_slice(bytes),
244            None => return Err(invalid_oid_bytes(bytes)),
245        }
246        Ok(Self {
247            bytes: buf,
248            len: bytes.len() as u8,
249        })
250    }
251
252    /// Raw digest bytes (20 or 32 bytes depending on the hash algorithm).
253    #[must_use]
254    pub fn as_bytes(&self) -> &[u8] {
255        &self.bytes[..self.len as usize]
256    }
257
258    /// The hash algorithm this OID belongs to.
259    #[must_use]
260    pub fn algo(&self) -> HashAlgo {
261        HashAlgo::from_len(self.len as usize).unwrap_or(HashAlgo::Sha1)
262    }
263
264    /// Check if this is the null (all-zero) object ID.
265    #[must_use]
266    pub fn is_zero(&self) -> bool {
267        self.as_bytes().iter().all(|&b| b == 0)
268    }
269
270    /// Number of leading hex digits this id shares with `other`.
271    #[must_use]
272    pub(crate) fn common_prefix_nibbles(&self, other: &Self) -> usize {
273        let (a, b) = (self.as_bytes(), other.as_bytes());
274        match a.iter().zip(b).position(|(x, y)| x != y) {
275            Some(i) => i * 2 + usize::from((a[i] ^ b[i]) & 0xf0 == 0),
276            None => a.len().min(b.len()) * 2,
277        }
278    }
279
280    /// Whether this OID is the empty blob for its hash algorithm (SHA-1 or SHA-256).
281    #[must_use]
282    pub(crate) fn is_empty_blob(&self) -> bool {
283        let bytes = self.as_bytes();
284        bytes == EMPTY_BLOB_SHA1 || bytes == EMPTY_BLOB_SHA256
285    }
286
287    /// Whether this OID is Git's well-known empty tree (canonical or legacy typo hash).
288    #[must_use]
289    pub(crate) fn is_well_known_empty_tree(&self) -> bool {
290        self.is_canonical_empty_tree()
291            || (self.as_bytes().len() == HashAlgo::Sha1.len()
292                && self.as_bytes() == WELL_KNOWN_EMPTY_TREE_LEGACY)
293    }
294
295    /// Whether this OID is the empty tree of a repository using `algo`, including the legacy
296    /// SHA-1 typo id.
297    #[must_use]
298    pub(crate) fn is_empty_tree_for(&self, algo: HashAlgo) -> bool {
299        match algo {
300            HashAlgo::Sha1 => self.is_well_known_empty_tree(),
301            HashAlgo::Sha256 => self.as_bytes() == EMPTY_TREE_SHA256,
302        }
303    }
304
305    /// Whether this OID is the canonical SHA-1 empty tree (`4b825dc6…4904`).
306    #[must_use]
307    pub(crate) fn is_canonical_empty_tree(&self) -> bool {
308        self.as_bytes().len() == HashAlgo::Sha1.len()
309            && self.as_bytes() == WELL_KNOWN_EMPTY_TREE_CANON
310    }
311
312    /// Canonical SHA-1 empty tree object id (`4b825dc642cb6eb9a060e54bf8d69288fbee4904`).
313    ///
314    /// Returns the well-known digest without writing a loose object. On SHA-256
315    /// repositories use [`Odb::empty_tree_oid`](crate::odb::Odb::empty_tree_oid)
316    /// instead.
317    #[must_use]
318    pub const fn empty_tree() -> Self {
319        let mut bytes = [0u8; MAX_OID_LEN];
320        let mut i = 0;
321        while i < WELL_KNOWN_EMPTY_TREE_CANON.len() {
322            bytes[i] = WELL_KNOWN_EMPTY_TREE_CANON[i];
323            i += 1;
324        }
325        Self { bytes, len: 20 }
326    }
327
328    /// Append `/<xx>/<rest-of-hex>` for this OID under `path` without heap hex strings.
329    pub(crate) fn push_loose_relative(&self, path: &mut std::path::PathBuf) {
330        const HEX: &[u8; 16] = b"0123456789abcdef";
331        let bytes = self.as_bytes();
332        let prefix = [
333            HEX[(bytes[0] >> 4) as usize],
334            HEX[(bytes[0] & 0xf) as usize],
335        ];
336        // SAFETY: `prefix` and `suffix` are ASCII hex digits only.
337        path.push(unsafe { std::str::from_utf8_unchecked(&prefix) });
338        let suffix_len = (bytes.len() - 1) * 2;
339        let mut suffix = [0u8; 62];
340        for (i, &b) in bytes[1..].iter().enumerate() {
341            suffix[i * 2] = HEX[(b >> 4) as usize];
342            suffix[i * 2 + 1] = HEX[(b & 0xf) as usize];
343        }
344        path.push(unsafe { std::str::from_utf8_unchecked(&suffix[..suffix_len]) });
345    }
346
347    /// Build `<objects-dir>/<xx>/<rest>` for this OID without intermediate hex [`String`]s.
348    #[must_use]
349    pub(crate) fn loose_path_in(&self, objects_dir: &std::path::Path) -> std::path::PathBuf {
350        let mut path = objects_dir.to_path_buf();
351        self.push_loose_relative(&mut path);
352        path
353    }
354
355    /// Lowercase hex representation (40 or 64 characters).
356    #[must_use]
357    pub fn to_hex(&self) -> String {
358        self.hex_digits().as_str().to_owned()
359    }
360
361    /// Append the lowercase hex representation to `out` without an intermediate [`String`].
362    pub(crate) fn push_hex_to(&self, out: &mut String) {
363        out.push_str(self.hex_digits().as_str());
364    }
365
366    /// The first [`SHORT_HEX_LEN`] lowercase hex digits, for human-facing labels.
367    ///
368    /// This is a fixed-width prefix and is not guaranteed to be unique in the
369    /// repository; use [`crate::rev_parse::abbreviate_object_id`] when the
370    /// abbreviation must resolve back to this id.
371    #[must_use]
372    pub fn to_short_hex(&self) -> String {
373        short_hex(self.hex_digits().as_str()).to_owned()
374    }
375
376    /// The lowercase hex digits of this id, without allocating.
377    fn hex_digits(&self) -> HexDigits {
378        const DIGITS: &[u8; 16] = b"0123456789abcdef";
379        let mut buf = [0u8; MAX_OID_LEN * 2];
380        for (pair, &byte) in buf.as_chunks_mut::<2>().0.iter_mut().zip(self.as_bytes()) {
381            *pair = [
382                DIGITS[usize::from(byte >> 4)],
383                DIGITS[usize::from(byte & 0x0f)],
384            ];
385        }
386        HexDigits {
387            buf,
388            len: usize::from(self.len) * 2,
389        }
390    }
391
392    /// The two-character directory prefix used by the loose object store.
393    ///
394    /// Returns the first two hex chars (e.g. `"ab"` for `"ab3f…"`).
395    #[must_use]
396    pub fn loose_prefix(&self) -> String {
397        hex::encode(&self.bytes[..1])
398    }
399
400    /// Parse an object ID from a hex string (40 chars for SHA-1, 64 for
401    /// SHA-256).
402    ///
403    /// # Errors
404    ///
405    /// Returns [`crate::error::ObjectError::InvalidId`] if the string is not a valid hex OID.
406    pub fn from_hex(s: &str) -> Result<Self> {
407        Self::decode_hex(s.as_bytes()).ok_or_else(|| {
408            Error::Object(ObjectError::InvalidId {
409                input: s.to_owned(),
410            })
411        })
412    }
413
414    /// Parse a fixed-width lowercase/uppercase ASCII hex OID (40 chars for SHA-1).
415    ///
416    /// # Errors
417    ///
418    /// Returns [`crate::error::ObjectError::InvalidId`] when `bytes` is not exactly 40 hex digits.
419    pub fn from_hex_ascii(bytes: &[u8]) -> Result<Self> {
420        if bytes.len() != HashAlgo::Sha1.hex_len() {
421            return Err(Error::Object(ObjectError::InvalidId {
422                input: String::from_utf8_lossy(bytes).into_owned(),
423            }));
424        }
425        Self::decode_hex(bytes).ok_or_else(|| {
426            Error::Object(ObjectError::InvalidId {
427                input: String::from_utf8_lossy(bytes).into_owned(),
428            })
429        })
430    }
431
432    /// Decode 40 or 64 ASCII hex digits (either case); `None` for any other input.
433    ///
434    /// Ref listings and tree walks parse ids in bulk, so this avoids per-digit
435    /// branching and allocation: invalid digits are folded into one check at the end.
436    fn decode_hex(hex: &[u8]) -> Option<Self> {
437        let len = hex.len() / 2;
438        if !Self::is_hex_len(hex.len()) {
439            return None;
440        }
441        let mut bytes = [0u8; MAX_OID_LEN];
442        let mut invalid = 0u8;
443        for (out, pair) in bytes.iter_mut().zip(hex.as_chunks::<2>().0) {
444            let hi = HEX_DECODE[usize::from(pair[0])];
445            let lo = HEX_DECODE[usize::from(pair[1])];
446            invalid |= hi | lo;
447            *out = (hi << 4) | lo;
448        }
449        (invalid & HEX_INVALID == 0).then_some(Self {
450            bytes,
451            len: len as u8,
452        })
453    }
454
455    /// The suffix used as the filename inside the loose prefix dir (the digest
456    /// minus its first byte: 38 hex chars for SHA-1, 62 for SHA-256).
457    #[must_use]
458    pub fn loose_suffix(&self) -> String {
459        hex::encode(&self.bytes[1..self.len as usize])
460    }
461
462    /// Whether `s` is a full-length hex OID for a supported hash algorithm
463    /// (40 hex chars for SHA-1 or 64 for SHA-256), case-insensitive.
464    #[must_use]
465    pub fn is_full_hex(s: &str) -> bool {
466        (s.len() == HashAlgo::Sha1.hex_len() || s.len() == HashAlgo::Sha256.hex_len())
467            && s.bytes().all(|b| b.is_ascii_hexdigit())
468    }
469
470    /// Whether `len` is a valid full hex-OID length (40 or 64).
471    #[must_use]
472    pub const fn is_hex_len(len: usize) -> bool {
473        len == HashAlgo::Sha1.hex_len() || len == HashAlgo::Sha256.hex_len()
474    }
475
476    /// Whether `len` is a valid loose-object filename suffix length, i.e. a full
477    /// hex OID minus its first byte (38 for SHA-1, 62 for SHA-256).
478    #[must_use]
479    pub const fn is_loose_suffix_len(len: usize) -> bool {
480        len == HashAlgo::Sha1.hex_len() - 2 || len == HashAlgo::Sha256.hex_len() - 2
481    }
482}
483
484impl std::hash::Hash for ObjectId {
485    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
486        state.write(self.as_bytes());
487    }
488}
489
490impl fmt::Display for ObjectId {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        f.write_str(self.hex_digits().as_str())
493    }
494}
495
496/// Stack buffer holding an [`ObjectId`]'s hex digits.
497struct HexDigits {
498    buf: [u8; MAX_OID_LEN * 2],
499    len: usize,
500}
501
502impl HexDigits {
503    fn as_str(&self) -> &str {
504        std::str::from_utf8(&self.buf[..self.len]).unwrap_or_default()
505    }
506}
507
508impl fmt::Debug for ObjectId {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        write!(f, "ObjectId({})", self.to_hex())
511    }
512}
513
514#[cfg(feature = "serde-models")]
515impl serde::Serialize for ObjectId {
516    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
517    where
518        S: serde::Serializer,
519    {
520        serializer.serialize_str(&self.to_hex())
521    }
522}
523
524#[cfg(feature = "serde-models")]
525impl<'de> serde::Deserialize<'de> for ObjectId {
526    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
527    where
528        D: serde::Deserializer<'de>,
529    {
530        let hex = String::deserialize(deserializer)?;
531        Self::from_hex(&hex).map_err(serde::de::Error::custom)
532    }
533}
534
535/// Marker bit in [`HEX_DECODE`] for bytes that are not hex digits.
536const HEX_INVALID: u8 = 0x10;
537
538/// Nibble value of each ASCII hex digit; every other byte maps to [`HEX_INVALID`].
539const HEX_DECODE: [u8; 256] = {
540    let mut table = [HEX_INVALID; 256];
541    let mut i = 0u8;
542    while i < 10 {
543        table[(b'0' + i) as usize] = i;
544        i += 1;
545    }
546    let mut i = 0u8;
547    while i < 6 {
548        table[(b'a' + i) as usize] = 10 + i;
549        table[(b'A' + i) as usize] = 10 + i;
550        i += 1;
551    }
552    table
553};
554
555impl FromStr for ObjectId {
556    type Err = Error;
557
558    fn from_str(s: &str) -> Result<Self> {
559        Self::from_hex(s)
560    }
561}
562
563/// A Git file mode (`100644`, `100755`, `120000`, `160000`, `040000`), or
564/// [`FileMode::ABSENT`] for the missing side of an add or delete.
565///
566/// Displays and serializes as the six-digit octal text Git prints in raw diff
567/// output, so the zero mode reads `000000`.
568///
569/// # Examples
570///
571/// ```
572/// use grit_lib::objects::FileMode;
573///
574/// assert_eq!(FileMode::EXECUTABLE.to_string(), "100755");
575/// assert_eq!(FileMode::ABSENT.to_string(), "000000");
576/// assert_eq!(FileMode::new(0o120000), FileMode::SYMLINK);
577/// assert!(FileMode::SYMLINK.is_symlink());
578/// ```
579#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
580pub struct FileMode(u32);
581
582impl FileMode {
583    /// No entry on this side (an add's old side, a delete's new side).
584    pub const ABSENT: Self = Self(0);
585    /// Regular, non-executable file.
586    pub const REGULAR: Self = Self(0o100644);
587    /// Executable file.
588    pub const EXECUTABLE: Self = Self(0o100755);
589    /// Symbolic link.
590    pub const SYMLINK: Self = Self(0o120000);
591    /// Submodule commit (gitlink).
592    pub const GITLINK: Self = Self(0o160000);
593    /// Tree (directory).
594    pub const TREE: Self = Self(0o040000);
595
596    /// Wrap raw mode bits as stored in a tree entry or the index.
597    #[must_use]
598    pub const fn new(bits: u32) -> Self {
599        Self(bits)
600    }
601
602    /// The raw mode bits.
603    #[must_use]
604    pub const fn bits(self) -> u32 {
605        self.0
606    }
607
608    /// Whether this is [`Self::ABSENT`].
609    #[must_use]
610    pub const fn is_absent(self) -> bool {
611        self.0 == 0
612    }
613
614    /// The octal text, or `None` for [`Self::ABSENT`] (the missing side of an add or delete).
615    #[must_use]
616    pub fn octal_if_present(self) -> Option<String> {
617        (!self.is_absent()).then(|| self.to_string())
618    }
619
620    /// Whether the object-type bits name a symbolic link.
621    #[must_use]
622    pub const fn is_symlink(self) -> bool {
623        self.0 & 0o170000 == 0o120000
624    }
625
626    /// Whether the object-type bits name a gitlink (submodule commit).
627    #[must_use]
628    pub const fn is_gitlink(self) -> bool {
629        self.0 & 0o170000 == 0o160000
630    }
631}
632
633impl From<u32> for FileMode {
634    fn from(bits: u32) -> Self {
635        Self(bits)
636    }
637}
638
639impl From<FileMode> for u32 {
640    fn from(mode: FileMode) -> Self {
641        mode.0
642    }
643}
644
645impl fmt::Display for FileMode {
646    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647        write!(f, "{:06o}", self.0)
648    }
649}
650
651impl fmt::Debug for FileMode {
652    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653        write!(f, "FileMode({:06o})", self.0)
654    }
655}
656
657#[cfg(feature = "serde-models")]
658impl serde::Serialize for FileMode {
659    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
660    where
661        S: serde::Serializer,
662    {
663        serializer.collect_str(self)
664    }
665}
666
667/// A parsed abbreviated object id: the leading hex digits ("nibbles") of a digest.
668///
669/// Parse the user's hex once with [`ObjectIdPrefix::from_hex`], then test candidates
670/// with [`ObjectIdPrefix::matches`], which compares raw digest bytes without allocating.
671/// Sorted backends (pack indexes, key-value stores) can instead scan the inclusive id
672/// range [`ObjectIdPrefix::lowest`]..=[`ObjectIdPrefix::highest`], which holds exactly
673/// the ids that match.
674///
675/// # Examples
676///
677/// ```
678/// use grit_lib::objects::{HashAlgo, ObjectId, ObjectIdPrefix};
679///
680/// # fn main() -> grit_lib::error::Result<()> {
681/// let id = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904")?;
682/// let prefix = ObjectIdPrefix::from_hex("4B825", HashAlgo::Sha1)?;
683/// assert_eq!(prefix.nibbles(), 5);
684/// assert!(prefix.matches(&id));
685/// assert!(!ObjectIdPrefix::from_hex("4b826", HashAlgo::Sha1)?.matches(&id));
686/// assert!(prefix.lowest() <= id && id <= prefix.highest());
687/// # Ok(())
688/// # }
689/// ```
690#[derive(Clone, Copy, PartialEq, Eq)]
691pub struct ObjectIdPrefix {
692    /// Prefix digits packed two per byte; the low nibble of an odd-length tail and
693    /// every byte past it are zero.
694    bytes: [u8; MAX_OID_LEN],
695    nibbles: u8,
696    algo: HashAlgo,
697}
698
699impl ObjectIdPrefix {
700    /// Parse `hex` (either case, possibly empty) as a prefix of `algo` object ids.
701    ///
702    /// The empty prefix matches every id.
703    ///
704    /// # Errors
705    ///
706    /// Returns [`crate::error::ObjectError::InvalidId`] when `hex` contains a non-hex character or is
707    /// longer than a full `algo` id ([`HashAlgo::hex_len`]).
708    pub fn from_hex(hex: &str, algo: HashAlgo) -> Result<Self> {
709        let digits = hex.as_bytes();
710        if digits.len() > algo.hex_len() {
711            return Err(Error::Object(ObjectError::InvalidId {
712                input: hex.to_owned(),
713            }));
714        }
715        let mut bytes = [0u8; MAX_OID_LEN];
716        let mut invalid = 0u8;
717        for (i, &digit) in digits.iter().enumerate() {
718            let nibble = HEX_DECODE[usize::from(digit)];
719            invalid |= nibble;
720            let shift = if i.is_multiple_of(2) { 4 } else { 0 };
721            bytes[i / 2] |= (nibble & 0x0f) << shift;
722        }
723        if invalid & HEX_INVALID != 0 {
724            return Err(Error::Object(ObjectError::InvalidId {
725                input: hex.to_owned(),
726            }));
727        }
728        Ok(Self {
729            bytes,
730            nibbles: digits.len() as u8,
731            algo,
732        })
733    }
734
735    /// Number of hex digits in the prefix.
736    #[must_use]
737    pub fn nibbles(&self) -> usize {
738        usize::from(self.nibbles)
739    }
740
741    /// Whether the prefix has no digits (and so matches every id).
742    #[must_use]
743    pub fn is_empty(&self) -> bool {
744        self.nibbles == 0
745    }
746
747    /// Hash algorithm the prefix was parsed for.
748    #[must_use]
749    pub fn algo(&self) -> HashAlgo {
750        self.algo
751    }
752
753    /// Whether `oid` starts with this prefix.
754    ///
755    /// Compares raw digest bytes (masking the last byte for an odd digit count), so the
756    /// check never allocates. An id shorter than the prefix never matches.
757    #[must_use]
758    pub fn matches(&self, oid: &ObjectId) -> bool {
759        self.matches_digest(oid.as_bytes())
760    }
761
762    /// Like [`Self::matches`] for a raw digest slice (for example a pack index entry).
763    #[must_use]
764    pub(crate) fn matches_digest(&self, digest: &[u8]) -> bool {
765        let whole = self.nibbles() / 2;
766        let Some(head) = digest.get(..whole) else {
767            return false;
768        };
769        if head != &self.bytes[..whole] {
770            return false;
771        }
772        if self.nibbles.is_multiple_of(2) {
773            return true;
774        }
775        digest
776            .get(whole)
777            .is_some_and(|&b| b & 0xf0 == self.bytes[whole])
778    }
779
780    /// The smallest `algo` id that starts with this prefix (remaining digits all `0`).
781    #[must_use]
782    pub fn lowest(&self) -> ObjectId {
783        ObjectId {
784            bytes: self.bytes,
785            len: self.algo.len() as u8,
786        }
787    }
788
789    /// The largest `algo` id that starts with this prefix (remaining digits all `f`).
790    #[must_use]
791    pub fn highest(&self) -> ObjectId {
792        let mut bytes = self.bytes;
793        let whole = self.nibbles() / 2;
794        if !self.nibbles.is_multiple_of(2) {
795            bytes[whole] |= 0x0f;
796        }
797        let first_free = whole + usize::from(self.nibbles % 2);
798        bytes[first_free..self.algo.len()].fill(0xff);
799        ObjectId {
800            bytes,
801            len: self.algo.len() as u8,
802        }
803    }
804}
805
806impl fmt::Display for ObjectIdPrefix {
807    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
808        let hex = hex::encode(&self.bytes[..self.nibbles().div_ceil(2)]);
809        f.write_str(&hex[..self.nibbles()])
810    }
811}
812
813impl fmt::Debug for ObjectIdPrefix {
814    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815        write!(f, "ObjectIdPrefix({self})")
816    }
817}
818
819/// The four Git object types.
820#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
821#[cfg_attr(feature = "serde-models", derive(serde::Serialize))]
822#[cfg_attr(feature = "serde-models", serde(rename_all = "snake_case"))]
823pub enum ObjectKind {
824    /// A raw file snapshot.
825    Blob,
826    /// A directory listing.
827    Tree,
828    /// A snapshot with metadata and parentage.
829    Commit,
830    /// An annotated tag.
831    Tag,
832}
833
834impl ObjectKind {
835    /// Parse from the ASCII keyword used in Git object headers.
836    ///
837    /// # Errors
838    ///
839    /// Returns [`crate::error::ObjectError::UnknownType`] for unrecognised strings.
840    pub fn from_bytes(b: &[u8]) -> Result<Self> {
841        match b {
842            b"blob" => Ok(Self::Blob),
843            b"tree" => Ok(Self::Tree),
844            b"commit" => Ok(Self::Commit),
845            b"tag" => Ok(Self::Tag),
846            other => Err(Error::Object(ObjectError::UnknownType {
847                name: String::from_utf8_lossy(other).into_owned(),
848            })),
849        }
850    }
851
852    /// Parse the `type` field on an annotated tag object (Git `type_from_string_gently` rules).
853    ///
854    /// The tag header line is `type <typename>\n` where `typename` must match a known object type
855    /// keyword **exactly** (no extra characters, no strict prefix of a longer keyword).
856    #[must_use]
857    pub fn from_tag_type_field(line: &[u8]) -> Option<Self> {
858        fn keyword_matches(canonical: &[u8], field: &[u8]) -> bool {
859            if field.is_empty() {
860                return false;
861            }
862            for (i, &bc) in field.iter().enumerate() {
863                let sc = canonical.get(i).copied().unwrap_or(0);
864                if sc != bc {
865                    return false;
866                }
867            }
868            canonical.get(field.len()).copied().unwrap_or(0) == 0
869        }
870
871        const NAMES: &[(ObjectKind, &[u8])] = &[
872            (ObjectKind::Blob, b"blob"),
873            (ObjectKind::Tree, b"tree"),
874            (ObjectKind::Commit, b"commit"),
875            (ObjectKind::Tag, b"tag"),
876        ];
877        for &(kind, name) in NAMES {
878            if keyword_matches(name, line) {
879                return Some(kind);
880            }
881        }
882        None
883    }
884
885    /// The ASCII keyword for this kind (used in object headers).
886    #[must_use]
887    pub fn as_str(&self) -> &'static str {
888        match self {
889            Self::Blob => "blob",
890            Self::Tree => "tree",
891            Self::Commit => "commit",
892            Self::Tag => "tag",
893        }
894    }
895}
896
897impl fmt::Display for ObjectKind {
898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899        f.write_str(self.as_str())
900    }
901}
902
903impl FromStr for ObjectKind {
904    type Err = Error;
905
906    fn from_str(s: &str) -> Result<Self> {
907        Self::from_bytes(s.as_bytes())
908    }
909}
910
911/// Kind and uncompressed size of a Git object without loading its payload.
912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub struct ObjectInfo {
914    /// Object type after resolving any pack delta chain.
915    pub kind: ObjectKind,
916    /// Uncompressed byte length of the object body (after the header NUL).
917    pub size: u64,
918}
919
920/// A decompressed, header-stripped Git object.
921#[derive(Debug, Clone)]
922pub struct Object {
923    /// The type of this object.
924    pub kind: ObjectKind,
925    /// Raw byte content (everything after the NUL in the header).
926    pub data: Vec<u8>,
927}
928
929/// Borrowed view of an object's kind and uncompressed payload.
930///
931/// Produced by [`crate::odb::Odb::read_into`](crate::odb::Odb::read_into) and
932/// [`crate::odb::store::ObjectStore::read_into`](crate::odb::store::ObjectStore::read_into);
933/// the payload bytes live in the caller's buffer.
934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
935pub struct ObjectRef<'a> {
936    /// Object type after resolving any pack delta chain.
937    pub kind: ObjectKind,
938    /// Uncompressed payload (header stripped).
939    pub data: &'a [u8],
940}
941
942impl<'a> ObjectRef<'a> {
943    /// Borrow `buf` as an object payload with the given `kind`.
944    #[must_use]
945    pub fn from_buf(kind: ObjectKind, buf: &'a [u8]) -> Self {
946        Self { kind, data: buf }
947    }
948}
949
950impl Object {
951    /// Construct a new object from its kind and raw data.
952    #[must_use]
953    pub fn new(kind: ObjectKind, data: Vec<u8>) -> Self {
954        Self { kind, data }
955    }
956
957    /// Borrowed view of this object's kind and payload.
958    #[must_use]
959    pub fn as_ref(&self) -> ObjectRef<'_> {
960        ObjectRef {
961            kind: self.kind,
962            data: self.data.as_slice(),
963        }
964    }
965}
966
967/// A single entry in a Git tree object.
968#[derive(Debug, Clone, PartialEq, Eq)]
969pub struct TreeEntry {
970    /// Unix file mode (e.g. `0o100644` for a regular file, `0o040000` for a tree).
971    pub mode: u32,
972    /// Entry name (file or directory name only, no path separators).
973    pub name: Vec<u8>,
974    /// The object ID of the blob or sub-tree.
975    pub oid: ObjectId,
976}
977
978impl TreeEntry {
979    /// Format the mode as Git does: no leading zero, minimal digits.
980    ///
981    /// Git uses `"40000"` for trees (not `"040000"`), and `"100644"` for blobs.
982    #[must_use]
983    pub fn mode_str(&self) -> String {
984        // Git omits the leading zero for tree mode
985        if self.mode == 0o040000 {
986            "40000".to_owned()
987        } else {
988            format!("{:o}", self.mode)
989        }
990    }
991}
992
993/// A single tree entry borrowing name bytes from the tree object payload.
994#[derive(Debug, Clone, Copy, PartialEq, Eq)]
995pub struct TreeEntryRef<'a> {
996    /// Unix file mode (e.g. `0o100644` for a regular file, `0o040000` for a tree).
997    pub mode: u32,
998    /// Entry name (file or directory name only, no path separators).
999    pub name: &'a [u8],
1000    /// The object ID of the blob or sub-tree.
1001    pub oid: ObjectId,
1002}
1003
1004impl TreeEntryRef<'_> {
1005    /// Allocate an owning [`TreeEntry`] with the same mode, name, and OID.
1006    #[must_use]
1007    pub fn to_owned(&self) -> TreeEntry {
1008        TreeEntry {
1009            mode: self.mode,
1010            name: self.name.to_vec(),
1011            oid: self.oid,
1012        }
1013    }
1014}
1015
1016/// Iterator over tree entries borrowing from the tree object's raw payload.
1017///
1018/// Construct with [`Self::with_oid_len`] when the hash width is known, or
1019/// [`Self::infer_oid_len`] to detect SHA-1 vs SHA-256 like [`parse_tree`].
1020#[derive(Debug, Clone)]
1021pub struct TreeRefIter<'a> {
1022    data: &'a [u8],
1023    pos: usize,
1024    oid_len: usize,
1025    /// Set after the first parse error so callers do not see endless `Err` items.
1026    failed: bool,
1027}
1028
1029impl<'a> TreeRefIter<'a> {
1030    /// Iterate `data` assuming each entry ends with an OID of `oid_len` bytes.
1031    #[must_use]
1032    pub fn with_oid_len(data: &'a [u8], oid_len: usize) -> Self {
1033        Self {
1034            data,
1035            pos: 0,
1036            oid_len,
1037            failed: false,
1038        }
1039    }
1040
1041    /// Detect OID width and return an iterator (SHA-1 first, then SHA-256).
1042    ///
1043    /// # Errors
1044    ///
1045    /// Returns [`crate::error::ObjectError::Corrupt`] when the blob does not parse as a tree.
1046    pub fn infer_oid_len(data: &'a [u8]) -> Result<Self> {
1047        match try_parse_tree_oid_len(data, HashAlgo::Sha1.len()) {
1048            Ok(()) => Ok(Self::with_oid_len(data, HashAlgo::Sha1.len())),
1049            Err(sha1_err) => match try_parse_tree_oid_len(data, HashAlgo::Sha256.len()) {
1050                Ok(()) => Ok(Self::with_oid_len(data, HashAlgo::Sha256.len())),
1051                Err(_) => Err(sha1_err),
1052            },
1053        }
1054    }
1055
1056    /// Iterate `data` from byte offset `pos`, which must be where an entry starts.
1057    pub(crate) fn with_oid_len_at(data: &'a [u8], oid_len: usize, pos: usize) -> Self {
1058        Self {
1059            data,
1060            pos,
1061            oid_len,
1062            failed: false,
1063        }
1064    }
1065
1066    /// Byte offset of the next entry (`data.len()` once every entry was read).
1067    pub(crate) fn position(&self) -> usize {
1068        self.pos
1069    }
1070
1071    fn next_entry(&mut self) -> Result<Option<TreeEntryRef<'a>>> {
1072        parse_tree_entry_at(self.data, &mut self.pos, self.oid_len)
1073    }
1074}
1075
1076/// Where one tree entry lies in a tree payload, found without building its object id.
1077pub(crate) struct TreeEntrySpan {
1078    /// The entry's mode.
1079    pub(crate) mode: u32,
1080    /// Byte range of the entry's name.
1081    pub(crate) name: std::ops::Range<usize>,
1082    /// Offset just past the entry; its object id is the `oid_len` bytes before it.
1083    pub(crate) end: usize,
1084}
1085
1086/// The entry starting at `pos` in tree payload `data`, for walks that skip most entries
1087/// unread.
1088///
1089/// Accepts exactly the entries [`TreeRefIter`] parses, with the same mode and name.
1090/// `None` at the end of `data`, for a malformed entry and for an id width that is no
1091/// digest length; [`TreeRefIter`] reports the error for those.
1092#[inline]
1093pub(crate) fn tree_entry_span(data: &[u8], pos: usize, oid_len: usize) -> Option<TreeEntrySpan> {
1094    HashAlgo::from_len(oid_len)?;
1095    let rest = data.get(pos..)?;
1096    let space = memchr::memchr(b' ', rest)?;
1097    let mode = parse_tree_mode(&rest[..space])?;
1098    let name_start = pos + space + 1;
1099    let name_end = name_start + memchr::memchr(0, &data[name_start..])?;
1100    let end = name_end + 1 + oid_len;
1101    (end <= data.len()).then_some(TreeEntrySpan {
1102        mode,
1103        name: name_start..name_end,
1104        end,
1105    })
1106}
1107
1108/// Parse a tree entry's octal mode, accepting exactly what `u32::from_str_radix(_, 8)` does.
1109#[inline]
1110fn parse_tree_mode(bytes: &[u8]) -> Option<u32> {
1111    // Ten octal digits cannot overflow a `u32`.
1112    if (1..=10).contains(&bytes.len()) {
1113        let mut mode = 0u32;
1114        let mut all_octal = true;
1115        for &b in bytes {
1116            let digit = b.wrapping_sub(b'0');
1117            all_octal &= digit < 8;
1118            mode = (mode << 3) | u32::from(digit & 7);
1119        }
1120        if all_octal {
1121            return Some(mode);
1122        }
1123    }
1124    std::str::from_utf8(bytes)
1125        .ok()
1126        .and_then(|s| u32::from_str_radix(s, 8).ok())
1127}
1128
1129/// Parse one tree entry and advance `pos`. Returns `Ok(None)` when `pos` is at end of `data`.
1130fn parse_tree_entry_at<'a>(
1131    data: &'a [u8],
1132    pos: &mut usize,
1133    oid_len: usize,
1134) -> Result<Option<TreeEntryRef<'a>>> {
1135    if *pos >= data.len() {
1136        return Ok(None);
1137    }
1138    let sp = memchr::memchr(b' ', &data[*pos..]).ok_or_else(|| {
1139        Error::Object(ObjectError::Corrupt {
1140            detail: "tree entry missing space".to_owned(),
1141        })
1142    })?;
1143    let mode_bytes = &data[*pos..*pos + sp];
1144    let mode = parse_tree_mode(mode_bytes).ok_or_else(|| {
1145        Error::Object(ObjectError::Corrupt {
1146            detail: format!("invalid tree mode: {}", String::from_utf8_lossy(mode_bytes)),
1147        })
1148    })?;
1149    *pos += sp + 1;
1150
1151    let nul = memchr::memchr(0, &data[*pos..]).ok_or_else(|| {
1152        Error::Object(ObjectError::Corrupt {
1153            detail: "tree entry missing NUL".to_owned(),
1154        })
1155    })?;
1156    let name = &data[*pos..*pos + nul];
1157    *pos += nul + 1;
1158
1159    if *pos + oid_len > data.len() {
1160        return Err(Error::Object(ObjectError::Corrupt {
1161            detail: "tree entry truncated SHA".to_owned(),
1162        }));
1163    }
1164    let oid = ObjectId::from_bytes(&data[*pos..*pos + oid_len])?;
1165    *pos += oid_len;
1166
1167    Ok(Some(TreeEntryRef { mode, name, oid }))
1168}
1169
1170impl<'a> Iterator for TreeRefIter<'a> {
1171    type Item = Result<TreeEntryRef<'a>>;
1172
1173    fn next(&mut self) -> Option<Self::Item> {
1174        if self.failed || self.pos >= self.data.len() {
1175            return None;
1176        }
1177        match self.next_entry() {
1178            Ok(Some(entry)) => Some(Ok(entry)),
1179            Ok(None) => None,
1180            Err(err) => {
1181                self.failed = true;
1182                self.pos = self.data.len();
1183                Some(Err(err))
1184            }
1185        }
1186    }
1187}
1188
1189/// Walk `data` once to verify it parses as a tree with the given OID width (no entry allocation).
1190fn try_parse_tree_oid_len(data: &[u8], oid_len: usize) -> Result<()> {
1191    let mut pos = 0usize;
1192    while parse_tree_entry_at(data, &mut pos, oid_len)?.is_some() {}
1193    Ok(())
1194}
1195
1196pub(crate) fn collect_tree_with_oid_len(data: &[u8], oid_len: usize) -> Result<Vec<TreeEntry>> {
1197    let mut pos = 0usize;
1198    let mut entries = Vec::with_capacity(data.len() / 32);
1199    while let Some(entry) = parse_tree_entry_at(data, &mut pos, oid_len)? {
1200        entries.push(TreeEntry {
1201            mode: entry.mode,
1202            name: entry.name.to_vec(),
1203            oid: entry.oid,
1204        });
1205    }
1206    Ok(entries)
1207}
1208
1209/// Parse the raw data of a tree object into its entries.
1210///
1211/// # Format
1212///
1213/// Each entry is `"<mode> <name>\0<20-byte-sha1>"` concatenated with no
1214/// separator between entries.
1215///
1216/// # Errors
1217///
1218/// Returns [`crate::error::ObjectError::Corrupt`] if the data is malformed.
1219pub fn parse_tree(data: &[u8]) -> Result<Vec<TreeEntry>> {
1220    match collect_tree_with_oid_len(data, HashAlgo::Sha1.len()) {
1221        Ok(entries) => Ok(entries),
1222        Err(sha1_err) => {
1223            collect_tree_with_oid_len(data, HashAlgo::Sha256.len()).map_err(|_| sha1_err)
1224        }
1225    }
1226}
1227
1228/// Parse a tree blob whose entry ids use `algo` (the repository's object format).
1229///
1230/// Unlike [`parse_tree`], which tries SHA-1 and then SHA-256 widths, this fails when the
1231/// data does not parse cleanly into whole entries of `algo`'s width.
1232///
1233/// # Errors
1234///
1235/// Returns [`crate::error::ObjectError::Corrupt`] if the data is malformed for `algo`.
1236pub fn parse_tree_for_algo(data: &[u8], algo: HashAlgo) -> Result<Vec<TreeEntry>> {
1237    collect_tree_with_oid_len(data, algo.len())
1238}
1239
1240/// Build the raw bytes of a tree object from a slice of entries.
1241///
1242/// Entries **must** already be sorted in Git tree order (see [`tree_entry_cmp`]),
1243/// with unique, valid names and modes; nothing here checks that. To write a tree
1244/// from entries in any order with validation, use
1245/// [`Objects::write_tree`](crate::objects::Objects::write_tree).
1246#[must_use]
1247pub fn serialize_tree(entries: &[TreeEntry]) -> Vec<u8> {
1248    let len = entries
1249        .iter()
1250        .map(|e| 8 + e.name.len() + e.oid.as_bytes().len())
1251        .sum();
1252    let mut out = Vec::with_capacity(len);
1253    for e in entries {
1254        push_tree_mode(&mut out, e.mode);
1255        out.push(b' ');
1256        out.extend_from_slice(&e.name);
1257        out.push(0);
1258        out.extend_from_slice(e.oid.as_bytes());
1259    }
1260    out
1261}
1262
1263/// Append `mode` in octal without leading zeros, as [`TreeEntry::mode_str`] formats it.
1264fn push_tree_mode(out: &mut Vec<u8>, mode: u32) {
1265    let mut digits = [0u8; 11];
1266    let mut start = digits.len();
1267    let mut rest = mode;
1268    loop {
1269        start -= 1;
1270        digits[start] = b'0' + (rest & 7) as u8;
1271        rest >>= 3;
1272        if rest == 0 {
1273            break;
1274        }
1275    }
1276    out.extend_from_slice(&digits[start..]);
1277}
1278
1279/// Compare two tree entries in Git's canonical tree order.
1280///
1281/// Trees are sorted byte-by-byte by `"<name>"` for blobs and `"<name>/"` for
1282/// sub-trees, so a directory `foo` sorts after a file `foo-bar` but before
1283/// `fooz`. An entry is a sub-tree when its mode is `040000`.
1284///
1285/// # Parameters
1286///
1287/// - `a_name`, `a_mode`: name bytes and mode of the first entry
1288/// - `b_name`, `b_mode`: name bytes and mode of the second entry
1289#[must_use]
1290#[inline]
1291pub fn tree_entry_cmp(
1292    a_name: &[u8],
1293    a_mode: u32,
1294    b_name: &[u8],
1295    b_mode: u32,
1296) -> std::cmp::Ordering {
1297    tree_name_cmp(a_name, a_mode == 0o040000, b_name, b_mode == 0o040000)
1298}
1299
1300/// [`tree_entry_cmp`] with each entry's sub-tree flag already computed.
1301pub(crate) fn tree_name_cmp(
1302    a_name: &[u8],
1303    a_is_tree: bool,
1304    b_name: &[u8],
1305    b_is_tree: bool,
1306) -> std::cmp::Ordering {
1307    let a_trailer = if a_is_tree { b'/' } else { 0u8 };
1308    let b_trailer = if b_is_tree { b'/' } else { 0u8 };
1309
1310    let min_len = a_name.len().min(b_name.len());
1311    let cmp = a_name[..min_len].cmp(&b_name[..min_len]);
1312    if cmp != std::cmp::Ordering::Equal {
1313        return cmp;
1314    }
1315    // Names share a prefix; compare the next character (or trailer).
1316    let ac = a_name.get(min_len).copied().unwrap_or(a_trailer);
1317    let bc = b_name.get(min_len).copied().unwrap_or(b_trailer);
1318    ac.cmp(&bc)
1319}
1320
1321/// Parse an octal tree-entry mode without going through `str`.
1322fn parse_tree_mode_octal(bytes: &[u8]) -> Option<u32> {
1323    if bytes.is_empty() || bytes.len() > 7 {
1324        return None;
1325    }
1326    bytes.iter().try_fold(0u32, |acc, &b| match b {
1327        b'0'..=b'7' => Some(acc * 8 + u32::from(b - b'0')),
1328        _ => None,
1329    })
1330}
1331
1332/// Find one tree entry by name without building a full [`TreeEntry`] vector.
1333///
1334/// Scans entries in stored order and returns the first whose name equals `name`
1335/// (file or directory). Because Git sorts entries by `name` (with a `/` trailer for
1336/// directories), the scan stops at the first entry that sorts after `name/`, so only
1337/// the prefix of the tree up to the match is decoded; corruption after that point is
1338/// not reported.
1339///
1340/// # Errors
1341///
1342/// [`crate::error::ObjectError::Corrupt`] when an entry scanned before the stop point is malformed.
1343pub(crate) fn find_tree_entry_by_name_in_data(
1344    data: &[u8],
1345    oid_len: usize,
1346    name: &[u8],
1347    name_is_tree: bool,
1348) -> Result<Option<TreeEntry>> {
1349    let mut pos = 0usize;
1350    while pos < data.len() {
1351        let rest = &data[pos..];
1352        let sp = memchr::memchr(b' ', rest).ok_or_else(|| {
1353            Error::Object(ObjectError::Corrupt {
1354                detail: "tree entry missing space".to_owned(),
1355            })
1356        })?;
1357        let mode = parse_tree_mode_octal(&rest[..sp]).ok_or_else(|| {
1358            Error::Object(ObjectError::Corrupt {
1359                detail: "invalid tree mode".to_owned(),
1360            })
1361        })?;
1362        let name_start = sp + 1;
1363        let nul = memchr::memchr(0, &rest[name_start..]).ok_or_else(|| {
1364            Error::Object(ObjectError::Corrupt {
1365                detail: "tree entry missing NUL".to_owned(),
1366            })
1367        })?;
1368        let entry_name = &rest[name_start..name_start + nul];
1369        let oid_start = name_start + nul + 1;
1370        let oid_end = oid_start + oid_len;
1371        if oid_end > rest.len() {
1372            return Err(Error::Object(ObjectError::Corrupt {
1373                detail: "tree entry truncated SHA".to_owned(),
1374            }));
1375        }
1376        if entry_name == name {
1377            return Ok(Some(TreeEntry {
1378                mode,
1379                name: entry_name.to_vec(),
1380                oid: ObjectId::from_bytes(&rest[oid_start..oid_end])?,
1381            }));
1382        }
1383        if tree_name_cmp(entry_name, mode == 0o040000, name, name_is_tree)
1384            == std::cmp::Ordering::Greater
1385        {
1386            return Ok(None);
1387        }
1388        pos += oid_end;
1389    }
1390    Ok(None)
1391}
1392
1393/// Like [`find_tree_entry_by_name_in_data`], trying directory ordering first then file.
1394pub(crate) fn find_tree_entry_by_name_dir_or_file_in_data(
1395    data: &[u8],
1396    oid_len: usize,
1397    name: &[u8],
1398) -> Result<Option<TreeEntry>> {
1399    if let Some(entry) = find_tree_entry_by_name_in_data(data, oid_len, name, true)? {
1400        if entry.mode == 0o040000 {
1401            return Ok(Some(entry));
1402        }
1403    }
1404    find_tree_entry_by_name_in_data(data, oid_len, name, false)
1405}
1406
1407/// Parsed representation of a commit object.
1408///
1409/// This is the read-side shape (it round-trips stored bytes exactly). To create a
1410/// new commit, build a [`NewCommit`](crate::objects::NewCommit) and pass it to
1411/// [`Objects::write_commit`](crate::objects::Objects::write_commit).
1412#[derive(Debug, Clone, PartialEq, Eq)]
1413pub struct CommitData {
1414    /// The tree this commit points to.
1415    pub tree: ObjectId,
1416    /// Parent commit IDs (zero or more).
1417    pub parents: Vec<ObjectId>,
1418    /// Author field decoded to Unicode (using `encoding` when present, else UTF-8).
1419    pub author: String,
1420    /// Committer field decoded to Unicode.
1421    pub committer: String,
1422    /// Exact `author` header payload bytes as stored in the object (after `author `).
1423    ///
1424    /// Empty means treat [`Self::author`] as UTF-8 when serializing (new commits).
1425    pub author_raw: Vec<u8>,
1426    /// Exact `committer` header payload bytes as stored in the object.
1427    pub committer_raw: Vec<u8>,
1428    /// Optional encoding override (e.g. `"UTF-8"`).
1429    pub encoding: Option<String>,
1430    /// Commit message (everything after the blank line).
1431    pub message: String,
1432    /// Optional raw message bytes for non-UTF-8 commit messages.
1433    /// When set, `serialize_commit` uses these bytes instead of `message`.
1434    #[doc = "Optional raw message bytes for non-UTF-8 messages."]
1435    pub raw_message: Option<Vec<u8>>,
1436    /// Raw bytes for headers not represented in the fields above (`gpgsig`, `mergetag`, …),
1437    /// including each line's trailing `\n` and any continuation lines (leading space).
1438    ///
1439    /// [`serialize_commit`] always emits `tree`, `parent`, `author`, `committer`, and `encoding`
1440    /// from the structured fields, then appends these bytes before the blank line and message.
1441    pub extra_headers: Vec<u8>,
1442}
1443
1444/// First paragraph of a commit message, folded like Git `%(contents:subject)`.
1445///
1446/// Non-blank lines in the first paragraph are joined with a single space. Each line keeps
1447/// its leading whitespace and internal spacing; only trailing whitespace on each line is
1448/// removed before joining. The paragraph ends at the first blank line. An empty message
1449/// yields an empty string.
1450#[must_use]
1451pub fn commit_subject_pretty(message: &str) -> String {
1452    let mut parts = Vec::new();
1453    for line in message.lines() {
1454        if line.trim().is_empty() {
1455            break;
1456        }
1457        parts.push(line.trim_end());
1458    }
1459    parts.join(" ")
1460}
1461
1462/// Subject from commit object bytes (see [`commit_subject_pretty`]).
1463///
1464/// # Errors
1465///
1466/// Returns [`crate::error::ObjectError::Corrupt`] when the commit headers are malformed.
1467pub fn read_commit_subject_pretty(data: &[u8]) -> Result<String> {
1468    let message_start = data.windows(2).position(|w| w == b"\n\n").map(|p| p + 2);
1469    let Some(message_start) = message_start else {
1470        return Ok(String::new());
1471    };
1472    let body = std::str::from_utf8(data.get(message_start..).unwrap_or_default()).unwrap_or("");
1473    Ok(commit_subject_pretty(body))
1474}
1475
1476/// First line of the commit message (subject), honoring the `encoding` header.
1477///
1478/// Scans headers only; does not require a full [`parse_commit`] parse.
1479///
1480/// # Errors
1481///
1482/// Returns [`crate::error::ObjectError::Corrupt`] when commit headers are malformed.
1483pub fn read_commit_subject_line(data: &[u8]) -> Result<String> {
1484    let mut pos = 0usize;
1485    let mut encoding: Option<String> = None;
1486    while pos < data.len() {
1487        let line_start = pos;
1488        let mut line_end = pos;
1489        while line_end < data.len() && data[line_end] != b'\n' {
1490            line_end += 1;
1491        }
1492        let line = &data[line_start..line_end];
1493        let after_nl = line_end.saturating_add(1);
1494        if line.is_empty() {
1495            let body = data.get(after_nl..).unwrap_or_default();
1496            let message = commit_encoding::decode_bytes(encoding.as_deref(), body);
1497            return Ok(message
1498                .lines()
1499                .find(|l| !l.trim().is_empty())
1500                .map(str::trim)
1501                .unwrap_or("(no subject)")
1502                .to_owned());
1503        }
1504        if line.first() == Some(&b' ') {
1505            pos = after_nl;
1506            continue;
1507        }
1508        if let Some(rest) = line.strip_prefix(b"encoding ") {
1509            encoding = Some(
1510                std::str::from_utf8(rest)
1511                    .map_err(|_| {
1512                        Error::Object(ObjectError::Corrupt {
1513                            detail: "encoding is not UTF-8".to_owned(),
1514                        })
1515                    })?
1516                    .trim()
1517                    .to_owned(),
1518            );
1519        }
1520        pos = after_nl;
1521    }
1522    Ok("(no subject)".to_owned())
1523}
1524
1525/// Length of the leading part of commit payload `data` that holds every header and the
1526/// message up to and including its first non-blank line.
1527///
1528/// [`read_commit_subject_line`] and [`parse_commit`] give the same headers and subject for that
1529/// prefix as for the whole of `data`. `data` may itself be a truncated prefix of the payload:
1530/// `None` means it does not yet provably hold such a prefix. A commit that declares a
1531/// non-UTF-8 `encoding` never yields one, since its line structure is only known after
1532/// decoding; neither does a commit whose message has no line with a printable ASCII
1533/// character, since only such a line is certain to be non-blank before decoding.
1534pub(crate) fn commit_through_subject_len(data: &[u8]) -> Option<usize> {
1535    let header_end = memchr::memmem::find(data, b"\n\n")? + 2;
1536    let declares_other_encoding = data[..header_end]
1537        .split(|&b| b == b'\n')
1538        .filter_map(|line| line.strip_prefix(b"encoding "))
1539        .any(|label| {
1540            let label = label.trim_ascii();
1541            !label.eq_ignore_ascii_case(b"utf-8") && !label.eq_ignore_ascii_case(b"utf8")
1542        });
1543    if declares_other_encoding {
1544        return None;
1545    }
1546    let mut pos = header_end;
1547    loop {
1548        let line_end = pos + memchr::memchr(b'\n', data.get(pos..)?)?;
1549        if data[pos..line_end].iter().any(u8::is_ascii_graphic) {
1550            return Some(line_end + 1);
1551        }
1552        pos = line_end + 1;
1553    }
1554}
1555
1556pub(crate) fn parse_oid_field(value: &[u8]) -> Result<ObjectId> {
1557    let s = std::str::from_utf8(value).map_err(|_| {
1558        Error::Object(ObjectError::Corrupt {
1559            detail: "commit header object id is not UTF-8".to_owned(),
1560        })
1561    })?;
1562    s.trim().parse::<ObjectId>().map_err(|_| {
1563        Error::Object(ObjectError::Corrupt {
1564            detail: "invalid object id in commit header".to_owned(),
1565        })
1566    })
1567}
1568
1569/// Parse `tree` and `parent` headers from a possibly truncated leading slice of a commit.
1570///
1571/// `prefix` may be cut anywhere (for example a fixed-size inflate of the object start).
1572/// Returns `Some` only when the slice provably holds the complete parent list: the `tree`
1573/// line, every `parent` line, and the start of a following line that cannot be another
1574/// `parent` header. Returns `None` when the slice ends inside that region or the headers are
1575/// not in canonical form; parse the whole object with
1576/// [`parse_commit_tree_and_parents_lenient`] instead, which then yields the same result
1577/// whenever this returns `Some`.
1578pub(crate) fn parse_commit_tree_and_parents_prefix(
1579    prefix: &[u8],
1580    hex_len: usize,
1581) -> Option<(ObjectId, Vec<ObjectId>)> {
1582    canonical_commit_tree_and_parents(prefix, hex_len, false)
1583}
1584
1585/// Parse `tree` and `parent` headers of a whole commit object the way Git's commit parser
1586/// does: a leading `tree` line followed by any number of `parent` lines.
1587///
1588/// Nothing after the parent list is inspected, so a commit missing `author` or `committer`
1589/// (or with other malformed headers) still yields its tree and parents. Returns `None` when
1590/// the first line is not a valid `tree` header or a `parent` line is malformed.
1591pub(crate) fn parse_commit_tree_and_parents_lenient(
1592    data: &[u8],
1593    hex_len: usize,
1594) -> Option<(ObjectId, Vec<ObjectId>)> {
1595    canonical_commit_tree_and_parents(data, hex_len, true)
1596}
1597
1598fn canonical_commit_tree_and_parents(
1599    data: &[u8],
1600    hex_len: usize,
1601    complete: bool,
1602) -> Option<(ObjectId, Vec<ObjectId>)> {
1603    fn header_oid<'a>(rest: &'a [u8], key: &[u8], hex_len: usize) -> Option<(ObjectId, &'a [u8])> {
1604        let line = rest.strip_prefix(key)?;
1605        if line.len() <= hex_len || line[hex_len] != b'\n' {
1606            return None;
1607        }
1608        let oid = ObjectId::from_hex(std::str::from_utf8(&line[..hex_len]).ok()?).ok()?;
1609        Some((oid, &line[hex_len + 1..]))
1610    }
1611    const PARENT: &[u8] = b"parent ";
1612    let (tree, mut rest) = header_oid(data, b"tree ", hex_len)?;
1613    let mut parents = Vec::new();
1614    loop {
1615        if !complete && rest.len() < PARENT.len() && PARENT.starts_with(rest) {
1616            return None;
1617        }
1618        if !rest.starts_with(PARENT) {
1619            return Some((tree, parents));
1620        }
1621        let (parent, next) = header_oid(rest, PARENT, hex_len)?;
1622        parents.push(parent);
1623        rest = next;
1624    }
1625}
1626
1627/// Parse the raw data of a commit object.
1628///
1629/// # Errors
1630///
1631/// Returns [`crate::error::ObjectError::Corrupt`] if required headers are missing.
1632pub fn parse_commit(data: &[u8]) -> Result<CommitData> {
1633    Ok(super::CommitRef::parse(data)?.to_owned())
1634}
1635
1636/// Value after `prefix` on the first header line that starts with `prefix`, scanning until a blank
1637/// line (Git tag headers). Returns `None` if no such line exists before the body.
1638#[must_use]
1639pub fn tag_header_field(data: &[u8], prefix: &[u8]) -> Option<String> {
1640    let mut pos = 0usize;
1641    while pos < data.len() {
1642        let rest = &data[pos..];
1643        let nl = rest.iter().position(|&b| b == b'\n');
1644        let line = if let Some(i) = nl { &rest[..i] } else { rest };
1645        if line.is_empty() {
1646            break;
1647        }
1648        if let Some(after) = line.strip_prefix(prefix) {
1649            return Some(String::from_utf8_lossy(after).trim().to_owned());
1650        }
1651        pos += line.len().saturating_add(nl.map(|_| 1).unwrap_or(0));
1652        if nl.is_none() {
1653            break;
1654        }
1655    }
1656    None
1657}
1658
1659/// OID from the first `object <hex>` line in the tag header block, if hex parses.
1660#[must_use]
1661pub fn tag_object_line_oid(data: &[u8]) -> Option<ObjectId> {
1662    let s = tag_header_field(data, b"object ")?;
1663    s.parse().ok()
1664}
1665
1666/// Parsed representation of an annotated tag object.
1667#[derive(Debug, Clone)]
1668pub struct TagData {
1669    /// The object this tag points to.
1670    pub object: ObjectId,
1671    /// The type of the tagged object (e.g. `"commit"`).
1672    pub object_type: String,
1673    /// The short tag name (without `refs/tags/` prefix).
1674    pub tag: String,
1675    /// The tagger identity and timestamp (raw Git format).
1676    pub tagger: Option<String>,
1677    /// Extra header lines after `tagger` and before the blank line (raw bytes, LF-terminated).
1678    pub extra_headers: Vec<u8>,
1679    /// The tag message (everything after the blank line), lossily decoded when not UTF-8.
1680    pub message: String,
1681    /// Optional raw message bytes for non-UTF-8 tag messages.
1682    ///
1683    /// When set, [`serialize_tag`] writes these bytes unchanged so parse→serialize keeps the object id.
1684    pub raw_message: Option<Vec<u8>>,
1685}
1686
1687/// Parse the raw data of a tag object.
1688///
1689/// # Errors
1690///
1691/// Returns [`crate::error::ObjectError::Corrupt`] if required headers are missing or malformed.
1692///
1693/// When the header block ends at EOF without a blank line, the message is empty (Git accepts this).
1694pub fn parse_tag(data: &[u8]) -> Result<TagData> {
1695    use super::extra_headers::next_header_block;
1696
1697    #[derive(Clone, Copy)]
1698    enum Continuation {
1699        None,
1700        Extra,
1701    }
1702
1703    let mut pos = 0usize;
1704    let mut object = None;
1705    let mut object_type = None;
1706    let mut tag_name = None;
1707    let mut tagger = None;
1708    let mut extra_headers = Vec::new();
1709    let mut cont = Continuation::None;
1710    let mut past_tagger = false;
1711
1712    while pos < data.len() {
1713        let line_start = pos;
1714        let mut line_end = pos;
1715        while line_end < data.len() && data[line_end] != b'\n' {
1716            line_end += 1;
1717        }
1718        let line = &data[line_start..line_end];
1719        let after_nl = (line_end + 1).min(data.len());
1720        if line.is_empty() {
1721            let body = data.get(after_nl..).unwrap_or_default();
1722            let (message, raw_message) = match std::str::from_utf8(body) {
1723                Ok(text) => (text.to_owned(), None),
1724                Err(_) => (
1725                    String::from_utf8_lossy(body).into_owned(),
1726                    Some(body.to_vec()),
1727                ),
1728            };
1729            return Ok(TagData {
1730                object: object.ok_or_else(|| {
1731                    Error::Object(ObjectError::Corrupt {
1732                        detail: "tag missing object header".to_owned(),
1733                    })
1734                })?,
1735                object_type: object_type.ok_or_else(|| {
1736                    Error::Object(ObjectError::Corrupt {
1737                        detail: "tag missing type header".to_owned(),
1738                    })
1739                })?,
1740                tag: tag_name.ok_or_else(|| {
1741                    Error::Object(ObjectError::Corrupt {
1742                        detail: "tag missing tag header".to_owned(),
1743                    })
1744                })?,
1745                tagger,
1746                extra_headers,
1747                message,
1748                raw_message,
1749            });
1750        }
1751
1752        if past_tagger {
1753            let (_, block_end, _) = next_header_block(data, line_start);
1754            extra_headers.extend_from_slice(&data[line_start..block_end]);
1755            pos = block_end;
1756            continue;
1757        }
1758
1759        if line.first() == Some(&b' ') {
1760            match cont {
1761                Continuation::Extra => {
1762                    extra_headers.extend_from_slice(&data[line_start..after_nl]);
1763                }
1764                Continuation::None => {}
1765            }
1766            pos = after_nl;
1767            continue;
1768        }
1769
1770        let key_end = line.iter().position(|&b| b == b' ').ok_or_else(|| {
1771            Error::Object(ObjectError::Corrupt {
1772                detail: "malformed tag header line".to_owned(),
1773            })
1774        })?;
1775        let key = &line[..key_end];
1776        let rest = line.get(key_end + 1..).unwrap_or_default();
1777
1778        match key {
1779            b"object" => {
1780                let line_str = std::str::from_utf8(rest).map_err(|_| {
1781                    Error::Object(ObjectError::Corrupt {
1782                        detail: "tag object line is not valid UTF-8".to_owned(),
1783                    })
1784                })?;
1785                object = Some(line_str.trim().parse::<ObjectId>()?);
1786                cont = Continuation::None;
1787            }
1788            b"type" => {
1789                let typ = std::str::from_utf8(rest).map_err(|_| {
1790                    Error::Object(ObjectError::Corrupt {
1791                        detail: "tag type line is not valid UTF-8".to_owned(),
1792                    })
1793                })?;
1794                let typ = typ.trim();
1795                if ObjectKind::from_tag_type_field(typ.as_bytes()).is_none() {
1796                    return Err(Error::Object(ObjectError::Corrupt {
1797                        detail: format!("invalid 'type' value in tag: {typ}"),
1798                    }));
1799                }
1800                object_type = Some(typ.to_owned());
1801                cont = Continuation::None;
1802            }
1803            b"tag" => {
1804                let line_str = std::str::from_utf8(rest).map_err(|_| {
1805                    Error::Object(ObjectError::Corrupt {
1806                        detail: "tag name line is not valid UTF-8".to_owned(),
1807                    })
1808                })?;
1809                tag_name = Some(line_str.trim().to_owned());
1810                cont = Continuation::None;
1811            }
1812            b"tagger" => {
1813                tagger = Some(
1814                    std::str::from_utf8(rest)
1815                        .map_err(|_| {
1816                            Error::Object(ObjectError::Corrupt {
1817                                detail: "tag tagger line is not valid UTF-8".to_owned(),
1818                            })
1819                        })?
1820                        .to_owned(),
1821                );
1822                past_tagger = true;
1823                cont = Continuation::None;
1824            }
1825            _ => {
1826                cont = Continuation::Extra;
1827                extra_headers.extend_from_slice(&data[line_start..after_nl]);
1828            }
1829        }
1830        pos = after_nl;
1831    }
1832
1833    Ok(TagData {
1834        object: object.ok_or_else(|| {
1835            Error::Object(ObjectError::Corrupt {
1836                detail: "tag missing object header".to_owned(),
1837            })
1838        })?,
1839        object_type: object_type.ok_or_else(|| {
1840            Error::Object(ObjectError::Corrupt {
1841                detail: "tag missing type header".to_owned(),
1842            })
1843        })?,
1844        tag: tag_name.ok_or_else(|| {
1845            Error::Object(ObjectError::Corrupt {
1846                detail: "tag missing tag header".to_owned(),
1847            })
1848        })?,
1849        tagger,
1850        extra_headers,
1851        message: String::new(),
1852        raw_message: None,
1853    })
1854}
1855
1856/// Serialize a [`TagData`] into the raw bytes suitable for storage as a tag object.
1857///
1858/// The caller is responsible for supplying a correctly-formatted `tagger` string
1859/// (including timestamp and timezone) when present.
1860#[must_use]
1861pub fn serialize_tag(t: &TagData) -> Vec<u8> {
1862    let mut out = Vec::new();
1863    out.extend_from_slice(format!("object {}\n", t.object).as_bytes());
1864    out.extend_from_slice(format!("type {}\n", t.object_type).as_bytes());
1865    out.extend_from_slice(format!("tag {}\n", t.tag).as_bytes());
1866    if let Some(ref tagger) = t.tagger {
1867        out.extend_from_slice(format!("tagger {tagger}\n").as_bytes());
1868    }
1869    out.extend_from_slice(&t.extra_headers);
1870    out.push(b'\n');
1871    if let Some(raw) = &t.raw_message {
1872        out.extend_from_slice(raw);
1873    } else {
1874        let msg = t.message.trim_end_matches('\n');
1875        if !msg.is_empty() {
1876            out.extend_from_slice(msg.as_bytes());
1877            out.push(b'\n');
1878        }
1879    }
1880    out
1881}
1882
1883/// Serialize a [`CommitData`] into the raw bytes suitable for storage.
1884///
1885/// The caller is responsible for supplying a correctly-formatted `author` and
1886/// `committer` string (including timestamp and timezone). To create a commit from
1887/// typed identities instead, use [`Objects::write_commit`](crate::objects::Objects::write_commit)
1888/// with a [`NewCommit`](crate::objects::NewCommit).
1889///
1890/// The message body is written exactly as given: `git commit` and `git commit-tree -m`
1891/// supply a trailing LF; `git commit-tree` reading from stdin or `-F` does not add one.
1892#[must_use]
1893pub fn serialize_commit(c: &CommitData) -> Vec<u8> {
1894    let mut out = Vec::new();
1895    out.extend_from_slice(format!("tree {}\n", c.tree).as_bytes());
1896    for p in &c.parents {
1897        out.extend_from_slice(format!("parent {p}\n").as_bytes());
1898    }
1899    out.extend_from_slice(b"author ");
1900    if c.author_raw.is_empty() {
1901        out.extend_from_slice(c.author.as_bytes());
1902    } else {
1903        out.extend_from_slice(&c.author_raw);
1904    }
1905    out.push(b'\n');
1906    out.extend_from_slice(b"committer ");
1907    if c.committer_raw.is_empty() {
1908        out.extend_from_slice(c.committer.as_bytes());
1909    } else {
1910        out.extend_from_slice(&c.committer_raw);
1911    }
1912    out.push(b'\n');
1913    if let Some(enc) = &c.encoding {
1914        out.extend_from_slice(format!("encoding {enc}\n").as_bytes());
1915    }
1916    out.extend_from_slice(&c.extra_headers);
1917    out.push(b'\n');
1918    if let Some(raw) = &c.raw_message {
1919        out.extend_from_slice(raw);
1920    } else if !c.message.is_empty() {
1921        out.extend_from_slice(c.message.as_bytes());
1922    }
1923    out
1924}
1925
1926#[cfg(test)]
1927mod short_hex_tests {
1928    use super::*;
1929
1930    #[test]
1931    fn short_hex_takes_seven_digits_or_the_whole_shorter_input() {
1932        assert_eq!(
1933            short_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904"),
1934            "4b825dc"
1935        );
1936        assert_eq!(short_hex("4b825dc"), "4b825dc");
1937        assert_eq!(short_hex("4b8"), "4b8");
1938        assert_eq!(short_hex(""), "");
1939        assert_eq!(short_hex("ééééé"), "ééééé");
1940    }
1941
1942    #[test]
1943    fn object_id_short_hex_matches_the_hex_prefix_for_both_algorithms() {
1944        let digest: Vec<u8> = (0x9a..=0xff).take(32).collect();
1945        for len in [HashAlgo::Sha1.len(), HashAlgo::Sha256.len()] {
1946            let id = ObjectId::from_bytes(&digest[..len]).unwrap();
1947            let short = id.to_short_hex();
1948            assert_eq!(short.len(), SHORT_HEX_LEN);
1949            assert_eq!(short, id.to_hex()[..SHORT_HEX_LEN]);
1950            assert_eq!(short, short_hex(&id.to_hex()));
1951        }
1952    }
1953}
1954
1955#[cfg(test)]
1956mod object_id_prefix_tests {
1957    use super::*;
1958
1959    const ID: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
1960
1961    fn id() -> ObjectId {
1962        ObjectId::from_hex(ID).unwrap()
1963    }
1964
1965    fn prefix(hex: &str) -> ObjectIdPrefix {
1966        ObjectIdPrefix::from_hex(hex, HashAlgo::Sha1).unwrap()
1967    }
1968
1969    #[test]
1970    fn matches_every_length_of_the_id_and_rejects_a_changed_last_digit() {
1971        let id = id();
1972        for n in 0..=ID.len() {
1973            let p = prefix(&ID[..n]);
1974            assert_eq!(p.nibbles(), n);
1975            assert_eq!(p.is_empty(), n == 0);
1976            assert!(p.matches(&id), "{n} digits");
1977            assert_eq!(p.to_string(), ID[..n]);
1978            if n > 0 {
1979                let mut changed = ID[..n].to_owned();
1980                let last = changed.pop().unwrap();
1981                changed.push(if last == '0' { '1' } else { '0' });
1982                assert!(!prefix(&changed).matches(&id), "{changed}");
1983            }
1984        }
1985    }
1986
1987    #[test]
1988    fn odd_prefix_ignores_the_low_nibble_of_its_last_byte() {
1989        let p = prefix("4b8");
1990        assert!(p.matches(&ObjectId::from_hex("4b80000000000000000000000000000000000000").unwrap()));
1991        assert!(p.matches(&ObjectId::from_hex("4b8fffffffffffffffffffffffffffffffffffff").unwrap()));
1992        assert!(
1993            !p.matches(&ObjectId::from_hex("4b90000000000000000000000000000000000000").unwrap())
1994        );
1995    }
1996
1997    #[test]
1998    fn parsing_is_case_insensitive_and_validates() {
1999        assert_eq!(prefix("4B825DC"), prefix("4b825dc"));
2000        assert!(matches!(
2001            ObjectIdPrefix::from_hex("4b8g", HashAlgo::Sha1),
2002            Err(Error::Object(ObjectError::InvalidId { .. }))
2003        ));
2004        assert!(matches!(
2005            ObjectIdPrefix::from_hex(&format!("{ID}0"), HashAlgo::Sha1),
2006            Err(Error::Object(ObjectError::InvalidId { .. }))
2007        ));
2008        let sha256 = "a".repeat(64);
2009        assert_eq!(
2010            ObjectIdPrefix::from_hex(&sha256, HashAlgo::Sha256)
2011                .unwrap()
2012                .nibbles(),
2013            64
2014        );
2015        assert_eq!(prefix("").algo(), HashAlgo::Sha1);
2016    }
2017
2018    #[test]
2019    fn longer_prefix_never_matches_a_shorter_digest() {
2020        let long = ObjectIdPrefix::from_hex(&format!("{ID}0000"), HashAlgo::Sha256).unwrap();
2021        assert!(!long.matches(&id()));
2022        assert!(ObjectIdPrefix::from_hex(ID, HashAlgo::Sha256)
2023            .unwrap()
2024            .matches(&id()));
2025    }
2026
2027    #[test]
2028    fn bounds_are_the_first_and_last_matching_ids() {
2029        let p = prefix("4b8");
2030        assert_eq!(
2031            p.lowest().to_hex(),
2032            "4b80000000000000000000000000000000000000"
2033        );
2034        assert_eq!(
2035            p.highest().to_hex(),
2036            "4b8fffffffffffffffffffffffffffffffffffff"
2037        );
2038        let even = prefix("4b82");
2039        assert_eq!(
2040            even.lowest().to_hex(),
2041            "4b82000000000000000000000000000000000000"
2042        );
2043        assert_eq!(
2044            even.highest().to_hex(),
2045            "4b82ffffffffffffffffffffffffffffffffffff"
2046        );
2047        assert_eq!(prefix("").lowest(), ObjectId::null(HashAlgo::Sha1));
2048        assert_eq!(prefix("").highest().to_hex(), "f".repeat(40));
2049        assert_eq!(prefix(ID).lowest(), id());
2050        assert_eq!(prefix(ID).highest(), id());
2051        let sha256 = ObjectIdPrefix::from_hex("abc", HashAlgo::Sha256).unwrap();
2052        assert_eq!(sha256.highest().to_hex(), format!("abc{}", "f".repeat(61)));
2053        assert_eq!(format!("{sha256:?}"), "ObjectIdPrefix(abc)");
2054    }
2055
2056    #[test]
2057    fn common_prefix_nibbles_counts_shared_leading_digits() {
2058        let a = id();
2059        let hex = |s: &str| ObjectId::from_hex(s).unwrap();
2060        assert_eq!(a.common_prefix_nibbles(&a), 40);
2061        assert_eq!(
2062            a.common_prefix_nibbles(&hex("4b825dc642cb6eb9a060e54bf8d69288fbee4905")),
2063            39
2064        );
2065        assert_eq!(
2066            a.common_prefix_nibbles(&hex("4b815dc642cb6eb9a060e54bf8d69288fbee4904")),
2067            3
2068        );
2069        assert_eq!(
2070            a.common_prefix_nibbles(&hex("4b925dc642cb6eb9a060e54bf8d69288fbee4904")),
2071            2
2072        );
2073        assert_eq!(
2074            a.common_prefix_nibbles(&hex("5b825dc642cb6eb9a060e54bf8d69288fbee4904")),
2075            0
2076        );
2077        assert_eq!(
2078            a.common_prefix_nibbles(&hex("4c825dc642cb6eb9a060e54bf8d69288fbee4904")),
2079            1
2080        );
2081    }
2082}
2083
2084#[cfg(test)]
2085mod commit_parse_tests {
2086    use super::*;
2087
2088    #[test]
2089    fn empty_tree_constant_is_canonical_sha1_digest() {
2090        assert_eq!(
2091            ObjectId::empty_tree().to_hex(),
2092            "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
2093        );
2094    }
2095
2096    #[test]
2097    fn is_empty_tree_for_matches_hashed_empty_tree() {
2098        for algo in [HashAlgo::Sha1, HashAlgo::Sha256] {
2099            let hashed =
2100                crate::hash::hash_object(algo, ObjectKind::Tree, b"").expect("hash empty tree");
2101            assert!(hashed.is_empty_tree_for(algo), "{algo:?}");
2102            let other = match algo {
2103                HashAlgo::Sha1 => HashAlgo::Sha256,
2104                HashAlgo::Sha256 => HashAlgo::Sha1,
2105            };
2106            assert!(!hashed.is_empty_tree_for(other), "{algo:?}");
2107            let empty_blob =
2108                crate::hash::hash_object(algo, ObjectKind::Blob, b"").expect("hash empty blob");
2109            assert!(!empty_blob.is_empty_tree_for(algo), "{algo:?}");
2110        }
2111        let legacy = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf899d69f7c6948d4").expect("hex");
2112        assert!(legacy.is_empty_tree_for(HashAlgo::Sha1));
2113        assert!(!legacy.is_empty_tree_for(HashAlgo::Sha256));
2114    }
2115
2116    #[test]
2117    fn serialize_tree_mode_matches_mode_str() {
2118        for mode in [
2119            0,
2120            0o7,
2121            0o100644,
2122            0o100755,
2123            0o120000,
2124            0o040000,
2125            0o160000,
2126            u32::MAX,
2127        ] {
2128            let mut out = Vec::new();
2129            push_tree_mode(&mut out, mode);
2130            let entry = TreeEntry {
2131                mode,
2132                name: Vec::new(),
2133                oid: ObjectId::empty_tree(),
2134            };
2135            assert_eq!(out, entry.mode_str().into_bytes(), "mode {mode:o}");
2136        }
2137    }
2138
2139    #[test]
2140    fn is_empty_blob_matches_both_hash_algorithms() {
2141        for algo in [HashAlgo::Sha1, HashAlgo::Sha256] {
2142            let oid = algo.hash_object(ObjectKind::Blob, b"").unwrap();
2143            assert!(oid.is_empty_blob(), "{algo:?} empty blob {}", oid.to_hex());
2144            let other = algo.hash_object(ObjectKind::Blob, b"x").unwrap();
2145            assert!(!other.is_empty_blob());
2146        }
2147        assert!(!ObjectId::empty_tree().is_empty_blob());
2148        assert!(!ObjectId::zero().is_empty_blob());
2149    }
2150
2151    #[test]
2152    fn commit_subject_pretty_folds_first_paragraph() {
2153        assert_eq!(commit_subject_pretty("hello\nworld\n\nbody"), "hello world");
2154        assert_eq!(commit_subject_pretty(""), "");
2155        assert_eq!(
2156            commit_subject_pretty("  hello   world\tthere  \n  next\t line  \n\nbody\n"),
2157            "  hello   world\tthere   next\t line"
2158        );
2159    }
2160
2161    #[test]
2162    fn commit_ref_matches_parse_commit_headers() {
2163        let raw = concat!(
2164            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",
2165            "parent 1111111111111111111111111111111111111111\n",
2166            "author A <a@example.com> 1 +0000\n",
2167            "committer C <c@example.com> 2 +0000\n",
2168            "\n",
2169            "ignored body\n",
2170        );
2171        let full = parse_commit(raw.as_bytes()).expect("parse");
2172        let link = crate::objects::CommitRef::parse(raw.as_bytes()).expect("CommitRef");
2173        assert_eq!(link.tree(), full.tree);
2174        assert_eq!(link.parents(), full.parents.as_slice());
2175        assert_eq!(link.author(), full.author);
2176        assert_eq!(link.committer(), full.committer);
2177    }
2178
2179    #[test]
2180    fn parse_commit_skips_multiline_gpgsig_continuation() {
2181        let raw = concat!(
2182            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",
2183            "author A U Thor <author@example.com> 1 +0000\n",
2184            "committer C O Mitter <committer@example.com> 1 +0000\n",
2185            "gpgsig -----BEGIN PGP SIGNATURE-----\n",
2186            " abcdef\n",
2187            " -----END PGP SIGNATURE-----\n",
2188            "\n",
2189            "msg\n",
2190        );
2191        let c = parse_commit(raw.as_bytes()).expect("parse signed commit");
2192        assert_eq!(c.tree.to_hex(), "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
2193        assert_eq!(c.message, "msg\n");
2194        assert_eq!(serialize_commit(&c), raw.as_bytes());
2195    }
2196
2197    #[test]
2198    fn hex_parsing_accepts_both_cases_and_lengths_and_rejects_the_rest() {
2199        let sha1 = "0123456789abcdefABCDEF0123456789abcdef01";
2200        let oid = ObjectId::from_hex(sha1).unwrap();
2201        assert_eq!(oid.algo(), HashAlgo::Sha1);
2202        assert_eq!(oid.to_hex(), sha1.to_ascii_lowercase());
2203        assert_eq!(ObjectId::from_hex_ascii(sha1.as_bytes()).unwrap(), oid);
2204        assert_eq!(sha1.parse::<ObjectId>().unwrap(), oid);
2205
2206        let sha256 = "f".repeat(64);
2207        let oid = sha256.parse::<ObjectId>().unwrap();
2208        assert_eq!(oid.algo(), HashAlgo::Sha256);
2209        assert_eq!(oid.as_bytes(), [0xff; 32]);
2210        assert!(ObjectId::from_hex_ascii(sha256.as_bytes()).is_err());
2211
2212        for bad in [
2213            "",
2214            &sha1[..39],
2215            &format!("{sha1}0"),
2216            "g123456789abcdef0123456789abcdef01234567",
2217            "0123456789abcdef0123456789abcdef0123456 ",
2218            "0123456789abcdef0123456789abcdef012345/7",
2219            "0123456789abcdef0123456789abcdef012345:7",
2220            "0123456789abcdef0123456789abcdef012345`7",
2221            "0123456789abcdef0123456789abcdef012345G7",
2222        ] {
2223            assert!(
2224                matches!(ObjectId::from_hex(bad), Err(Error::Object(ObjectError::InvalidId { input: s })) if s == bad),
2225                "{bad:?}"
2226            );
2227            assert!(bad.parse::<ObjectId>().is_err(), "{bad:?}");
2228            assert!(ObjectId::from_hex_ascii(bad.as_bytes()).is_err(), "{bad:?}");
2229        }
2230        let mut non_ascii = sha1.as_bytes().to_vec();
2231        non_ascii[3] = 0xb0;
2232        assert!(ObjectId::from_hex_ascii(&non_ascii).is_err());
2233    }
2234
2235    #[test]
2236    fn hex_and_display_cover_every_byte_for_both_lengths() {
2237        let all: Vec<u8> = (0..=255).collect();
2238        for width in [20, 32] {
2239            for chunk in all.chunks(width).filter(|c| c.len() == width) {
2240                let oid = ObjectId::from_bytes(chunk).unwrap();
2241                let expected: String = chunk.iter().map(|b| format!("{b:02x}")).collect();
2242                assert_eq!(oid.to_hex(), expected);
2243                assert_eq!(oid.to_string(), expected);
2244                assert_eq!(format!("{oid:?}"), format!("ObjectId({expected})"));
2245                assert_eq!(ObjectId::from_hex(&expected).unwrap(), oid);
2246            }
2247        }
2248    }
2249
2250    #[test]
2251    fn serialize_commit_applies_public_field_edits_after_parse() {
2252        let raw = concat!(
2253            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",
2254            "author A <a@example.com> 1 +0000\n",
2255            "committer C <c@example.com> 1 +0000\n",
2256            "\n",
2257            "msg\n",
2258        );
2259        let mut commit = parse_commit(raw.as_bytes()).expect("parse");
2260        let zero = ObjectId::from_hex("0000000000000000000000000000000000000000").unwrap();
2261        commit.tree = zero;
2262        let serialized = serialize_commit(&commit);
2263        let tree_line = format!("tree {}\n", zero.to_hex());
2264        assert!(
2265            serialized.starts_with(tree_line.as_bytes()),
2266            "serialize_commit ignored the updated public tree field"
2267        );
2268    }
2269
2270    #[test]
2271    fn parse_commit_preserves_gpgsig_mergetag_bytes_exactly() {
2272        let raw = concat!(
2273            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",
2274            "author A <a@example.com> 1 +0000\n",
2275            "committer C <c@example.com> 1 +0000\n",
2276            "encoding ISO-8859-1\n",
2277            "gpgsig -----BEGIN PGP SIGNATURE-----\n",
2278            " line2\n",
2279            " -----END PGP SIGNATURE-----\n",
2280            "mergetag object 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n",
2281            " type commit\n",
2282            " tag merge-tag\n",
2283            " tagger T <t@example.com> 1 +0000\n",
2284            " -----BEGIN PGP SIGNATURE-----\n",
2285            " inner\n",
2286            " -----END PGP SIGNATURE-----\n",
2287            "\n",
2288            "msg-only\n",
2289        );
2290        let parsed = parse_commit(raw.as_bytes()).expect("parse");
2291        assert_eq!(serialize_commit(&parsed), raw.as_bytes());
2292    }
2293
2294    #[test]
2295    fn tree_entry_mode_str_and_tag_object_line_oid() {
2296        let oid = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").unwrap();
2297        let entry = TreeEntry {
2298            mode: 0o040000,
2299            name: b"dir".to_vec(),
2300            oid,
2301        };
2302        assert_eq!(entry.mode_str(), "40000");
2303        let tag_body = format!("object {}\ntype commit\ntag t\n\n", oid.to_hex());
2304        assert_eq!(tag_object_line_oid(tag_body.as_bytes()), Some(oid));
2305    }
2306
2307    #[test]
2308    fn parse_commit_non_commit_bytes_does_not_panic() {
2309        let tree_bytes = b"100644 blob 0123456789012345678901234567890123456789\tf";
2310        let err = parse_commit(tree_bytes).expect_err("tree bytes are not a commit");
2311        assert!(matches!(err, Error::Object(ObjectError::Corrupt { .. })));
2312    }
2313
2314    #[test]
2315    fn parse_tree_with_sha256_oid_width() {
2316        let oid_bytes = [0x6eu8; 32];
2317        let oid = ObjectId::from_bytes(&oid_bytes).expect("oid");
2318        let mut raw = b"100644 file\0".to_vec();
2319        raw.extend_from_slice(oid.as_bytes());
2320        let entries = parse_tree_for_algo(&raw, HashAlgo::Sha256).expect("tree");
2321        assert_eq!(entries.len(), 1);
2322        assert_eq!(entries[0].oid, oid);
2323    }
2324
2325    #[test]
2326    fn parse_commit_tree_and_parents_prefix_matches_full_parse_or_declines() -> Result<()> {
2327        let tree = "1111111111111111111111111111111111111111";
2328        let p1 = "2222222222222222222222222222222222222222";
2329        let p2 = "3333333333333333333333333333333333333333";
2330        let raw = format!(
2331            "tree {tree}\nparent {p1}\nparent {p2}\nauthor A <a@x> 1 +0000\n\
2332             committer C <c@x> 2 +0000\n\nmessage\n"
2333        );
2334        let commit = parse_commit(raw.as_bytes())?;
2335        let full = (commit.tree, commit.parents);
2336        assert_eq!(full.1.len(), 2);
2337        assert_eq!(
2338            parse_commit_tree_and_parents_lenient(raw.as_bytes(), HashAlgo::Sha1.hex_len()),
2339            Some(full.clone())
2340        );
2341        let hex_len = HashAlgo::Sha1.hex_len();
2342        let header_end = raw.find("author").expect("author line");
2343        for cut in 0..=raw.len() {
2344            let got = parse_commit_tree_and_parents_prefix(&raw.as_bytes()[..cut], hex_len);
2345            if cut > header_end {
2346                assert_eq!(got.as_ref(), Some(&full), "cut at {cut}");
2347            } else {
2348                assert_eq!(
2349                    got, None,
2350                    "cut at {cut} must not claim a complete parent list"
2351                );
2352            }
2353        }
2354        Ok(())
2355    }
2356
2357    #[test]
2358    fn commit_tree_and_parents_prefix_never_disagrees_with_whole_object() {
2359        let tree = "tree 1111111111111111111111111111111111111111\n";
2360        let parent = "parent 2222222222222222222222222222222222222222\n";
2361        let parent2 = "parent 3333333333333333333333333333333333333333\n";
2362        let bodies = [
2363            format!("{tree}{parent}author A <a@x> 1 +0000\n\nmessage\n"),
2364            format!("{tree}{parent}{parent2}committer C <c@x> 2 +0000\n\nno author\n"),
2365            format!("{tree}{parent}"),
2366            format!("{tree}{parent}{parent2}"),
2367            format!("{tree}author A <a@x> 1 +0000\n{parent}\nlate parent is ignored\n"),
2368            format!("{tree}{parent}not a header\n"),
2369            format!("{tree}parent zz\n\n"),
2370            format!("{tree}{parent}parent 2222"),
2371            format!("author A <a@x> 1 +0000\n{tree}\n"),
2372        ];
2373        let hex_len = HashAlgo::Sha1.hex_len();
2374        for body in &bodies {
2375            let whole = parse_commit_tree_and_parents_lenient(body.as_bytes(), hex_len);
2376            for cut in 0..=body.len() {
2377                if let Some(got) =
2378                    parse_commit_tree_and_parents_prefix(&body.as_bytes()[..cut], hex_len)
2379                {
2380                    assert_eq!(Some(got), whole, "cut {cut} of {body:?}");
2381                }
2382            }
2383        }
2384        let parents_of = |body: &str| {
2385            parse_commit_tree_and_parents_lenient(body.as_bytes(), hex_len).map(|(_, p)| p.len())
2386        };
2387        assert_eq!(parents_of(&bodies[1]), Some(2), "missing author is fine");
2388        assert_eq!(
2389            parents_of(&bodies[3]),
2390            Some(2),
2391            "object may end after parents"
2392        );
2393        assert_eq!(
2394            parents_of(&bodies[4]),
2395            Some(0),
2396            "only leading parents count"
2397        );
2398        assert_eq!(parents_of(&bodies[6]), None, "malformed parent line");
2399        assert_eq!(parents_of(&bodies[7]), None, "truncated parent line");
2400        assert_eq!(parents_of(&bodies[8]), None, "tree must come first");
2401    }
2402
2403    #[test]
2404    fn parse_commit_tree_and_parents_prefix_handles_root_and_sha256() -> Result<()> {
2405        let root = b"tree 1111111111111111111111111111111111111111\nauthor A <a@x> 1 +0000\n";
2406        let (tree, parents) =
2407            parse_commit_tree_and_parents_prefix(root, HashAlgo::Sha1.hex_len()).expect("root");
2408        assert_eq!(tree.to_hex(), "1111111111111111111111111111111111111111");
2409        assert!(parents.is_empty());
2410
2411        let t = "a".repeat(64);
2412        let p = "b".repeat(64);
2413        let raw = format!("tree {t}\nparent {p}\ncommitter C <c@x> 2 +0000\n");
2414        let (tree, parents) =
2415            parse_commit_tree_and_parents_prefix(raw.as_bytes(), HashAlgo::Sha256.hex_len())
2416                .expect("sha256");
2417        assert_eq!(tree.to_hex(), t);
2418        assert_eq!(parents.len(), 1);
2419        assert_eq!(parents[0].to_hex(), p);
2420
2421        assert!(parse_commit_tree_and_parents_prefix(raw.as_bytes(), 40).is_none());
2422        assert!(parse_commit_tree_and_parents_prefix(b"parent x\n", 40).is_none());
2423        assert!(parse_commit_tree_and_parents_prefix(
2424            b"tree zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\nauthor\n",
2425            40
2426        )
2427        .is_none());
2428        Ok(())
2429    }
2430
2431    #[test]
2432    fn object_id_loose_path_helpers() {
2433        let oid = ObjectId::from_hex("4b825dc642cb6eb9a060e54bf8d69288fbee4904").unwrap();
2434        assert_eq!(oid.loose_prefix(), "4b");
2435        assert_eq!(oid.loose_suffix().len(), 38);
2436        assert!(ObjectId::is_hex_len(40));
2437        assert!(ObjectId::is_loose_suffix_len(38));
2438    }
2439
2440    #[test]
2441    fn tree_ref_iter_yields_at_most_one_error() {
2442        let bad = b"100644 incomplete";
2443        let mut iter = TreeRefIter::with_oid_len(bad, HashAlgo::Sha1.len());
2444        assert!(iter.next().unwrap().is_err());
2445        assert!(iter.next().is_none());
2446    }
2447
2448    #[test]
2449    fn tree_ref_iter_public_api_smoke() {
2450        let data = serialize_tree(&[TreeEntry {
2451            mode: 0o100644,
2452            name: b"a".to_vec(),
2453            oid: ObjectId::from_hex("0123456789012345678901234567890123456789").unwrap(),
2454        }]);
2455        let mut iter = TreeRefIter::infer_oid_len(&data).expect("infer");
2456        let entry = iter.next().unwrap().expect("entry");
2457        assert_eq!(entry.name, b"a");
2458        let _owned = entry.to_owned();
2459        let _vec = parse_tree(&data).expect("parse");
2460        let _ = TreeRefIter::with_oid_len(&data, HashAlgo::Sha1.len());
2461    }
2462
2463    #[test]
2464    fn find_tree_entry_by_name_in_data_locates_directory_in_large_tree() -> Result<()> {
2465        let dummy = ObjectId::from_hex("0123456789012345678901234567890123456789")?;
2466        let mut entries: Vec<TreeEntry> = (1..=60)
2467            .map(|i| TreeEntry {
2468                mode: 0o100644,
2469                name: format!("f{i}.txt").into_bytes(),
2470                oid: dummy,
2471            })
2472            .collect();
2473        entries.push(TreeEntry {
2474            mode: 0o040000,
2475            name: b"sub".to_vec(),
2476            oid: dummy,
2477        });
2478        entries.sort_by(|a, b| {
2479            tree_name_cmp(&a.name, a.mode == 0o040000, &b.name, b.mode == 0o040000)
2480        });
2481        let data = serialize_tree(&entries);
2482        assert!(entries.len() >= 48);
2483        let found = find_tree_entry_by_name_in_data(&data, HashAlgo::Sha1.len(), b"sub", true)?
2484            .expect("sub directory in wide tree");
2485        assert_eq!(found.mode, 0o040000);
2486        assert_eq!(found.name, b"sub");
2487        Ok(())
2488    }
2489
2490    fn sorted_tree_data(entries: &mut [TreeEntry]) -> Vec<u8> {
2491        entries.sort_by(|a, b| {
2492            tree_name_cmp(&a.name, a.mode == 0o040000, &b.name, b.mode == 0o040000)
2493        });
2494        serialize_tree(entries)
2495    }
2496
2497    #[test]
2498    fn find_tree_entry_by_name_in_data_matches_parse_tree_for_every_name() -> Result<()> {
2499        let oid_a = ObjectId::from_hex("1111111111111111111111111111111111111111")?;
2500        let oid_b = ObjectId::from_hex("2222222222222222222222222222222222222222")?;
2501        let mut entries = vec![
2502            TreeEntry {
2503                mode: 0o040000,
2504                name: b"foo".to_vec(),
2505                oid: oid_a,
2506            },
2507            TreeEntry {
2508                mode: 0o100644,
2509                name: b"foo.c".to_vec(),
2510                oid: oid_b,
2511            },
2512            TreeEntry {
2513                mode: 0o100755,
2514                name: b"foo-bar".to_vec(),
2515                oid: oid_b,
2516            },
2517            TreeEntry {
2518                mode: 0o120000,
2519                name: b"link".to_vec(),
2520                oid: oid_a,
2521            },
2522            TreeEntry {
2523                mode: 0o160000,
2524                name: b"sub".to_vec(),
2525                oid: oid_b,
2526            },
2527            TreeEntry {
2528                mode: 0o100644,
2529                name: b"README".to_vec(),
2530                oid: oid_a,
2531            },
2532        ];
2533        let data = sorted_tree_data(&mut entries);
2534        for expected in parse_tree(&data)? {
2535            let name_is_tree = expected.mode == 0o040000;
2536            let found = find_tree_entry_by_name_in_data(
2537                &data,
2538                HashAlgo::Sha1.len(),
2539                &expected.name,
2540                name_is_tree,
2541            )?
2542            .expect("entry present");
2543            assert_eq!(found, expected);
2544        }
2545        for missing in [&b"fo"[..], b"foo/", b"foo.d", b"zzz", b"", b"AAA", b"lin"] {
2546            assert!(
2547                find_tree_entry_by_name_in_data(&data, HashAlgo::Sha1.len(), missing, false)?
2548                    .is_none(),
2549                "unexpected match for {:?}",
2550                String::from_utf8_lossy(missing)
2551            );
2552        }
2553        Ok(())
2554    }
2555
2556    #[test]
2557    fn find_tree_entry_by_name_in_data_stops_after_sorted_position() -> Result<()> {
2558        let oid = ObjectId::from_hex("3333333333333333333333333333333333333333")?;
2559        let mut entries = vec![
2560            TreeEntry {
2561                mode: 0o100644,
2562                name: b"a".to_vec(),
2563                oid,
2564            },
2565            TreeEntry {
2566                mode: 0o100644,
2567                name: b"c".to_vec(),
2568                oid,
2569            },
2570        ];
2571        let mut data = sorted_tree_data(&mut entries);
2572        data.extend_from_slice(b"garbage without separators");
2573        let found = find_tree_entry_by_name_in_data(&data, HashAlgo::Sha1.len(), b"a", false)?;
2574        assert_eq!(found.map(|e| e.name), Some(b"a".to_vec()));
2575        assert!(
2576            find_tree_entry_by_name_in_data(&data, HashAlgo::Sha1.len(), b"b", false)?.is_none()
2577        );
2578        assert!(matches!(
2579            find_tree_entry_by_name_in_data(&data, HashAlgo::Sha1.len(), b"d", false),
2580            Err(Error::Object(ObjectError::Corrupt { .. }))
2581        ));
2582        Ok(())
2583    }
2584
2585    #[test]
2586    fn find_tree_entry_by_name_in_data_rejects_bad_mode_and_truncated_oid() {
2587        let bad_mode = b"10x644 a\0aaaaaaaaaaaaaaaaaaaa";
2588        assert!(matches!(
2589            find_tree_entry_by_name_in_data(bad_mode, HashAlgo::Sha1.len(), b"a", false),
2590            Err(Error::Object(ObjectError::Corrupt { .. }))
2591        ));
2592        let truncated = b"100644 a\0short";
2593        assert!(matches!(
2594            find_tree_entry_by_name_in_data(truncated, HashAlgo::Sha1.len(), b"a", false),
2595            Err(Error::Object(ObjectError::Corrupt { .. }))
2596        ));
2597    }
2598
2599    #[test]
2600    fn find_tree_entry_by_name_in_data_reads_sha256_width() -> Result<()> {
2601        let oid = ObjectId::from_bytes(&[0x5au8; 32])?;
2602        let mut raw = b"100644 file\0".to_vec();
2603        raw.extend_from_slice(oid.as_bytes());
2604        let found = find_tree_entry_by_name_in_data(&raw, HashAlgo::Sha256.len(), b"file", false)?
2605            .expect("file");
2606        assert_eq!(found.oid, oid);
2607        assert_eq!(found.mode, 0o100644);
2608        Ok(())
2609    }
2610
2611    #[test]
2612    fn tree_entry_span_matches_tree_ref_iter_and_defers_malformed_entries() {
2613        let mut data = Vec::new();
2614        for (mode, name) in [
2615            (&b"100644"[..], &b"a.txt"[..]),
2616            (b"40000", b"dir"),
2617            (b"+644", b"odd"),
2618        ] {
2619            data.extend_from_slice(mode);
2620            data.push(b' ');
2621            data.extend_from_slice(name);
2622            data.push(0);
2623            data.extend_from_slice(&[name[0]; 20]);
2624        }
2625        let mut iter = TreeRefIter::with_oid_len(&data, 20);
2626        let mut pos = 0;
2627        while let Some(entry) = iter.next() {
2628            let entry = entry.unwrap();
2629            let span = tree_entry_span(&data, pos, 20).expect("well-formed entry");
2630            assert_eq!(span.mode, entry.mode);
2631            assert_eq!(&data[span.name], entry.name);
2632            assert_eq!(span.end, iter.position());
2633            assert_eq!(&data[span.end - 20..span.end], entry.oid.as_bytes());
2634            assert_eq!(
2635                TreeRefIter::with_oid_len_at(&data, 20, pos)
2636                    .next()
2637                    .unwrap()
2638                    .unwrap(),
2639                entry
2640            );
2641            pos = iter.position();
2642        }
2643        assert_eq!(pos, data.len());
2644        assert!(tree_entry_span(&data, pos, 20).is_none());
2645        let (first, second) = (6 + 1 + 5 + 1 + 20, 5 + 1 + 3 + 1 + 20);
2646        // A truncated id, a bad mode, a missing NUL and a non-digest id width.
2647        assert!(tree_entry_span(&data[..first + second - 1], first, 20).is_none());
2648        assert!(tree_entry_span(b"10064x f\0aaaaaaaaaaaaaaaaaaaa", 0, 20).is_none());
2649        assert!(tree_entry_span(b"100644 f", 0, 20).is_none());
2650        assert!(tree_entry_span(&data, 0, 19).is_none());
2651        for bad in [
2652            &data[..first + second - 1],
2653            b"10064x f\0aaaaaaaaaaaaaaaaaaaa",
2654        ] {
2655            assert!(TreeRefIter::with_oid_len(bad, 20).any(|entry| entry.is_err()));
2656        }
2657    }
2658
2659    #[test]
2660    fn object_id_from_bytes_accepts_only_digest_lengths() {
2661        let sha1 = ObjectId::from_bytes(&[0xab; 20]).unwrap();
2662        assert_eq!(sha1.as_bytes(), &[0xab; 20]);
2663        assert_eq!(sha1.algo(), HashAlgo::Sha1);
2664        let sha256 = ObjectId::from_bytes(&[0xcd; 32]).unwrap();
2665        assert_eq!(sha256.as_bytes(), &[0xcd; 32]);
2666        assert_eq!(sha256.algo(), HashAlgo::Sha256);
2667        assert!(matches!(
2668            ObjectId::from_bytes(&[1; 19]),
2669            Err(Error::Object(ObjectError::InvalidId { input: hex })) if hex == "01".repeat(19)
2670        ));
2671    }
2672
2673    #[test]
2674    fn parse_tree_mode_accepts_what_from_str_radix_accepts() {
2675        let cases: &[&[u8]] = &[
2676            b"100644",
2677            b"40000",
2678            b"040000",
2679            b"160000",
2680            b"120000",
2681            b"0",
2682            b"7777777777",
2683            b"37777777777",
2684            b"77777777777",
2685            b"777777777777",
2686            b"",
2687            b"+644",
2688            b"-644",
2689            b"100648",
2690            b"10064a",
2691            b"1 0",
2692            b"\xff",
2693            b"00000000000100644",
2694        ];
2695        for &case in cases {
2696            let expected = std::str::from_utf8(case)
2697                .ok()
2698                .and_then(|s| u32::from_str_radix(s, 8).ok());
2699            assert_eq!(
2700                parse_tree_mode(case),
2701                expected,
2702                "mode {:?}",
2703                String::from_utf8_lossy(case)
2704            );
2705        }
2706    }
2707}
2708
2709#[cfg(test)]
2710mod tests {
2711    use super::*;
2712
2713    const HEAD: &str = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\nauthor A <a@example.com> 1 +0000\ncommitter C <c@example.com> 2 +0000\n";
2714
2715    fn len_of(message: &[u8]) -> Option<usize> {
2716        let mut data = HEAD.as_bytes().to_vec();
2717        data.extend_from_slice(message);
2718        commit_through_subject_len(&data).map(|len| len - HEAD.len())
2719    }
2720
2721    #[test]
2722    fn commit_through_subject_len_ends_after_the_first_non_blank_line() {
2723        assert_eq!(len_of(b"\nsubject\n\nbody\n"), Some(9));
2724        assert_eq!(len_of(b"\n\n \t\r\n  subject\r\nmore\n"), Some(17));
2725        assert_eq!(len_of(b"\nx\n"), Some(3));
2726        let signed = b"gpgsig -----BEGIN-----\n \n abc\n -----END-----\n\nsigned\nbody\n";
2727        assert_eq!(len_of(signed), Some(signed.len() - 5));
2728    }
2729
2730    #[test]
2731    fn commit_through_subject_len_skips_lines_that_may_decode_blank() {
2732        let message = "\n\u{a0}\u{3000}\n\u{65e5}\u{672c}\nascii\nbody\n";
2733        assert_eq!(
2734            len_of(message.as_bytes()),
2735            Some(message.len() - "body\n".len())
2736        );
2737    }
2738
2739    #[test]
2740    fn commit_through_subject_len_needs_a_complete_prefix() {
2741        assert_eq!(len_of(b""), None);
2742        assert_eq!(len_of(b"\n"), None);
2743        assert_eq!(len_of(b"\n\n   \n"), None);
2744        assert_eq!(len_of(b"\nsubject without newline"), None);
2745        assert_eq!(commit_through_subject_len(b"tree 4b82"), None);
2746        assert_eq!(commit_through_subject_len(HEAD.as_bytes()), None);
2747    }
2748
2749    #[test]
2750    fn commit_through_subject_len_gives_up_on_other_encodings() {
2751        assert_eq!(len_of(b"encoding ISO-8859-1\n\nS\xe9ance\n\nbody\n"), None);
2752        assert_eq!(len_of(b"encoding ISO-2022-JP\n\nsubject\n"), None);
2753        assert_eq!(len_of(b"encoding UTF-8\n\nsubject\nbody\n"), Some(24));
2754        assert_eq!(len_of(b"encoding utf8 \n\nsubject\nbody\n"), Some(24));
2755    }
2756
2757    #[test]
2758    fn commit_through_subject_prefix_parses_like_the_whole_commit() {
2759        let whole = format!("{HEAD}change-id zzzz\n\n\n  Subject here  \n\nlong body\n");
2760        let len = commit_through_subject_len(whole.as_bytes()).unwrap();
2761        let prefix = &whole.as_bytes()[..len];
2762        assert_eq!(
2763            read_commit_subject_line(prefix).unwrap(),
2764            read_commit_subject_line(whole.as_bytes()).unwrap()
2765        );
2766        let (short, full) = (
2767            parse_commit(prefix).unwrap(),
2768            parse_commit(whole.as_bytes()).unwrap(),
2769        );
2770        assert_eq!(short.extra_headers, full.extra_headers);
2771        assert_eq!(short.author, full.author);
2772        assert_eq!(short.message, "\n  Subject here  \n");
2773    }
2774}