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