ostrya-core 0.10.0

ostree object model, checksums, and on-disk format primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Commit objects.
//!
//! This module has no borrowed view type. `Commit::parse` returns the owned
//! struct.

use std::sync::LazyLock;

use ostrya_gvariant::{
    ArrayIter, GvDecode, GvEncode, GvType, Slice, Type, Value, VariantBytes, from_bytes, to_bytes,
};

use crate::be::Be64;
use crate::checksum::Checksum;
use crate::error::{Error, Result};

/// The type `a{sv}` of the metadata dict, parsed one time and shared. `Type`
/// is `Send + Sync`, so each parse call and each serialize call use this value.
static METADATA_TYPE: LazyLock<Type> =
    LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));

/// An owned commit object.
///
/// # Wire form
///
/// A commit object is the GVariant tuple `(a{sv}aya(say)sstayay)`. It holds
/// these members, in this order:
///
/// 1. `a{sv}`: the metadata dict
/// 2. `ay`: the checksum of the parent commit, empty for a root commit
/// 3. `a(say)`: the related objects
/// 4. `s`: the subject
/// 5. `s`: the body
/// 6. `t`: the timestamp, big-endian
/// 7. `ay`: the checksum of the root dirtree
/// 8. `ay`: the checksum of the root dirmeta
///
/// The struct holds the timestamp in host byte order.
///
/// The metadata is a [`Value`] tree. It writes back to the same bytes,
/// because [`from_bytes`] accepts only normal form and [`to_bytes`] writes
/// normal form.
///
/// A walk of a long parent chain uses [`Commit::parse_link`]. A check of the
/// timestamp alone uses [`Commit::parse_timestamp`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Commit {
    /// The `a{sv}` metadata dict as a [`Value`] tree.
    ///
    /// The tree is an array of two-element tuples, in on-disk order.
    pub metadata: Value,
    /// The checksum of the parent commit, or `None` for a root commit.
    pub parent: Option<Checksum>,
    /// The related objects.
    ///
    /// The `ostree` command writes an empty array. The port uses the field
    /// for the dependencies of a commit: each entry is a name and the 32-byte
    /// checksum of a commit. A parse keeps the entries as read, so the commit
    /// serializes to the same bytes.
    pub related: Vec<(String, Vec<u8>)>,
    /// The commit subject, the first line of its message.
    pub subject: String,
    /// The commit body, the rest of its message.
    pub body: String,
    /// The commit time, in seconds since the Unix epoch, UTC.
    pub timestamp: u64,
    /// The checksum of the dirtree object of the root directory.
    pub root_dirtree: Checksum,
    /// The checksum of the dirmeta object of the root directory.
    pub root_dirmeta: Checksum,
}

/// The parent and the root checksums of a commit, from [`Commit::parse_link`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommitLink {
    /// The checksum of the parent commit, or `None` for a root commit.
    pub parent: Option<Checksum>,
    /// The checksum of the dirtree object of the root directory.
    pub root_dirtree: Checksum,
    /// The checksum of the dirmeta object of the root directory.
    pub root_dirmeta: Checksum,
}

/// The commit tuple with the metadata and the checksums as raw slices. The
/// parse functions apply the value checks to this view.
type CommitView<'a> = (
    &'a [u8],
    &'a [u8],
    ArrayIter<'a, (&'a str, &'a [u8])>,
    &'a str,
    &'a str,
    Be64,
    &'a [u8],
    &'a [u8],
);

