Skip to main content

ostrya_core/
commit.rs

1//! Commit objects.
2//!
3//! This module has no borrowed view type. `Commit::parse` returns the owned
4//! struct.
5
6use std::sync::LazyLock;
7
8use ostrya_gvariant::{
9    ArrayIter, GvDecode, GvEncode, GvType, Slice, Type, Value, VariantBytes, from_bytes, to_bytes,
10};
11
12use crate::be::Be64;
13use crate::checksum::Checksum;
14use crate::error::{Error, Result};
15
16/// The type `a{sv}` of the metadata dict, parsed one time and shared. `Type`
17/// is `Send + Sync`, so each parse call and each serialize call use this value.
18static METADATA_TYPE: LazyLock<Type> =
19    LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));
20
21/// An owned commit object.
22///
23/// # Wire form
24///
25/// A commit object is the GVariant tuple `(a{sv}aya(say)sstayay)`. It holds
26/// these members, in this order:
27///
28/// 1. `a{sv}`: the metadata dict
29/// 2. `ay`: the checksum of the parent commit, empty for a root commit
30/// 3. `a(say)`: the related objects
31/// 4. `s`: the subject
32/// 5. `s`: the body
33/// 6. `t`: the timestamp, big-endian
34/// 7. `ay`: the checksum of the root dirtree
35/// 8. `ay`: the checksum of the root dirmeta
36///
37/// The struct holds the timestamp in host byte order.
38///
39/// The metadata is a [`Value`] tree. It writes back to the same bytes,
40/// because [`from_bytes`] accepts only normal form and [`to_bytes`] writes
41/// normal form.
42///
43/// A walk of a long parent chain uses [`Commit::parse_link`]. A check of the
44/// timestamp alone uses [`Commit::parse_timestamp`].
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Commit {
47    /// The `a{sv}` metadata dict as a [`Value`] tree.
48    ///
49    /// The tree is an array of two-element tuples, in on-disk order.
50    pub metadata: Value,
51    /// The checksum of the parent commit, or `None` for a root commit.
52    pub parent: Option<Checksum>,
53    /// The related objects.
54    ///
55    /// The `ostree` command writes an empty array. A parse keeps the entries
56    /// as read, so the commit serializes to the same bytes.
57    pub related: Vec<(String, Vec<u8>)>,
58    /// The commit subject, the first line of its message.
59    pub subject: String,
60    /// The commit body, the rest of its message.
61    pub body: String,
62    /// The commit time, in seconds since the Unix epoch, UTC.
63    pub timestamp: u64,
64    /// The checksum of the dirtree object of the root directory.
65    pub root_dirtree: Checksum,
66    /// The checksum of the dirmeta object of the root directory.
67    pub root_dirmeta: Checksum,
68}
69
70/// The parent and the root checksums of a commit, from [`Commit::parse_link`].
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct CommitLink {
73    /// The checksum of the parent commit, or `None` for a root commit.
74    pub parent: Option<Checksum>,
75    /// The checksum of the dirtree object of the root directory.
76    pub root_dirtree: Checksum,
77    /// The checksum of the dirmeta object of the root directory.
78    pub root_dirmeta: Checksum,
79}
80
81/// The commit tuple with the metadata and the checksums as raw slices. The
82/// parse functions apply the value checks to this view.
83type CommitView<'a> = (
84    &'a [u8],
85    &'a [u8],
86    ArrayIter<'a, (&'a str, &'a [u8])>,
87    &'a str,
88    &'a str,
89    Be64,
90    &'a [u8],
91    &'a [u8],
92);
93
94impl Commit {
95    /// Parses a serialized commit object.
96    ///
97    /// # Errors
98    ///
99    /// - [`Error::Gvariant`] with [`NotNormal`] if `data`, the metadata dict,
100    ///   or an entry of the related objects is not in normal form.
101    /// - [`Error::Gvariant`] with [`DepthExceeded`] if the metadata dict nests
102    ///   deeper than the depth limit of [`from_bytes`].
103    /// - [`Error::InvalidCommit`] with "parent checksum is neither empty nor
104    ///   32 bytes" if the parent checksum has a length other than 0 or 32.
105    /// - [`Error::InvalidCommit`] with "root dirtree checksum is not 32 bytes"
106    ///   if the root dirtree checksum has a length other than 32.
107    /// - [`Error::InvalidCommit`] with "root dirmeta checksum is not 32 bytes"
108    ///   if the root dirmeta checksum has a length other than 32.
109    ///
110    /// [`NotNormal`]: ostrya_gvariant::Error::NotNormal
111    /// [`DepthExceeded`]: ostrya_gvariant::Error::DepthExceeded
112    pub fn parse(data: &[u8]) -> Result<Commit> {
113        let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
114        let metadata = from_bytes(&METADATA_TYPE, metadata)?;
115        let parent = parse_parent(parent)?;
116        let related = related
117            .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
118            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
119        Ok(Commit {
120            metadata,
121            parent,
122            related,
123            subject: subject.to_owned(),
124            body: body.to_owned(),
125            timestamp: timestamp.0,
126            root_dirtree: parse_root_dirtree(root_dirtree)?,
127            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
128        })
129    }
130
131    /// Parses a serialized commit object, and returns the entries of its
132    /// metadata dict as bytes beside it.
133    ///
134    /// The returned commit holds an empty metadata dict. Each entry is the key
135    /// and the bytes of its `v` in normal form, in the order of the dict. A
136    /// key that occurs in more than one entry stays in each entry. The
137    /// function checks the metadata dict as [`Commit::parse`] does, and builds
138    /// no value tree of it.
139    ///
140    /// # Errors
141    ///
142    /// The errors of [`Commit::parse`].
143    #[allow(clippy::type_complexity)]
144    pub fn parse_with_metadata_entries(data: &[u8]) -> Result<(Commit, Vec<(String, Vec<u8>)>)> {
145        let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
146        ostrya_gvariant::validate(&METADATA_TYPE, metadata)?;
147        let entries = ArrayIter::<(&str, VariantBytes)>::decode(metadata)?
148            .map(|entry| {
149                let (key, value) = entry?;
150                let mut bytes = Vec::new();
151                value.encode(&mut bytes)?;
152                Ok((key.to_owned(), bytes))
153            })
154            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
155        let parent = parse_parent(parent)?;
156        let related = related
157            .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
158            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
159        let commit = Commit {
160            metadata: Value::Array(Vec::new()),
161            parent,
162            related,
163            subject: subject.to_owned(),
164            body: body.to_owned(),
165            timestamp: timestamp.0,
166            root_dirtree: parse_root_dirtree(root_dirtree)?,
167            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
168        };
169        Ok((commit, entries))
170    }
171
172    /// Parses the parent and the root checksums of a serialized commit object.
173    ///
174    /// The function does not decode the metadata dict or the entries of the
175    /// related objects. It checks the tuple frame, the subject, the body, and
176    /// the three checksums as [`Commit::parse`] does.
177    ///
178    /// # Errors
179    ///
180    /// - [`Error::Gvariant`] with [`NotNormal`] if the tuple frame, the
181    ///   subject, or the body is not in normal form.
182    /// - [`Error::InvalidCommit`] with the messages of [`Commit::parse`] if
183    ///   the parent, the root dirtree, or the root dirmeta checksum has a
184    ///   wrong length.
185    ///
186    /// [`NotNormal`]: ostrya_gvariant::Error::NotNormal
187    pub fn parse_link(data: &[u8]) -> Result<CommitLink> {
188        let (_, parent, _, _, _, _, root_dirtree, root_dirmeta): CommitView =
189            GvDecode::decode(data)?;
190        Ok(CommitLink {
191            parent: parse_parent(parent)?,
192            root_dirtree: parse_root_dirtree(root_dirtree)?,
193            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
194        })
195    }
196
197    /// Parses the timestamp of a serialized commit object.
198    ///
199    /// The function does not decode the metadata dict or the entries of the
200    /// related objects. It checks the tuple frame, the subject, the body, and
201    /// the three checksums as [`Commit::parse`] does. The timestamp is in host
202    /// byte order, as [`Commit::timestamp`] holds it.
203    ///
204    /// # Errors
205    ///
206    /// The errors of [`Commit::parse_link`].
207    pub fn parse_timestamp(data: &[u8]) -> Result<u64> {
208        let (_, parent, _, _, _, timestamp, root_dirtree, root_dirmeta): CommitView =
209            GvDecode::decode(data)?;
210        parse_parent(parent)?;
211        parse_root_dirtree(root_dirtree)?;
212        parse_root_dirmeta(root_dirmeta)?;
213        Ok(timestamp.0)
214    }
215
216    /// Serializes the commit to normal-form bytes.
217    ///
218    /// The SHA-256 of these bytes is the commit checksum, which
219    /// [`checksum`](Commit::checksum) returns.
220    ///
221    /// # Errors
222    ///
223    /// - [`Error::Gvariant`] with [`TypeMismatch`] if
224    ///   [`metadata`](Commit::metadata) is not a value of type `a{sv}`.
225    /// - [`Error::Gvariant`] with [`InvalidValue`] if a string holds an
226    ///   interior NUL byte. This applies to the strings in the metadata, the
227    ///   subject, the body, and the names of the related objects.
228    /// - [`Error::Gvariant`] with [`DepthExceeded`] if the metadata nests
229    ///   deeper than the depth limit of [`to_bytes`].
230    ///
231    /// [`TypeMismatch`]: ostrya_gvariant::Error::TypeMismatch
232    /// [`InvalidValue`]: ostrya_gvariant::Error::InvalidValue
233    /// [`DepthExceeded`]: ostrya_gvariant::Error::DepthExceeded
234    pub fn serialize(&self) -> Result<Vec<u8>> {
235        Ok(ostrya_gvariant::encode_to_vec(self)?)
236    }
237
238    /// Serializes the commit with the serialized `a{sv}` dict `metadata` in
239    /// place of [`metadata`](Commit::metadata).
240    ///
241    /// The call writes `metadata` as it is and reads no field
242    /// [`metadata`](Commit::metadata), so a caller that holds the metadata as
243    /// bytes builds no value tree. The call does not check `metadata`. If it
244    /// is not a normal-form `a{sv}` dict, [`Commit::parse`] refuses the
245    /// result. With the bytes of `self.metadata`, the result is the result of
246    /// [`serialize`](Commit::serialize).
247    ///
248    /// # Errors
249    ///
250    /// [`Error::Gvariant`] with [`InvalidValue`] if a string holds an
251    /// interior NUL byte: the subject, the body, or the name of a related
252    /// object.
253    ///
254    /// [`InvalidValue`]: ostrya_gvariant::Error::InvalidValue
255    pub fn serialize_with_metadata(&self, metadata: &[u8]) -> Result<Vec<u8>> {
256        let mut out = Vec::new();
257        self.encode_with(metadata, &mut out)?;
258        Ok(out)
259    }
260
261    /// Returns the commit checksum, the SHA-256 of the serialized bytes.
262    ///
263    /// # Errors
264    ///
265    /// The errors of [`serialize`](Commit::serialize).
266    pub fn checksum(&self) -> Result<Checksum> {
267        Ok(Checksum::sha256(&self.serialize()?))
268    }
269
270    /// Returns the content checksum of the commit.
271    ///
272    /// The content checksum is the SHA-256 of the 32-byte root dirtree
273    /// checksum followed by the 32-byte root dirmeta checksum. The metadata
274    /// and the timestamp of the commit do not change it.
275    pub fn content_checksum(&self) -> Checksum {
276        let mut buf = [0u8; 64];
277        buf[..32].copy_from_slice(self.root_dirtree.as_bytes());
278        buf[32..].copy_from_slice(self.root_dirmeta.as_bytes());
279        Checksum::sha256(&buf)
280    }
281
282    /// Returns the child of the variant under `key` in the metadata dict.
283    ///
284    /// If `key` occurs in more than one entry, the first entry applies. If no
285    /// entry has `key`, or if its value is not a variant, the result is `None`.
286    pub fn metadata_value(&self, key: &str) -> Option<&Value> {
287        self.metadata
288            .dict_get(key)?
289            .as_variant()
290            .map(|(_, value)| value)
291    }
292
293    /// Returns the value of the `version` metadata key.
294    ///
295    /// `version` is the only well-known key without the `ostree.` prefix. If
296    /// the key is absent, or if its value is not a string, the result is
297    /// `None`.
298    pub fn version(&self) -> Option<&str> {
299        self.metadata_value("version")?.as_str()
300    }
301
302    /// Returns the ref names in the `ostree.ref-binding` metadata key.
303    ///
304    /// If the key is absent, or if the commit is bound to no ref, the list is
305    /// empty.
306    pub fn ref_bindings(&self) -> Vec<&str> {
307        self.metadata_value("ostree.ref-binding")
308            .and_then(Value::as_array)
309            .map(|refs| refs.iter().filter_map(Value::as_str).collect())
310            .unwrap_or_default()
311    }
312
313    /// Returns the value of the `ostree.collection-binding` metadata key.
314    ///
315    /// If the key is absent, or if its value is not a string, the result is
316    /// `None`.
317    pub fn collection_binding(&self) -> Option<&str> {
318        self.metadata_value("ostree.collection-binding")?.as_str()
319    }
320}
321
322/// The parent checksum of a commit: an empty `ay` for a root commit.
323fn parse_parent(parent: &[u8]) -> Result<Option<Checksum>> {
324    match parent.len() {
325        0 => Ok(None),
326        32 => Ok(Some(Checksum::from_ay(parent)?)),
327        _ => Err(Error::InvalidCommit(
328            "parent checksum is neither empty nor 32 bytes",
329        )),
330    }
331}
332
333/// The root dirtree checksum of a commit.
334fn parse_root_dirtree(root_dirtree: &[u8]) -> Result<Checksum> {
335    Checksum::from_ay(root_dirtree)
336        .map_err(|_| Error::InvalidCommit("root dirtree checksum is not 32 bytes"))
337}
338
339/// The root dirmeta checksum of a commit.
340fn parse_root_dirmeta(root_dirmeta: &[u8]) -> Result<Checksum> {
341    Checksum::from_ay(root_dirmeta)
342        .map_err(|_| Error::InvalidCommit("root dirmeta checksum is not 32 bytes"))
343}
344
345/// A pre-serialized `a{sv}` spliced in as the first tuple member.
346struct RawDict<'a>(&'a [u8]);
347
348impl GvType for RawDict<'_> {
349    const ALIGNMENT: usize = 8;
350    const FIXED_SIZE: Option<usize> = None;
351}
352
353impl GvEncode for RawDict<'_> {
354    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
355        out.extend_from_slice(self.0);
356        Ok(())
357    }
358}
359
360impl GvType for Commit {
361    const SIGNATURE: &'static str = "(a{sv}aya(say)sstayay)";
362    // Greatest member alignment: the metadata dict and the timestamp.
363    const ALIGNMENT: usize = 8;
364    const FIXED_SIZE: Option<usize> = None;
365}
366
367impl GvEncode for Commit {
368    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
369        let metadata = to_bytes(&METADATA_TYPE, &self.metadata)?;
370        self.encode_with(&metadata, out)
371    }
372}
373
374impl Commit {
375    /// Writes the commit tuple with the serialized metadata dict `metadata`.
376    fn encode_with(&self, metadata: &[u8], out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
377        let parent: &[u8] = match &self.parent {
378            Some(checksum) => checksum.as_bytes(),
379            None => &[],
380        };
381        let related: Vec<(&str, &[u8])> = self
382            .related
383            .iter()
384            .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
385            .collect();
386        (
387            RawDict(metadata),
388            parent,
389            Slice(&related),
390            self.subject.as_str(),
391            self.body.as_str(),
392            Be64(self.timestamp),
393            self.root_dirtree,
394            self.root_dirmeta,
395        )
396            .encode(out)
397    }
398}
399
400/// The metadata key that holds the ref names a commit is bound to.
401const REF_BINDING_KEY: &str = "ostree.ref-binding";
402/// The metadata key that holds the collection id a commit is bound to.
403const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
404
405/// Returns the `ostree.ref-binding` value for `refs`.
406///
407/// The value is a variant of type `as`. It holds the names sorted byte-wise
408/// in ascending order, with duplicates kept. An empty list gives the empty
409/// array, which is the value of a commit bound to no ref.
410pub fn ref_binding(refs: &[&str]) -> Value {
411    let mut names = refs.to_vec();
412    names.sort_unstable();
413    Value::variant(
414        Type::parse("as").expect("\"as\" is a valid gvariant type"),
415        Value::Array(
416            names
417                .into_iter()
418                .map(|name| Value::Str(name.to_owned()))
419                .collect(),
420        ),
421    )
422}
423
424/// Returns the `a{sv}` metadata dict of a new commit.
425///
426/// The entry order is part of the commit checksum. The dict holds these
427/// entries, in this order:
428///
429/// 1. `entries`, in the order given, with duplicate keys kept
430/// 2. `ostree.ref-binding` with the [`ref_binding`] value for `refs`, if
431///    `refs` is set
432/// 3. `ostree.collection-binding` with `collection_id`, if `collection_id` is
433///    set
434///
435/// If `refs` is `None`, the dict holds neither binding key, and the function
436/// ignores `collection_id`. Each value in `entries` must be a
437/// [`Value::Variant`], or [`Commit::serialize`] returns an error.
438pub fn commit_metadata(
439    entries: impl IntoIterator<Item = (String, Value)>,
440    refs: Option<&[&str]>,
441    collection_id: Option<&str>,
442) -> Value {
443    let mut dict: Vec<Value> = entries
444        .into_iter()
445        .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
446        .collect();
447    if let Some(refs) = refs {
448        dict.push(Value::Tuple(vec![
449            Value::Str(REF_BINDING_KEY.to_owned()),
450            ref_binding(refs),
451        ]));
452        if let Some(collection) = collection_id {
453            dict.push(Value::Tuple(vec![
454                Value::Str(COLLECTION_BINDING_KEY.to_owned()),
455                Value::variant(Type::Str, Value::Str(collection.to_owned())),
456            ]));
457        }
458    }
459    Value::Array(dict)
460}
461
462/// An error of [`commit_timestamp`] and of [`source_date_epoch`].
463#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum TimestampError {
465    /// A `SOURCE_DATE_EPOCH` value that is not a count of seconds.
466    ///
467    /// The variant holds the value as read, before the trim.
468    SourceDateEpoch(String),
469    /// The system clock is before the Unix epoch.
470    ClockBeforeEpoch,
471}
472
473impl std::fmt::Display for TimestampError {
474    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475        match self {
476            TimestampError::SourceDateEpoch(raw) => {
477                write!(f, "SOURCE_DATE_EPOCH is not a Unix timestamp: {raw:?}")
478            }
479            TimestampError::ClockBeforeEpoch => {
480                f.write_str("the system clock is before the Unix epoch")
481            }
482        }
483    }
484}
485
486impl std::error::Error for TimestampError {}
487
488/// Returns the timestamp of a new commit.
489///
490/// The timestamp is in seconds since the Unix epoch, UTC. The function takes
491/// it from the first of these sources that is set:
492///
493/// 1. `explicit`
494/// 2. the `SOURCE_DATE_EPOCH` environment variable
495/// 3. the system clock
496///
497/// The function trims white space from `SOURCE_DATE_EPOCH` before it parses
498/// the value. If `SOURCE_DATE_EPOCH` is not valid Unicode, the function
499/// treats it as unset.
500///
501/// # Errors
502///
503/// - [`TimestampError::SourceDateEpoch`] if `explicit` is `None` and
504///   `SOURCE_DATE_EPOCH` is set to a value that is not a count of seconds.
505///   The function does not use the clock in this case, as the
506///   reproducible-build convention requires.
507/// - [`TimestampError::ClockBeforeEpoch`] if the function reads the system
508///   clock and the clock is before the Unix epoch.
509pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
510    timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
511}
512
513/// Returns the value of the `SOURCE_DATE_EPOCH` environment variable, in
514/// seconds since the Unix epoch.
515///
516/// The function reads the variable with the rule of [`commit_timestamp`]: it
517/// trims white space before it parses the value, and it treats a value that
518/// is not valid Unicode as unset. If the variable is unset, the result is
519/// `None`.
520///
521/// # Errors
522///
523/// [`TimestampError::SourceDateEpoch`] if the variable is set to a value
524/// that is not a count of seconds.
525pub fn source_date_epoch() -> std::result::Result<Option<u64>, TimestampError> {
526    parse_source_date_epoch(std::env::var("SOURCE_DATE_EPOCH").ok())
527}
528
529/// [`source_date_epoch`] over a given `SOURCE_DATE_EPOCH` value.
530fn parse_source_date_epoch(
531    raw: Option<String>,
532) -> std::result::Result<Option<u64>, TimestampError> {
533    raw.map(|raw| {
534        raw.trim()
535            .parse::<u64>()
536            .map_err(|_| TimestampError::SourceDateEpoch(raw))
537    })
538    .transpose()
539}
540
541/// [`commit_timestamp`] over a given `SOURCE_DATE_EPOCH` value.
542fn timestamp_from(
543    explicit: Option<u64>,
544    source_date_epoch: Option<String>,
545) -> std::result::Result<u64, TimestampError> {
546    if let Some(timestamp) = explicit {
547        return Ok(timestamp);
548    }
549    if let Some(timestamp) = parse_source_date_epoch(source_date_epoch)? {
550        return Ok(timestamp);
551    }
552    let now = std::time::SystemTime::now()
553        .duration_since(std::time::UNIX_EPOCH)
554        .map_err(|_| TimestampError::ClockBeforeEpoch)?;
555    Ok(now.as_secs())
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    fn csum(byte: u8) -> Checksum {
563        Checksum::from_bytes([byte; 32])
564    }
565
566    fn sample() -> Commit {
567        Commit {
568            metadata: Value::Array(vec![Value::Tuple(vec![
569                Value::Str("version".to_owned()),
570                Value::variant(Type::Str, Value::Str("42".to_owned())),
571            ])]),
572            parent: Some(csum(0xaa)),
573            related: Vec::new(),
574            subject: "subject".to_owned(),
575            body: "body".to_owned(),
576            timestamp: 1_700_000_000,
577            root_dirtree: csum(1),
578            root_dirmeta: csum(2),
579        }
580    }
581
582    /// The entries are the key and the `v` of each entry of the dict, in
583    /// order, with duplicate keys kept. The rest is the parsed commit.
584    #[test]
585    fn metadata_entries_are_the_variants_of_the_dict() {
586        let entry = |key: &str, value: Value| Value::Tuple(vec![Value::Str(key.into()), value]);
587        let values = [
588            ("z", Value::variant(Type::Str, Value::Str("1".into()))),
589            ("a", Value::variant(Type::U32, Value::U32(7))),
590            (
591                "z",
592                Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![1, 2, 3])),
593            ),
594        ];
595        let commit = Commit {
596            metadata: Value::Array(values.iter().map(|(k, v)| entry(k, v.clone())).collect()),
597            ..sample()
598        };
599        let bytes = commit.serialize().unwrap();
600        let (bare, entries) = Commit::parse_with_metadata_entries(&bytes).unwrap();
601        assert_eq!(
602            bare,
603            Commit {
604                metadata: Value::Array(Vec::new()),
605                ..commit
606            }
607        );
608        assert_eq!(entries.len(), values.len());
609        for ((key, raw), (want_key, want)) in entries.iter().zip(&values) {
610            assert_eq!(key, want_key);
611            assert_eq!(&from_bytes(&Type::Variant, raw).unwrap(), want);
612        }
613
614        // A dict that `Commit::parse` refuses is refused.
615        let mut bad = bytes.clone();
616        bad[0] ^= 0xff;
617        assert!(Commit::parse(&bad).is_err());
618        assert!(Commit::parse_with_metadata_entries(&bad).is_err());
619    }
620
621    #[test]
622    fn round_trips_with_parent_and_metadata() {
623        let commit = sample();
624        let bytes = commit.serialize().unwrap();
625        let parsed = Commit::parse(&bytes).unwrap();
626        assert_eq!(parsed, commit);
627        assert_eq!(parsed.serialize().unwrap(), bytes);
628        assert_eq!(parsed.version(), Some("42"));
629        assert!(parsed.ref_bindings().is_empty());
630        assert_eq!(parsed.collection_binding(), None);
631    }
632
633    /// The bytes of the metadata dict in place of the dict give the bytes of
634    /// `serialize`, and the call does not read the field.
635    #[test]
636    fn serialize_with_metadata_splices_the_dict_bytes() {
637        let commit = sample();
638        let dict = to_bytes(&METADATA_TYPE, &commit.metadata).unwrap();
639        let other = Commit {
640            metadata: Value::Array(Vec::new()),
641            ..sample()
642        };
643        assert_eq!(
644            other.serialize_with_metadata(&dict).unwrap(),
645            commit.serialize().unwrap()
646        );
647    }
648
649    #[test]
650    fn empty_parent_ay_means_a_root_commit() {
651        let commit = Commit {
652            parent: None,
653            ..sample()
654        };
655        let parsed = Commit::parse(&commit.serialize().unwrap()).unwrap();
656        assert_eq!(parsed.parent, None);
657    }
658
659    /// Serializes a commit through the `Value` tree with any width of the
660    /// parent and the root dirtree checksums. The `Commit` struct cannot hold
661    /// such widths.
662    fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
663        craft_with(parent, root_dirtree, &[2; 32])
664    }
665
666    /// [`craft`] with any width of the root dirmeta checksum.
667    fn craft_with(parent: &[u8], root_dirtree: &[u8], root_dirmeta: &[u8]) -> Vec<u8> {
668        let ty = Type::parse(<Commit as GvType>::SIGNATURE).unwrap();
669        let value = Value::Tuple(vec![
670            Value::Array(Vec::new()),
671            Value::Bytes(parent.to_vec()),
672            Value::Array(Vec::new()),
673            Value::Str(String::new()),
674            Value::Str(String::new()),
675            Value::U64(0),
676            Value::Bytes(root_dirtree.to_vec()),
677            Value::Bytes(root_dirmeta.to_vec()),
678        ]);
679        to_bytes(&ty, &value).unwrap()
680    }
681
682    #[test]
683    fn parse_rejects_malformed_checksum_widths() {
684        assert_eq!(
685            Commit::parse(&craft(&[0xaa; 31], &[1; 32])),
686            Err(Error::InvalidCommit(
687                "parent checksum is neither empty nor 32 bytes"
688            ))
689        );
690        assert_eq!(
691            Commit::parse(&craft(&[], &[1; 31])),
692            Err(Error::InvalidCommit(
693                "root dirtree checksum is not 32 bytes"
694            ))
695        );
696    }
697
698    #[test]
699    fn parse_link_agrees_with_parse() {
700        let root = Commit {
701            parent: None,
702            ..sample()
703        };
704        for commit in [sample(), root] {
705            let bytes = commit.serialize().unwrap();
706            let parsed = Commit::parse(&bytes).unwrap();
707            assert_eq!(
708                Commit::parse_link(&bytes).unwrap(),
709                CommitLink {
710                    parent: parsed.parent,
711                    root_dirtree: parsed.root_dirtree,
712                    root_dirmeta: parsed.root_dirmeta,
713                }
714            );
715        }
716    }
717
718    #[test]
719    fn parse_link_refuses_what_parse_refuses_in_its_fields() {
720        let whole = sample().serialize().unwrap();
721        for bytes in [
722            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
723            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
724            craft_with(&[], &[1; 31], &[2; 32]),
725            craft_with(&[], &[1; 32], &[2; 33]),
726            craft_with(&[], &[1; 32], &[]),
727            whole[..whole.len() - 1].to_vec(),
728            Vec::new(),
729        ] {
730            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
731            assert_eq!(Commit::parse_link(&bytes), Err(refused));
732        }
733    }
734
735    #[test]
736    fn parse_timestamp_agrees_with_parse() {
737        let root = Commit {
738            parent: None,
739            ..sample()
740        };
741        let wide = Commit {
742            timestamp: 0x0102_0304_0506_0708,
743            ..sample()
744        };
745        for commit in [sample(), root, wide] {
746            let bytes = commit.serialize().unwrap();
747            assert_eq!(
748                Commit::parse_timestamp(&bytes).unwrap(),
749                Commit::parse(&bytes).unwrap().timestamp
750            );
751        }
752    }
753
754    #[test]
755    fn parse_timestamp_refuses_what_parse_refuses_in_its_fields() {
756        let whole = sample().serialize().unwrap();
757        for bytes in [
758            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
759            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
760            craft_with(&[], &[1; 31], &[2; 32]),
761            craft_with(&[], &[1; 32], &[2; 33]),
762            craft_with(&[], &[1; 32], &[]),
763            whole[..whole.len() - 1].to_vec(),
764            Vec::new(),
765        ] {
766            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
767            assert_eq!(Commit::parse_timestamp(&bytes), Err(refused));
768        }
769    }
770
771    #[test]
772    fn content_checksum_hashes_the_two_root_checksums() {
773        let commit = sample();
774        let mut buf = Vec::new();
775        buf.extend_from_slice(csum(1).as_bytes());
776        buf.extend_from_slice(csum(2).as_bytes());
777        assert_eq!(commit.content_checksum(), Checksum::sha256(&buf));
778    }
779
780    fn entry(key: &str, value: &str) -> (String, Value) {
781        (
782            key.to_owned(),
783            Value::variant(Type::Str, Value::Str(value.to_owned())),
784        )
785    }
786
787    fn text(value: &Value) -> String {
788        ostrya_gvariant::to_text(&METADATA_TYPE, value).unwrap()
789    }
790
791    #[test]
792    fn commit_metadata_orders_entries_then_bindings() {
793        let dict = commit_metadata(
794            [entry("b", "1"), entry("a", "2"), entry("b", "3")],
795            Some(&["zeta", "alpha", "mid", "alpha"]),
796            Some("org.example.C"),
797        );
798        assert_eq!(
799            text(&dict),
800            "{'b': <'1'>, 'a': <'2'>, 'b': <'3'>, \
801             'ostree.ref-binding': <['alpha', 'alpha', 'mid', 'zeta']>, \
802             'ostree.collection-binding': <'org.example.C'>}"
803        );
804    }
805
806    #[test]
807    fn commit_metadata_without_refs_holds_no_binding_key() {
808        let dict = commit_metadata([entry("k", "v")], None, Some("org.example.C"));
809        assert_eq!(text(&dict), "{'k': <'v'>}");
810        assert_eq!(commit_metadata([], None, None), Value::Array(Vec::new()));
811    }
812
813    #[test]
814    fn empty_ref_list_writes_the_empty_array() {
815        let dict = commit_metadata([], Some(&[]), None);
816        assert_eq!(text(&dict), "{'ostree.ref-binding': <@as []>}");
817        assert_eq!(
818            dict,
819            Value::Array(vec![Value::Tuple(vec![
820                Value::Str("ostree.ref-binding".to_owned()),
821                ref_binding(&[]),
822            ])])
823        );
824    }
825
826    #[test]
827    fn timestamp_prefers_explicit_then_source_date_epoch() {
828        assert_eq!(timestamp_from(Some(5), Some("abc".to_owned())), Ok(5));
829        assert_eq!(
830            timestamp_from(None, Some(" 1700000000\n".to_owned())),
831            Ok(1_700_000_000)
832        );
833        let err = timestamp_from(None, Some("abc".to_owned())).unwrap_err();
834        assert_eq!(err, TimestampError::SourceDateEpoch("abc".to_owned()));
835        assert_eq!(
836            err.to_string(),
837            "SOURCE_DATE_EPOCH is not a Unix timestamp: \"abc\""
838        );
839        let now = std::time::SystemTime::now()
840            .duration_since(std::time::UNIX_EPOCH)
841            .unwrap()
842            .as_secs();
843        let got = timestamp_from(None, None).unwrap();
844        assert!(got.abs_diff(now) <= 5, "{got} is near {now}");
845    }
846
847    #[test]
848    fn source_date_epoch_is_trimmed_and_unset_is_none() {
849        assert_eq!(parse_source_date_epoch(None), Ok(None));
850        assert_eq!(
851            parse_source_date_epoch(Some(" 1700000000\n".to_owned())),
852            Ok(Some(1_700_000_000))
853        );
854        for raw in ["", "abc", "-1", "@1"] {
855            assert_eq!(
856                parse_source_date_epoch(Some(raw.to_owned())),
857                Err(TimestampError::SourceDateEpoch(raw.to_owned())),
858                "{raw:?}"
859            );
860        }
861    }
862}