1use 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
16static METADATA_TYPE: LazyLock<Type> =
19 LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));
20
21#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct Commit {
47 pub metadata: Value,
51 pub parent: Option<Checksum>,
53 pub related: Vec<(String, Vec<u8>)>,
60 pub subject: String,
62 pub body: String,
64 pub timestamp: u64,
66 pub root_dirtree: Checksum,
68 pub root_dirmeta: Checksum,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct CommitLink {
75 pub parent: Option<Checksum>,
77 pub root_dirtree: Checksum,
79 pub root_dirmeta: Checksum,
81}
82
83type 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 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 #[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 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 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 pub fn serialize(&self) -> Result<Vec<u8>> {
237 Ok(ostrya_gvariant::encode_to_vec(self)?)
238 }
239
240 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 pub fn checksum(&self) -> Result<Checksum> {
269 Ok(Checksum::sha256(&self.serialize()?))
270 }
271
272 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 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 pub fn version(&self) -> Option<&str> {
301 self.metadata_value("version")?.as_str()
302 }
303
304 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 pub fn collection_binding(&self) -> Option<&str> {
320 self.metadata_value("ostree.collection-binding")?.as_str()
321 }
322}
323
324fn 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
335fn 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
341fn 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
347struct 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 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 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
402const REF_BINDING_KEY: &str = "ostree.ref-binding";
404const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
406
407pub 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
426pub 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#[derive(Debug, Clone, PartialEq, Eq)]
466pub enum TimestampError {
467 SourceDateEpoch(String),
471 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
490pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
512 timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
513}
514
515pub fn source_date_epoch() -> std::result::Result<Option<u64>, TimestampError> {
528 parse_source_date_epoch(std::env::var("SOURCE_DATE_EPOCH").ok())
529}
530
531fn 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
543fn 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 #[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 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 #[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 fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
665 craft_with(parent, root_dirtree, &[2; 32])
666 }
667
668 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}