impl Commit {
    /// Parses a serialized commit object.
    ///
    /// # Errors
    ///
    /// - [`Error::Gvariant`] with [`NotNormal`] if `data`, the metadata dict,
    ///   or an entry of the related objects is not in normal form.
    /// - [`Error::Gvariant`] with [`DepthExceeded`] if the metadata dict nests
    ///   deeper than the depth limit of [`from_bytes`].
    /// - [`Error::InvalidCommit`] with "parent checksum is neither empty nor
    ///   32 bytes" if the parent checksum has a length other than 0 or 32.
    /// - [`Error::InvalidCommit`] with "root dirtree checksum is not 32 bytes"
    ///   if the root dirtree checksum has a length other than 32.
    /// - [`Error::InvalidCommit`] with "root dirmeta checksum is not 32 bytes"
    ///   if the root dirmeta checksum has a length other than 32.
    ///
    /// [`NotNormal`]: ostrya_gvariant::Error::NotNormal
    /// [`DepthExceeded`]: ostrya_gvariant::Error::DepthExceeded
    pub fn parse(data: &[u8]) -> Result<Commit> {
        let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
        let metadata = from_bytes(&METADATA_TYPE, metadata)?;
        let parent = parse_parent(parent)?;
        let related = related
            .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
        Ok(Commit {
            metadata,
            parent,
            related,
            subject: subject.to_owned(),
            body: body.to_owned(),
            timestamp: timestamp.0,
            root_dirtree: parse_root_dirtree(root_dirtree)?,
            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
        })
    }

    /// Parses a serialized commit object, and returns the entries of its
    /// metadata dict as bytes beside it.
    ///
    /// The returned commit holds an empty metadata dict. Each entry is the key
    /// and the bytes of its `v` in normal form, in the order of the dict. A
    /// key that occurs in more than one entry stays in each entry. The
    /// function checks the metadata dict as [`Commit::parse`] does, and builds
    /// no value tree of it.
    ///
    /// # Errors
    ///
    /// The errors of [`Commit::parse`].
    #[allow(clippy::type_complexity)]
    pub fn parse_with_metadata_entries(data: &[u8]) -> Result<(Commit, Vec<(String, Vec<u8>)>)> {
        let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
        ostrya_gvariant::validate(&METADATA_TYPE, metadata)?;
        let entries = ArrayIter::<(&str, VariantBytes)>::decode(metadata)?
            .map(|entry| {
                let (key, value) = entry?;
                let mut bytes = Vec::new();
                value.encode(&mut bytes)?;
                Ok((key.to_owned(), bytes))
            })
            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
        let parent = parse_parent(parent)?;
        let related = related
            .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
        let commit = Commit {
            metadata: Value::Array(Vec::new()),
            parent,
            related,
            subject: subject.to_owned(),
            body: body.to_owned(),
            timestamp: timestamp.0,
            root_dirtree: parse_root_dirtree(root_dirtree)?,
            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
        };
        Ok((commit, entries))
    }

    /// Parses the parent and the root checksums of a serialized commit object.
    ///
    /// The function does not decode the metadata dict or the entries of the
    /// related objects. It checks the tuple frame, the subject, the body, and
    /// the three checksums as [`Commit::parse`] does.
    ///
    /// # Errors
    ///
    /// - [`Error::Gvariant`] with [`NotNormal`] if the tuple frame, the
    ///   subject, or the body is not in normal form.
    /// - [`Error::InvalidCommit`] with the messages of [`Commit::parse`] if
    ///   the parent, the root dirtree, or the root dirmeta checksum has a
    ///   wrong length.
    ///
    /// [`NotNormal`]: ostrya_gvariant::Error::NotNormal
    pub fn parse_link(data: &[u8]) -> Result<CommitLink> {
        let (_, parent, _, _, _, _, root_dirtree, root_dirmeta): CommitView =
            GvDecode::decode(data)?;
        Ok(CommitLink {
            parent: parse_parent(parent)?,
            root_dirtree: parse_root_dirtree(root_dirtree)?,
            root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
        })
    }

