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, 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 the parent and the root checksums of a serialized commit object.
132    ///
133    /// The function does not decode the metadata dict or the entries of the
134    /// related objects. It checks the tuple frame, the subject, the body, and
135    /// the three checksums as [`Commit::parse`] does.
136    ///
137    /// # Errors
138    ///
139    /// - [`Error::Gvariant`] with [`NotNormal`] if the tuple frame, the
140    ///   subject, or the body is not in normal form.
141    /// - [`Error::InvalidCommit`] with the messages of [`Commit::parse`] if
142    ///   the parent, the root dirtree, or the root dirmeta checksum has a
143    ///   wrong length.
144    ///
145    /// [`NotNormal`]: ostrya_gvariant::Error::NotNormal
146    pub fn parse_link(data: &[u8]) -> Result<CommitLink> {
147        let (_, parent, _, _, _, _, root_dirtree, root_dirmeta): CommitView =
148            GvDecode::decode(data)?;
149        Ok(CommitLink {
150            parent: parse_parent(parent)?,
151            root_dirtree: parse_root_dirtree(root_dirtree)?,
152            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
153        })
154    }
155
156    /// Parses the timestamp of a serialized commit object.
157    ///
158    /// The function does not decode the metadata dict or the entries of the
159    /// related objects. It checks the tuple frame, the subject, the body, and
160    /// the three checksums as [`Commit::parse`] does. The timestamp is in host
161    /// byte order, as [`Commit::timestamp`] holds it.
162    ///
163    /// # Errors
164    ///
165    /// The errors of [`Commit::parse_link`].
166    pub fn parse_timestamp(data: &[u8]) -> Result<u64> {
167        let (_, parent, _, _, _, timestamp, root_dirtree, root_dirmeta): CommitView =
168            GvDecode::decode(data)?;
169        parse_parent(parent)?;
170        parse_root_dirtree(root_dirtree)?;
171        parse_root_dirmeta(root_dirmeta)?;
172        Ok(timestamp.0)
173    }
174
175    /// Serializes the commit to normal-form bytes.
176    ///
177    /// The SHA-256 of these bytes is the commit checksum, which
178    /// [`checksum`](Commit::checksum) returns.
179    ///
180    /// # Errors
181    ///
182    /// - [`Error::Gvariant`] with [`TypeMismatch`] if
183    ///   [`metadata`](Commit::metadata) is not a value of type `a{sv}`.
184    /// - [`Error::Gvariant`] with [`InvalidValue`] if a string holds an
185    ///   interior NUL byte. This applies to the strings in the metadata, the
186    ///   subject, the body, and the names of the related objects.
187    /// - [`Error::Gvariant`] with [`DepthExceeded`] if the metadata nests
188    ///   deeper than the depth limit of [`to_bytes`].
189    ///
190    /// [`TypeMismatch`]: ostrya_gvariant::Error::TypeMismatch
191    /// [`InvalidValue`]: ostrya_gvariant::Error::InvalidValue
192    /// [`DepthExceeded`]: ostrya_gvariant::Error::DepthExceeded
193    pub fn serialize(&self) -> Result<Vec<u8>> {
194        Ok(ostrya_gvariant::encode_to_vec(self)?)
195    }
196
197    /// Returns the commit checksum, the SHA-256 of the serialized bytes.
198    ///
199    /// # Errors
200    ///
201    /// The errors of [`serialize`](Commit::serialize).
202    pub fn checksum(&self) -> Result<Checksum> {
203        Ok(Checksum::sha256(&self.serialize()?))
204    }
205
206    /// Returns the content checksum of the commit.
207    ///
208    /// The content checksum is the SHA-256 of the 32-byte root dirtree
209    /// checksum followed by the 32-byte root dirmeta checksum. The metadata
210    /// and the timestamp of the commit do not change it.
211    pub fn content_checksum(&self) -> Checksum {
212        let mut buf = [0u8; 64];
213        buf[..32].copy_from_slice(self.root_dirtree.as_bytes());
214        buf[32..].copy_from_slice(self.root_dirmeta.as_bytes());
215        Checksum::sha256(&buf)
216    }
217
218    /// Returns the child of the variant under `key` in the metadata dict.
219    ///
220    /// If `key` occurs in more than one entry, the first entry applies. If no
221    /// entry has `key`, or if its value is not a variant, the result is `None`.
222    pub fn metadata_value(&self, key: &str) -> Option<&Value> {
223        self.metadata
224            .dict_get(key)?
225            .as_variant()
226            .map(|(_, value)| value)
227    }
228
229    /// Returns the value of the `version` metadata key.
230    ///
231    /// `version` is the only well-known key without the `ostree.` prefix. If
232    /// the key is absent, or if its value is not a string, the result is
233    /// `None`.
234    pub fn version(&self) -> Option<&str> {
235        self.metadata_value("version")?.as_str()
236    }
237
238    /// Returns the ref names in the `ostree.ref-binding` metadata key.
239    ///
240    /// If the key is absent, or if the commit is bound to no ref, the list is
241    /// empty.
242    pub fn ref_bindings(&self) -> Vec<&str> {
243        self.metadata_value("ostree.ref-binding")
244            .and_then(Value::as_array)
245            .map(|refs| refs.iter().filter_map(Value::as_str).collect())
246            .unwrap_or_default()
247    }
248
249    /// Returns the value of the `ostree.collection-binding` metadata key.
250    ///
251    /// If the key is absent, or if its value is not a string, the result is
252    /// `None`.
253    pub fn collection_binding(&self) -> Option<&str> {
254        self.metadata_value("ostree.collection-binding")?.as_str()
255    }
256}
257
258/// The parent checksum of a commit: an empty `ay` for a root commit.
259fn parse_parent(parent: &[u8]) -> Result<Option<Checksum>> {
260    match parent.len() {
261        0 => Ok(None),
262        32 => Ok(Some(Checksum::from_ay(parent)?)),
263        _ => Err(Error::InvalidCommit(
264            "parent checksum is neither empty nor 32 bytes",
265        )),
266    }
267}
268
269/// The root dirtree checksum of a commit.
270fn parse_root_dirtree(root_dirtree: &[u8]) -> Result<Checksum> {
271    Checksum::from_ay(root_dirtree)
272        .map_err(|_| Error::InvalidCommit("root dirtree checksum is not 32 bytes"))
273}
274
275/// The root dirmeta checksum of a commit.
276fn parse_root_dirmeta(root_dirmeta: &[u8]) -> Result<Checksum> {
277    Checksum::from_ay(root_dirmeta)
278        .map_err(|_| Error::InvalidCommit("root dirmeta checksum is not 32 bytes"))
279}
280
281/// A pre-serialized `a{sv}` spliced in as the first tuple member.
282struct RawDict<'a>(&'a [u8]);
283
284impl GvType for RawDict<'_> {
285    const ALIGNMENT: usize = 8;
286    const FIXED_SIZE: Option<usize> = None;
287}
288
289impl GvEncode for RawDict<'_> {
290    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
291        out.extend_from_slice(self.0);
292        Ok(())
293    }
294}
295
296impl GvType for Commit {
297    const SIGNATURE: &'static str = "(a{sv}aya(say)sstayay)";
298    // Greatest member alignment: the metadata dict and the timestamp.
299    const ALIGNMENT: usize = 8;
300    const FIXED_SIZE: Option<usize> = None;
301}
302
303impl GvEncode for Commit {
304    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
305        let metadata = to_bytes(&METADATA_TYPE, &self.metadata)?;
306        let parent: &[u8] = match &self.parent {
307            Some(checksum) => checksum.as_bytes(),
308            None => &[],
309        };
310        let related: Vec<(&str, &[u8])> = self
311            .related
312            .iter()
313            .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
314            .collect();
315        (
316            RawDict(&metadata),
317            parent,
318            Slice(&related),
319            self.subject.as_str(),
320            self.body.as_str(),
321            Be64(self.timestamp),
322            self.root_dirtree,
323            self.root_dirmeta,
324        )
325            .encode(out)
326    }
327}
328
329/// The metadata key that holds the ref names a commit is bound to.
330const REF_BINDING_KEY: &str = "ostree.ref-binding";
331/// The metadata key that holds the collection id a commit is bound to.
332const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
333
334/// Returns the `ostree.ref-binding` value for `refs`.
335///
336/// The value is a variant of type `as`. It holds the names sorted byte-wise
337/// in ascending order, with duplicates kept. An empty list gives the empty
338/// array, which is the value of a commit bound to no ref.
339pub fn ref_binding(refs: &[&str]) -> Value {
340    let mut names = refs.to_vec();
341    names.sort_unstable();
342    Value::variant(
343        Type::parse("as").expect("\"as\" is a valid gvariant type"),
344        Value::Array(
345            names
346                .into_iter()
347                .map(|name| Value::Str(name.to_owned()))
348                .collect(),
349        ),
350    )
351}
352
353/// Returns the `a{sv}` metadata dict of a new commit.
354///
355/// The entry order is part of the commit checksum. The dict holds these
356/// entries, in this order:
357///
358/// 1. `entries`, in the order given, with duplicate keys kept
359/// 2. `ostree.ref-binding` with the [`ref_binding`] value for `refs`, if
360///    `refs` is set
361/// 3. `ostree.collection-binding` with `collection_id`, if `collection_id` is
362///    set
363///
364/// If `refs` is `None`, the dict holds neither binding key, and the function
365/// ignores `collection_id`. Each value in `entries` must be a
366/// [`Value::Variant`], or [`Commit::serialize`] returns an error.
367pub fn commit_metadata(
368    entries: impl IntoIterator<Item = (String, Value)>,
369    refs: Option<&[&str]>,
370    collection_id: Option<&str>,
371) -> Value {
372    let mut dict: Vec<Value> = entries
373        .into_iter()
374        .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
375        .collect();
376    if let Some(refs) = refs {
377        dict.push(Value::Tuple(vec![
378            Value::Str(REF_BINDING_KEY.to_owned()),
379            ref_binding(refs),
380        ]));
381        if let Some(collection) = collection_id {
382            dict.push(Value::Tuple(vec![
383                Value::Str(COLLECTION_BINDING_KEY.to_owned()),
384                Value::variant(Type::Str, Value::Str(collection.to_owned())),
385            ]));
386        }
387    }
388    Value::Array(dict)
389}
390
391/// An error of [`commit_timestamp`].
392#[derive(Debug, Clone, PartialEq, Eq)]
393pub enum TimestampError {
394    /// A `SOURCE_DATE_EPOCH` value that is not a count of seconds.
395    ///
396    /// The variant holds the value as read, before the trim.
397    SourceDateEpoch(String),
398    /// The system clock is before the Unix epoch.
399    ClockBeforeEpoch,
400}
401
402impl std::fmt::Display for TimestampError {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        match self {
405            TimestampError::SourceDateEpoch(raw) => {
406                write!(f, "SOURCE_DATE_EPOCH is not a Unix timestamp: {raw:?}")
407            }
408            TimestampError::ClockBeforeEpoch => {
409                f.write_str("the system clock is before the Unix epoch")
410            }
411        }
412    }
413}
414
415impl std::error::Error for TimestampError {}
416
417/// Returns the timestamp of a new commit.
418///
419/// The timestamp is in seconds since the Unix epoch, UTC. The function takes
420/// it from the first of these sources that is set:
421///
422/// 1. `explicit`
423/// 2. the `SOURCE_DATE_EPOCH` environment variable
424/// 3. the system clock
425///
426/// The function trims white space from `SOURCE_DATE_EPOCH` before it parses
427/// the value. If `SOURCE_DATE_EPOCH` is not valid Unicode, the function
428/// treats it as unset.
429///
430/// # Errors
431///
432/// - [`TimestampError::SourceDateEpoch`] if `explicit` is `None` and
433///   `SOURCE_DATE_EPOCH` is set to a value that is not a count of seconds.
434///   The function does not use the clock in this case, as the
435///   reproducible-build convention requires.
436/// - [`TimestampError::ClockBeforeEpoch`] if the function reads the system
437///   clock and the clock is before the Unix epoch.
438pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
439    timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
440}
441
442/// [`commit_timestamp`] over a given `SOURCE_DATE_EPOCH` value.
443fn timestamp_from(
444    explicit: Option<u64>,
445    source_date_epoch: Option<String>,
446) -> std::result::Result<u64, TimestampError> {
447    if let Some(timestamp) = explicit {
448        return Ok(timestamp);
449    }
450    if let Some(raw) = source_date_epoch {
451        return raw
452            .trim()
453            .parse::<u64>()
454            .map_err(|_| TimestampError::SourceDateEpoch(raw));
455    }
456    let now = std::time::SystemTime::now()
457        .duration_since(std::time::UNIX_EPOCH)
458        .map_err(|_| TimestampError::ClockBeforeEpoch)?;
459    Ok(now.as_secs())
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    fn csum(byte: u8) -> Checksum {
467        Checksum::from_bytes([byte; 32])
468    }
469
470    fn sample() -> Commit {
471        Commit {
472            metadata: Value::Array(vec![Value::Tuple(vec![
473                Value::Str("version".to_owned()),
474                Value::variant(Type::Str, Value::Str("42".to_owned())),
475            ])]),
476            parent: Some(csum(0xaa)),
477            related: Vec::new(),
478            subject: "subject".to_owned(),
479            body: "body".to_owned(),
480            timestamp: 1_700_000_000,
481            root_dirtree: csum(1),
482            root_dirmeta: csum(2),
483        }
484    }
485
486    #[test]
487    fn round_trips_with_parent_and_metadata() {
488        let commit = sample();
489        let bytes = commit.serialize().unwrap();
490        let parsed = Commit::parse(&bytes).unwrap();
491        assert_eq!(parsed, commit);
492        assert_eq!(parsed.serialize().unwrap(), bytes);
493        assert_eq!(parsed.version(), Some("42"));
494        assert!(parsed.ref_bindings().is_empty());
495        assert_eq!(parsed.collection_binding(), None);
496    }
497
498    #[test]
499    fn empty_parent_ay_means_a_root_commit() {
500        let commit = Commit {
501            parent: None,
502            ..sample()
503        };
504        let parsed = Commit::parse(&commit.serialize().unwrap()).unwrap();
505        assert_eq!(parsed.parent, None);
506    }
507
508    /// Serializes a commit through the `Value` tree with any width of the
509    /// parent and the root dirtree checksums. The `Commit` struct cannot hold
510    /// such widths.
511    fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
512        craft_with(parent, root_dirtree, &[2; 32])
513    }
514
515    /// [`craft`] with any width of the root dirmeta checksum.
516    fn craft_with(parent: &[u8], root_dirtree: &[u8], root_dirmeta: &[u8]) -> Vec<u8> {
517        let ty = Type::parse(<Commit as GvType>::SIGNATURE).unwrap();
518        let value = Value::Tuple(vec![
519            Value::Array(Vec::new()),
520            Value::Bytes(parent.to_vec()),
521            Value::Array(Vec::new()),
522            Value::Str(String::new()),
523            Value::Str(String::new()),
524            Value::U64(0),
525            Value::Bytes(root_dirtree.to_vec()),
526            Value::Bytes(root_dirmeta.to_vec()),
527        ]);
528        to_bytes(&ty, &value).unwrap()
529    }
530
531    #[test]
532    fn parse_rejects_malformed_checksum_widths() {
533        assert_eq!(
534            Commit::parse(&craft(&[0xaa; 31], &[1; 32])),
535            Err(Error::InvalidCommit(
536                "parent checksum is neither empty nor 32 bytes"
537            ))
538        );
539        assert_eq!(
540            Commit::parse(&craft(&[], &[1; 31])),
541            Err(Error::InvalidCommit(
542                "root dirtree checksum is not 32 bytes"
543            ))
544        );
545    }
546
547    #[test]
548    fn parse_link_agrees_with_parse() {
549        let root = Commit {
550            parent: None,
551            ..sample()
552        };
553        for commit in [sample(), root] {
554            let bytes = commit.serialize().unwrap();
555            let parsed = Commit::parse(&bytes).unwrap();
556            assert_eq!(
557                Commit::parse_link(&bytes).unwrap(),
558                CommitLink {
559                    parent: parsed.parent,
560                    root_dirtree: parsed.root_dirtree,
561                    root_dirmeta: parsed.root_dirmeta,
562                }
563            );
564        }
565    }
566
567    #[test]
568    fn parse_link_refuses_what_parse_refuses_in_its_fields() {
569        let whole = sample().serialize().unwrap();
570        for bytes in [
571            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
572            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
573            craft_with(&[], &[1; 31], &[2; 32]),
574            craft_with(&[], &[1; 32], &[2; 33]),
575            craft_with(&[], &[1; 32], &[]),
576            whole[..whole.len() - 1].to_vec(),
577            Vec::new(),
578        ] {
579            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
580            assert_eq!(Commit::parse_link(&bytes), Err(refused));
581        }
582    }
583
584    #[test]
585    fn parse_timestamp_agrees_with_parse() {
586        let root = Commit {
587            parent: None,
588            ..sample()
589        };
590        let wide = Commit {
591            timestamp: 0x0102_0304_0506_0708,
592            ..sample()
593        };
594        for commit in [sample(), root, wide] {
595            let bytes = commit.serialize().unwrap();
596            assert_eq!(
597                Commit::parse_timestamp(&bytes).unwrap(),
598                Commit::parse(&bytes).unwrap().timestamp
599            );
600        }
601    }
602
603    #[test]
604    fn parse_timestamp_refuses_what_parse_refuses_in_its_fields() {
605        let whole = sample().serialize().unwrap();
606        for bytes in [
607            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
608            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
609            craft_with(&[], &[1; 31], &[2; 32]),
610            craft_with(&[], &[1; 32], &[2; 33]),
611            craft_with(&[], &[1; 32], &[]),
612            whole[..whole.len() - 1].to_vec(),
613            Vec::new(),
614        ] {
615            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
616            assert_eq!(Commit::parse_timestamp(&bytes), Err(refused));
617        }
618    }
619
620    #[test]
621    fn content_checksum_hashes_the_two_root_checksums() {
622        let commit = sample();
623        let mut buf = Vec::new();
624        buf.extend_from_slice(csum(1).as_bytes());
625        buf.extend_from_slice(csum(2).as_bytes());
626        assert_eq!(commit.content_checksum(), Checksum::sha256(&buf));
627    }
628
629    fn entry(key: &str, value: &str) -> (String, Value) {
630        (
631            key.to_owned(),
632            Value::variant(Type::Str, Value::Str(value.to_owned())),
633        )
634    }
635
636    fn text(value: &Value) -> String {
637        ostrya_gvariant::to_text(&METADATA_TYPE, value).unwrap()
638    }
639
640    #[test]
641    fn commit_metadata_orders_entries_then_bindings() {
642        let dict = commit_metadata(
643            [entry("b", "1"), entry("a", "2"), entry("b", "3")],
644            Some(&["zeta", "alpha", "mid", "alpha"]),
645            Some("org.example.C"),
646        );
647        assert_eq!(
648            text(&dict),
649            "{'b': <'1'>, 'a': <'2'>, 'b': <'3'>, \
650             'ostree.ref-binding': <['alpha', 'alpha', 'mid', 'zeta']>, \
651             'ostree.collection-binding': <'org.example.C'>}"
652        );
653    }
654
655    #[test]
656    fn commit_metadata_without_refs_holds_no_binding_key() {
657        let dict = commit_metadata([entry("k", "v")], None, Some("org.example.C"));
658        assert_eq!(text(&dict), "{'k': <'v'>}");
659        assert_eq!(commit_metadata([], None, None), Value::Array(Vec::new()));
660    }
661
662    #[test]
663    fn empty_ref_list_writes_the_empty_array() {
664        let dict = commit_metadata([], Some(&[]), None);
665        assert_eq!(text(&dict), "{'ostree.ref-binding': <@as []>}");
666        assert_eq!(
667            dict,
668            Value::Array(vec![Value::Tuple(vec![
669                Value::Str("ostree.ref-binding".to_owned()),
670                ref_binding(&[]),
671            ])])
672        );
673    }
674
675    #[test]
676    fn timestamp_prefers_explicit_then_source_date_epoch() {
677        assert_eq!(timestamp_from(Some(5), Some("abc".to_owned())), Ok(5));
678        assert_eq!(
679            timestamp_from(None, Some(" 1700000000\n".to_owned())),
680            Ok(1_700_000_000)
681        );
682        let err = timestamp_from(None, Some("abc".to_owned())).unwrap_err();
683        assert_eq!(err, TimestampError::SourceDateEpoch("abc".to_owned()));
684        assert_eq!(
685            err.to_string(),
686            "SOURCE_DATE_EPOCH is not a Unix timestamp: \"abc\""
687        );
688        let now = std::time::SystemTime::now()
689            .duration_since(std::time::UNIX_EPOCH)
690            .unwrap()
691            .as_secs();
692        let got = timestamp_from(None, None).unwrap();
693        assert!(got.abs_diff(now) <= 5, "{got} is near {now}");
694    }
695}