    /// Parses the timestamp of a serialized commit object.
    ///
    /// The function does not decode the metadata dict or the entries of the
    /// related objects. It checks the tuple frame, the subject, the body, and
    /// the three checksums as [`Commit::parse`] does. The timestamp is in host
    /// byte order, as [`Commit::timestamp`] holds it.
    ///
    /// # Errors
    ///
    /// The errors of [`Commit::parse_link`].
    pub fn parse_timestamp(data: &[u8]) -> Result<u64> {
        let (_, parent, _, _, _, timestamp, root_dirtree, root_dirmeta): CommitView =
            GvDecode::decode(data)?;
        parse_parent(parent)?;
        parse_root_dirtree(root_dirtree)?;
        parse_root_dirmeta(root_dirmeta)?;
        Ok(timestamp.0)
    }

    /// Serializes the commit to normal-form bytes.
    ///
    /// The SHA-256 of these bytes is the commit checksum, which
    /// [`checksum`](Commit::checksum) returns.
    ///
    /// # Errors
    ///
    /// - [`Error::Gvariant`] with [`TypeMismatch`] if
    ///   [`metadata`](Commit::metadata) is not a value of type `a{sv}`.
    /// - [`Error::Gvariant`] with [`InvalidValue`] if a string holds an
    ///   interior NUL byte. This applies to the strings in the metadata, the
    ///   subject, the body, and the names of the related objects.
    /// - [`Error::Gvariant`] with [`DepthExceeded`] if the metadata nests
    ///   deeper than the depth limit of [`to_bytes`].
    ///
    /// [`TypeMismatch`]: ostrya_gvariant::Error::TypeMismatch
    /// [`InvalidValue`]: ostrya_gvariant::Error::InvalidValue
    /// [`DepthExceeded`]: ostrya_gvariant::Error::DepthExceeded
    pub fn serialize(&self) -> Result<Vec<u8>> {
        Ok(ostrya_gvariant::encode_to_vec(self)?)
    }

    /// Serializes the commit with the serialized `a{sv}` dict `metadata` in
    /// place of [`metadata`](Commit::metadata).
    ///
    /// The call writes `metadata` as it is and reads no field
    /// [`metadata`](Commit::metadata), so a caller that holds the metadata as
    /// bytes builds no value tree. The call does not check `metadata`. If it
    /// is not a normal-form `a{sv}` dict, [`Commit::parse`] refuses the
    /// result. With the bytes of `self.metadata`, the result is the result of
    /// [`serialize`](Commit::serialize).
    ///
    /// # Errors
    ///
    /// [`Error::Gvariant`] with [`InvalidValue`] if a string holds an
    /// interior NUL byte: the subject, the body, or the name of a related
    /// object.
    ///
    /// [`InvalidValue`]: ostrya_gvariant::Error::InvalidValue
    pub fn serialize_with_metadata(&self, metadata: &[u8]) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        self.encode_with(metadata, &mut out)?;
        Ok(out)
    }

    /// Returns the commit checksum, the SHA-256 of the serialized bytes.
    ///
    /// # Errors
    ///
    /// The errors of [`serialize`](Commit::serialize).
    pub fn checksum(&self) -> Result<Checksum> {
        Ok(Checksum::sha256(&self.serialize()?))
    }

    /// Returns the content checksum of the commit.
    ///
    /// The content checksum is the SHA-256 of the 32-byte root dirtree
    /// checksum followed by the 32-byte root dirmeta checksum. The metadata
    /// and the timestamp of the commit do not change it.
    pub fn content_checksum(&self) -> Checksum {
        let mut buf = [0u8; 64];
        buf[..32].copy_from_slice(self.root_dirtree.as_bytes());
        buf[32..].copy_from_slice(self.root_dirmeta.as_bytes());
        Checksum::sha256(&buf)
    }

    /// Returns the child of the variant under `key` in the metadata dict.
    ///
    /// If `key` occurs in more than one entry, the first entry applies. If no
    /// entry has `key`, or if its value is not a variant, the result is `None`.
    pub fn metadata_value(&self, key: &str) -> Option<&Value> {
        self.metadata
            .dict_get(key)?
            .as_variant()
            .map(|(_, value)| value)
    }

    /// Returns the value of the `version` metadata key.
    ///
    /// `version` is the only well-known key without the `ostree.` prefix. If
    /// the key is absent, or if its value is not a string, the result is
    /// `None`.
    pub fn version(&self) -> Option<&str> {
        self.metadata_value("version")?.as_str()
    }

    /// Returns the ref names in the `ostree.ref-binding` metadata key.
    ///
    /// If the key is absent, or if the commit is bound to no ref, the list is
    /// empty.
    pub fn ref_bindings(&self) -> Vec<&str> {
        self.metadata_value("ostree.ref-binding")
            .and_then(Value::as_array)
            .map(|refs| refs.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default()
    }

    /// Returns the value of the `ostree.collection-binding` metadata key.
    ///
    /// If the key is absent, or if its value is not a string, the result is
    /// `None`.
    pub fn collection_binding(&self) -> Option<&str> {
        self.metadata_value("ostree.collection-binding")?.as_str()
    }
}

/// The parent checksum of a commit: an empty `ay` for a root commit.
fn parse_parent(parent: &[u8]) -> Result<Option<Checksum>> {
    match parent.len() {
        0 => Ok(None),
        32 => Ok(Some(Checksum::from_ay(parent)?)),
        _ => Err(Error::InvalidCommit(
            "parent checksum is neither empty nor 32 bytes",
        )),
    }
}

/// The root dirtree checksum of a commit.
fn parse_root_dirtree(root_dirtree: &[u8]) -> Result<Checksum> {
    Checksum::from_ay(root_dirtree)
        .map_err(|_| Error::InvalidCommit("root dirtree checksum is not 32 bytes"))
}

/// The root dirmeta checksum of a commit.
fn parse_root_dirmeta(root_dirmeta: &[u8]) -> Result<Checksum> {
    Checksum::from_ay(root_dirmeta)
        .map_err(|_| Error::InvalidCommit("root dirmeta checksum is not 32 bytes"))
}

/// A pre-serialized `a{sv}` spliced in as the first tuple member.
struct RawDict<'a>(&'a [u8]);

impl GvType for RawDict<'_> {
    const ALIGNMENT: usize = 8;
    const FIXED_SIZE: Option<usize> = None;
}

impl GvEncode for RawDict<'_> {
    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
        out.extend_from_slice(self.0);
        Ok(())
    }
}

impl GvType for Commit {
    const SIGNATURE: &'static str = "(a{sv}aya(say)sstayay)";
    // Greatest member alignment: the metadata dict and the timestamp.
    const ALIGNMENT: usize = 8;
    const FIXED_SIZE: Option<usize> = None;
}

impl GvEncode for Commit {
    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
        let metadata = to_bytes(&METADATA_TYPE, &self.metadata)?;
        self.encode_with(&metadata, out)
    }
}

impl Commit {
    /// Writes the commit tuple with the serialized metadata dict `metadata`.
    fn encode_with(&self, metadata: &[u8], out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
        let parent: &[u8] = match &self.parent {
            Some(checksum) => checksum.as_bytes(),
            None => &[],
        };
        let related: Vec<(&str, &[u8])> = self
            .related
            .iter()
            .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
            .collect();
        (
            RawDict(metadata),
            parent,
            Slice(&related),
            self.subject.as_str(),
            self.body.as_str(),
            Be64(self.timestamp),
            self.root_dirtree,
            self.root_dirmeta,
        )
            .encode(out)
    }
}

/// The metadata key that holds the ref names a commit is bound to.
const REF_BINDING_KEY: &str = "ostree.ref-binding";
/// The metadata key that holds the collection id a commit is bound to.
const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";

/// Returns the `ostree.ref-binding` value for `refs`.
///
/// The value is a variant of type `as`. It holds the names sorted byte-wise
/// in ascending order, with duplicates kept. An empty list gives the empty
/// array, which is the value of a commit bound to no ref.
pub fn ref_binding(refs: &[&str]) -> Value {
    let mut names = refs.to_vec();
    names.sort_unstable();
    Value::variant(
        Type::parse("as").expect("\"as\" is a valid gvariant type"),
        Value::Array(
            names
                .into_iter()
                .map(|name| Value::Str(name.to_owned()))
                .collect(),
        ),
    )
}

/// Returns the `a{sv}` metadata dict of a new commit.
///
/// The entry order is part of the commit checksum. The dict holds these
/// entries, in this order:
///
/// 1. `entries`, in the order given, with duplicate keys kept
/// 2. `ostree.ref-binding` with the [`ref_binding`] value for `refs`, if
///    `refs` is set
/// 3. `ostree.collection-binding` with `collection_id`, if `collection_id` is
///    set
///
/// If `refs` is `None`, the dict holds neither binding key, and the function
/// ignores `collection_id`. Each value in `entries` must be a
/// [`Value::Variant`], or [`Commit::serialize`] returns an error.
pub fn commit_metadata(
    entries: impl IntoIterator<Item = (String, Value)>,
    refs: Option<&[&str]>,
    collection_id: Option<&str>,
) -> Value {
    let mut dict: Vec<Value> = entries
        .into_iter()
        .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
        .collect();
    if let Some(refs) = refs {
        dict.push(Value::Tuple(vec![
            Value::Str(REF_BINDING_KEY.to_owned()),
            ref_binding(refs),
        ]));
        if let Some(collection) = collection_id {
            dict.push(Value::Tuple(vec![
                Value::Str(COLLECTION_BINDING_KEY.to_owned()),
                Value::variant(Type::Str, Value::Str(collection.to_owned())),
            ]));
        }
    }
    Value::Array(dict)
}

/// An error of [`commit_timestamp`] and of [`source_date_epoch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimestampError {
    /// A `SOURCE_DATE_EPOCH` value that is not a count of seconds.
    ///
    /// The variant holds the value as read, before the trim.
    SourceDateEpoch(String),
    /// The system clock is before the Unix epoch.
    ClockBeforeEpoch,
}

impl std::fmt::Display for TimestampError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TimestampError::SourceDateEpoch(raw) => {
                write!(f, "SOURCE_DATE_EPOCH is not a Unix timestamp: {raw:?}")
            }
            TimestampError::ClockBeforeEpoch => {
                f.write_str("the system clock is before the Unix epoch")
            }
        }
    }
}

impl std::error::Error for TimestampError {}

/// Returns the timestamp of a new commit.
///
/// The timestamp is in seconds since the Unix epoch, UTC. The function takes
/// it from the first of these sources that is set:
///
/// 1. `explicit`
/// 2. the `SOURCE_DATE_EPOCH` environment variable
/// 3. the system clock
///
/// The function trims white space from `SOURCE_DATE_EPOCH` before it parses
/// the value. If `SOURCE_DATE_EPOCH` is not valid Unicode, the function
/// treats it as unset.
///
/// # Errors
///
/// - [`TimestampError::SourceDateEpoch`] if `explicit` is `None` and
///   `SOURCE_DATE_EPOCH` is set to a value that is not a count of seconds.
///   The function does not use the clock in this case, as the
///   reproducible-build convention requires.
/// - [`TimestampError::ClockBeforeEpoch`] if the function reads the system
///   clock and the clock is before the Unix epoch.
pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
    timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
}

/// Returns the value of the `SOURCE_DATE_EPOCH` environment variable, in
/// seconds since the Unix epoch.
///
/// The function reads the variable with the rule of [`commit_timestamp`]: it
/// trims white space before it parses the value, and it treats a value that
/// is not valid Unicode as unset. If the variable is unset, the result is
/// `None`.
///
/// # Errors
///
/// [`TimestampError::SourceDateEpoch`] if the variable is set to a value
/// that is not a count of seconds.
pub fn source_date_epoch() -> std::result::Result<Option<u64>, TimestampError> {
    parse_source_date_epoch(std::env::var("SOURCE_DATE_EPOCH").ok())
}

/// [`source_date_epoch`] over a given `SOURCE_DATE_EPOCH` value.
fn parse_source_date_epoch(
    raw: Option<String>,
) -> std::result::Result<Option<u64>, TimestampError> {
    raw.map(|raw| {
        raw.trim()
            .parse::<u64>()
            .map_err(|_| TimestampError::SourceDateEpoch(raw))
    })
    .transpose()
}

/// [`commit_timestamp`] over a given `SOURCE_DATE_EPOCH` value.
fn timestamp_from(
    explicit: Option<u64>,
    source_date_epoch: Option<String>,
) -> std::result::Result<u64, TimestampError> {
    if let Some(timestamp) = explicit {
        return Ok(timestamp);
    }
    if let Some(timestamp) = parse_source_date_epoch(source_date_epoch)? {
        return Ok(timestamp);
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| TimestampError::ClockBeforeEpoch)?;
    Ok(now.as_secs())
}

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

    fn csum(byte: u8) -> Checksum {
        Checksum::from_bytes([byte; 32])
    }

    fn sample() -> Commit {
        Commit {
            metadata: Value::Array(vec![Value::Tuple(vec![
                Value::Str("version".to_owned()),
                Value::variant(Type::Str, Value::Str("42".to_owned())),
            ])]),
            parent: Some(csum(0xaa)),
            related: Vec::new(),
            subject: "subject".to_owned(),
            body: "body".to_owned(),
            timestamp: 1_700_000_000,
            root_dirtree: csum(1),
            root_dirmeta: csum(2),
        }
    }

    /// The entries are the key and the `v` of each entry of the dict, in
    /// order, with duplicate keys kept. The rest is the parsed commit.
    #[test]
    fn metadata_entries_are_the_variants_of_the_dict() {
        let entry = |key: &str, value: Value| Value::Tuple(vec![Value::Str(key.into()), value]);
        let values = [
            ("z", Value::variant(Type::Str, Value::Str("1".into()))),
            ("a", Value::variant(Type::U32, Value::U32(7))),
            (
                "z",
                Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![1, 2, 3])),
            ),
        ];
        let commit = Commit {
            metadata: Value::Array(values.iter().map(|(k, v)| entry(k, v.clone())).collect()),
            ..sample()
        };
        let bytes = commit.serialize().unwrap();
        let (bare, entries) = Commit::parse_with_metadata_entries(&bytes).unwrap();
        assert_eq!(
            bare,
            Commit {
                metadata: Value::Array(Vec::new()),
                ..commit
            }
        );
        assert_eq!(entries.len(), values.len());
        for ((key, raw), (want_key, want)) in entries.iter().zip(&values) {
            assert_eq!(key, want_key);
            assert_eq!(&from_bytes(&Type::Variant, raw).unwrap(), want);
        }

        // A dict that `Commit::parse` refuses is refused.
        let mut bad = bytes.clone();
        bad[0] ^= 0xff;
        assert!(Commit::parse(&bad).is_err());
        assert!(Commit::parse_with_metadata_entries(&bad).is_err());
    }

    #[test]
    fn round_trips_with_parent_and_metadata() {
        let commit = sample();
        let bytes = commit.serialize().unwrap();
        let parsed = Commit::parse(&bytes).unwrap();
        assert_eq!(parsed, commit);
        assert_eq!(parsed.serialize().unwrap(), bytes);
        assert_eq!(parsed.version(), Some("42"));
        assert!(parsed.ref_bindings().is_empty());
        assert_eq!(parsed.collection_binding(), None);
    }

    /// The bytes of the metadata dict in place of the dict give the bytes of
    /// `serialize`, and the call does not read the field.
    #[test]
    fn serialize_with_metadata_splices_the_dict_bytes() {
        let commit = sample();
        let dict = to_bytes(&METADATA_TYPE, &commit.metadata).unwrap();
        let other = Commit {
            metadata: Value::Array(Vec::new()),
            ..sample()
        };
        assert_eq!(
            other.serialize_with_metadata(&dict).unwrap(),
            commit.serialize().unwrap()
        );
    }

    #[test]
    fn empty_parent_ay_means_a_root_commit() {
        let commit = Commit {
            parent: None,
            ..sample()
        };
        let parsed = Commit::parse(&commit.serialize().unwrap()).unwrap();
        assert_eq!(parsed.parent, None);
    }

    /// Serializes a commit through the `Value` tree with any width of the
    /// parent and the root dirtree checksums. The `Commit` struct cannot hold
    /// such widths.
    fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
        craft_with(parent, root_dirtree, &[2; 32])
    }

    /// [`craft`] with any width of the root dirmeta checksum.
    fn craft_with(parent: &[u8], root_dirtree: &[u8], root_dirmeta: &[u8]) -> Vec<u8> {
        let ty = Type::parse(<Commit as GvType>::SIGNATURE).unwrap();
        let value = Value::Tuple(vec![
            Value::Array(Vec::new()),
            Value::Bytes(parent.to_vec()),
            Value::Array(Vec::new()),
            Value::Str(String::new()),
            Value::Str(String::new()),
            Value::U64(0),
            Value::Bytes(root_dirtree.to_vec()),
            Value::Bytes(root_dirmeta.to_vec()),
        ]);
        to_bytes(&ty, &value).unwrap()
    }

    #[test]
    fn parse_rejects_malformed_checksum_widths() {
        assert_eq!(
            Commit::parse(&craft(&[0xaa; 31], &[1; 32])),
            Err(Error::InvalidCommit(
                "parent checksum is neither empty nor 32 bytes"
            ))
        );
        assert_eq!(
            Commit::parse(&craft(&[], &[1; 31])),
            Err(Error::InvalidCommit(
                "root dirtree checksum is not 32 bytes"
            ))
        );
    }

    #[test]
    fn parse_link_agrees_with_parse() {
        let root = Commit {
            parent: None,
            ..sample()
        };
        for commit in [sample(), root] {
            let bytes = commit.serialize().unwrap();
            let parsed = Commit::parse(&bytes).unwrap();
            assert_eq!(
                Commit::parse_link(&bytes).unwrap(),
                CommitLink {
                    parent: parsed.parent,
                    root_dirtree: parsed.root_dirtree,
                    root_dirmeta: parsed.root_dirmeta,
                }
            );
        }
    }

    #[test]
    fn parse_link_refuses_what_parse_refuses_in_its_fields() {
        let whole = sample().serialize().unwrap();
        for bytes in [
            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
            craft_with(&[], &[1; 31], &[2; 32]),
            craft_with(&[], &[1; 32], &[2; 33]),
            craft_with(&[], &[1; 32], &[]),
            whole[..whole.len() - 1].to_vec(),
            Vec::new(),
        ] {
            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
            assert_eq!(Commit::parse_link(&bytes), Err(refused));
        }
    }

    #[test]
    fn parse_timestamp_agrees_with_parse() {
        let root = Commit {
            parent: None,
            ..sample()
        };
        let wide = Commit {
            timestamp: 0x0102_0304_0506_0708,
            ..sample()
        };
        for commit in [sample(), root, wide] {
            let bytes = commit.serialize().unwrap();
            assert_eq!(
                Commit::parse_timestamp(&bytes).unwrap(),
                Commit::parse(&bytes).unwrap().timestamp
            );
        }
    }

    #[test]
    fn parse_timestamp_refuses_what_parse_refuses_in_its_fields() {
        let whole = sample().serialize().unwrap();
        for bytes in [
            craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
            craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
            craft_with(&[], &[1; 31], &[2; 32]),
            craft_with(&[], &[1; 32], &[2; 33]),
            craft_with(&[], &[1; 32], &[]),
            whole[..whole.len() - 1].to_vec(),
            Vec::new(),
        ] {
            let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
            assert_eq!(Commit::parse_timestamp(&bytes), Err(refused));
        }
    }

    #[test]
    fn content_checksum_hashes_the_two_root_checksums() {
        let commit = sample();
        let mut buf = Vec::new();
        buf.extend_from_slice(csum(1).as_bytes());
        buf.extend_from_slice(csum(2).as_bytes());
        assert_eq!(commit.content_checksum(), Checksum::sha256(&buf));
    }

    fn entry(key: &str, value: &str) -> (String, Value) {
        (
            key.to_owned(),
            Value::variant(Type::Str, Value::Str(value.to_owned())),
        )
    }

    fn text(value: &Value) -> String {
        ostrya_gvariant::to_text(&METADATA_TYPE, value).unwrap()
    }

    #[test]
    fn commit_metadata_orders_entries_then_bindings() {
        let dict = commit_metadata(
            [entry("b", "1"), entry("a", "2"), entry("b", "3")],
            Some(&["zeta", "alpha", "mid", "alpha"]),
            Some("org.example.C"),
        );
        assert_eq!(
            text(&dict),
            "{'b': <'1'>, 'a': <'2'>, 'b': <'3'>, \
             'ostree.ref-binding': <['alpha', 'alpha', 'mid', 'zeta']>, \
             'ostree.collection-binding': <'org.example.C'>}"
        );
    }

    #[test]
    fn commit_metadata_without_refs_holds_no_binding_key() {
        let dict = commit_metadata([entry("k", "v")], None, Some("org.example.C"));
        assert_eq!(text(&dict), "{'k': <'v'>}");
        assert_eq!(commit_metadata([], None, None), Value::Array(Vec::new()));
    }

    #[test]
    fn empty_ref_list_writes_the_empty_array() {
        let dict = commit_metadata([], Some(&[]), None);
        assert_eq!(text(&dict), "{'ostree.ref-binding': <@as []>}");
        assert_eq!(
            dict,
            Value::Array(vec![Value::Tuple(vec![
                Value::Str("ostree.ref-binding".to_owned()),
                ref_binding(&[]),
            ])])
        );
    }

    #[test]
    fn timestamp_prefers_explicit_then_source_date_epoch() {
        assert_eq!(timestamp_from(Some(5), Some("abc".to_owned())), Ok(5));
        assert_eq!(
            timestamp_from(None, Some(" 1700000000\n".to_owned())),
            Ok(1_700_000_000)
        );
        let err = timestamp_from(None, Some("abc".to_owned())).unwrap_err();
        assert_eq!(err, TimestampError::SourceDateEpoch("abc".to_owned()));
        assert_eq!(
            err.to_string(),
            "SOURCE_DATE_EPOCH is not a Unix timestamp: \"abc\""
        );
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let got = timestamp_from(None, None).unwrap();
        assert!(got.abs_diff(now) <= 5, "{got} is near {now}");
    }

    #[test]
    fn source_date_epoch_is_trimmed_and_unset_is_none() {
        assert_eq!(parse_source_date_epoch(None), Ok(None));
        assert_eq!(
            parse_source_date_epoch(Some(" 1700000000\n".to_owned())),
            Ok(Some(1_700_000_000))
        );
        for raw in ["", "abc", "-1", "@1"] {
            assert_eq!(
                parse_source_date_epoch(Some(raw.to_owned())),
                Err(TimestampError::SourceDateEpoch(raw.to_owned())),
                "{raw:?}"
            );
        }
    }
}