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>)>,
58 pub subject: String,
60 pub body: String,
62 pub timestamp: u64,
64 pub root_dirtree: Checksum,
66 pub root_dirmeta: Checksum,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct CommitLink {
73 pub parent: Option<Checksum>,
75 pub root_dirtree: Checksum,
77 pub root_dirmeta: Checksum,
79}
80
81type 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 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 #[allow(clippy::type_complexity)]
144 pub fn parse_with_metadata_entries(data: &[u8]) -> Result<(Commit, Vec<(String, Vec<u8>)>)> {
145 let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
146 ostrya_gvariant::validate(&METADATA_TYPE, metadata)?;
147 let entries = ArrayIter::<(&str, VariantBytes)>::decode(metadata)?
148 .map(|entry| {
149 let (key, value) = entry?;
150 let mut bytes = Vec::new();
151 value.encode(&mut bytes)?;
152 Ok((key.to_owned(), bytes))
153 })
154 .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
155 let parent = parse_parent(parent)?;
156 let related = related
157 .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
158 .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
159 let commit = Commit {
160 metadata: Value::Array(Vec::new()),
161 parent,
162 related,
163 subject: subject.to_owned(),
164 body: body.to_owned(),
165 timestamp: timestamp.0,
166 root_dirtree: parse_root_dirtree(root_dirtree)?,
167 root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
168 };
169 Ok((commit, entries))
170 }
171
172 pub fn parse_link(data: &[u8]) -> Result<CommitLink> {
188 let (_, parent, _, _, _, _, root_dirtree, root_dirmeta): CommitView =
189 GvDecode::decode(data)?;
190 Ok(CommitLink {
191 parent: parse_parent(parent)?,
192 root_dirtree: parse_root_dirtree(root_dirtree)?,
193 root_dirmeta: parse_root_dirmeta(root_dirmeta)?,
194 })
195 }
196
197 pub fn parse_timestamp(data: &[u8]) -> Result<u64> {
208 let (_, parent, _, _, _, timestamp, root_dirtree, root_dirmeta): CommitView =
209 GvDecode::decode(data)?;
210 parse_parent(parent)?;
211 parse_root_dirtree(root_dirtree)?;
212 parse_root_dirmeta(root_dirmeta)?;
213 Ok(timestamp.0)
214 }
215
216 pub fn serialize(&self) -> Result<Vec<u8>> {
235 Ok(ostrya_gvariant::encode_to_vec(self)?)
236 }
237
238 pub fn serialize_with_metadata(&self, metadata: &[u8]) -> Result<Vec<u8>> {
256 let mut out = Vec::new();
257 self.encode_with(metadata, &mut out)?;
258 Ok(out)
259 }
260
261 pub fn checksum(&self) -> Result<Checksum> {
267 Ok(Checksum::sha256(&self.serialize()?))
268 }
269
270 pub fn content_checksum(&self) -> Checksum {
276 let mut buf = [0u8; 64];
277 buf[..32].copy_from_slice(self.root_dirtree.as_bytes());
278 buf[32..].copy_from_slice(self.root_dirmeta.as_bytes());
279 Checksum::sha256(&buf)
280 }
281
282 pub fn metadata_value(&self, key: &str) -> Option<&Value> {
287 self.metadata
288 .dict_get(key)?
289 .as_variant()
290 .map(|(_, value)| value)
291 }
292
293 pub fn version(&self) -> Option<&str> {
299 self.metadata_value("version")?.as_str()
300 }
301
302 pub fn ref_bindings(&self) -> Vec<&str> {
307 self.metadata_value("ostree.ref-binding")
308 .and_then(Value::as_array)
309 .map(|refs| refs.iter().filter_map(Value::as_str).collect())
310 .unwrap_or_default()
311 }
312
313 pub fn collection_binding(&self) -> Option<&str> {
318 self.metadata_value("ostree.collection-binding")?.as_str()
319 }
320}
321
322fn parse_parent(parent: &[u8]) -> Result<Option<Checksum>> {
324 match parent.len() {
325 0 => Ok(None),
326 32 => Ok(Some(Checksum::from_ay(parent)?)),
327 _ => Err(Error::InvalidCommit(
328 "parent checksum is neither empty nor 32 bytes",
329 )),
330 }
331}
332
333fn parse_root_dirtree(root_dirtree: &[u8]) -> Result<Checksum> {
335 Checksum::from_ay(root_dirtree)
336 .map_err(|_| Error::InvalidCommit("root dirtree checksum is not 32 bytes"))
337}
338
339fn parse_root_dirmeta(root_dirmeta: &[u8]) -> Result<Checksum> {
341 Checksum::from_ay(root_dirmeta)
342 .map_err(|_| Error::InvalidCommit("root dirmeta checksum is not 32 bytes"))
343}
344
345struct RawDict<'a>(&'a [u8]);
347
348impl GvType for RawDict<'_> {
349 const ALIGNMENT: usize = 8;
350 const FIXED_SIZE: Option<usize> = None;
351}
352
353impl GvEncode for RawDict<'_> {
354 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
355 out.extend_from_slice(self.0);
356 Ok(())
357 }
358}
359
360impl GvType for Commit {
361 const SIGNATURE: &'static str = "(a{sv}aya(say)sstayay)";
362 const ALIGNMENT: usize = 8;
364 const FIXED_SIZE: Option<usize> = None;
365}
366
367impl GvEncode for Commit {
368 fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
369 let metadata = to_bytes(&METADATA_TYPE, &self.metadata)?;
370 self.encode_with(&metadata, out)
371 }
372}
373
374impl Commit {
375 fn encode_with(&self, metadata: &[u8], out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
377 let parent: &[u8] = match &self.parent {
378 Some(checksum) => checksum.as_bytes(),
379 None => &[],
380 };
381 let related: Vec<(&str, &[u8])> = self
382 .related
383 .iter()
384 .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
385 .collect();
386 (
387 RawDict(metadata),
388 parent,
389 Slice(&related),
390 self.subject.as_str(),
391 self.body.as_str(),
392 Be64(self.timestamp),
393 self.root_dirtree,
394 self.root_dirmeta,
395 )
396 .encode(out)
397 }
398}
399
400const REF_BINDING_KEY: &str = "ostree.ref-binding";
402const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
404
405pub fn ref_binding(refs: &[&str]) -> Value {
411 let mut names = refs.to_vec();
412 names.sort_unstable();
413 Value::variant(
414 Type::parse("as").expect("\"as\" is a valid gvariant type"),
415 Value::Array(
416 names
417 .into_iter()
418 .map(|name| Value::Str(name.to_owned()))
419 .collect(),
420 ),
421 )
422}
423
424pub fn commit_metadata(
439 entries: impl IntoIterator<Item = (String, Value)>,
440 refs: Option<&[&str]>,
441 collection_id: Option<&str>,
442) -> Value {
443 let mut dict: Vec<Value> = entries
444 .into_iter()
445 .map(|(key, value)| Value::Tuple(vec![Value::Str(key), value]))
446 .collect();
447 if let Some(refs) = refs {
448 dict.push(Value::Tuple(vec![
449 Value::Str(REF_BINDING_KEY.to_owned()),
450 ref_binding(refs),
451 ]));
452 if let Some(collection) = collection_id {
453 dict.push(Value::Tuple(vec![
454 Value::Str(COLLECTION_BINDING_KEY.to_owned()),
455 Value::variant(Type::Str, Value::Str(collection.to_owned())),
456 ]));
457 }
458 }
459 Value::Array(dict)
460}
461
462#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum TimestampError {
465 SourceDateEpoch(String),
469 ClockBeforeEpoch,
471}
472
473impl std::fmt::Display for TimestampError {
474 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475 match self {
476 TimestampError::SourceDateEpoch(raw) => {
477 write!(f, "SOURCE_DATE_EPOCH is not a Unix timestamp: {raw:?}")
478 }
479 TimestampError::ClockBeforeEpoch => {
480 f.write_str("the system clock is before the Unix epoch")
481 }
482 }
483 }
484}
485
486impl std::error::Error for TimestampError {}
487
488pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
510 timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
511}
512
513pub fn source_date_epoch() -> std::result::Result<Option<u64>, TimestampError> {
526 parse_source_date_epoch(std::env::var("SOURCE_DATE_EPOCH").ok())
527}
528
529fn parse_source_date_epoch(
531 raw: Option<String>,
532) -> std::result::Result<Option<u64>, TimestampError> {
533 raw.map(|raw| {
534 raw.trim()
535 .parse::<u64>()
536 .map_err(|_| TimestampError::SourceDateEpoch(raw))
537 })
538 .transpose()
539}
540
541fn timestamp_from(
543 explicit: Option<u64>,
544 source_date_epoch: Option<String>,
545) -> std::result::Result<u64, TimestampError> {
546 if let Some(timestamp) = explicit {
547 return Ok(timestamp);
548 }
549 if let Some(timestamp) = parse_source_date_epoch(source_date_epoch)? {
550 return Ok(timestamp);
551 }
552 let now = std::time::SystemTime::now()
553 .duration_since(std::time::UNIX_EPOCH)
554 .map_err(|_| TimestampError::ClockBeforeEpoch)?;
555 Ok(now.as_secs())
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 fn csum(byte: u8) -> Checksum {
563 Checksum::from_bytes([byte; 32])
564 }
565
566 fn sample() -> Commit {
567 Commit {
568 metadata: Value::Array(vec![Value::Tuple(vec![
569 Value::Str("version".to_owned()),
570 Value::variant(Type::Str, Value::Str("42".to_owned())),
571 ])]),
572 parent: Some(csum(0xaa)),
573 related: Vec::new(),
574 subject: "subject".to_owned(),
575 body: "body".to_owned(),
576 timestamp: 1_700_000_000,
577 root_dirtree: csum(1),
578 root_dirmeta: csum(2),
579 }
580 }
581
582 #[test]
585 fn metadata_entries_are_the_variants_of_the_dict() {
586 let entry = |key: &str, value: Value| Value::Tuple(vec![Value::Str(key.into()), value]);
587 let values = [
588 ("z", Value::variant(Type::Str, Value::Str("1".into()))),
589 ("a", Value::variant(Type::U32, Value::U32(7))),
590 (
591 "z",
592 Value::variant(Type::parse("ay").unwrap(), Value::Bytes(vec![1, 2, 3])),
593 ),
594 ];
595 let commit = Commit {
596 metadata: Value::Array(values.iter().map(|(k, v)| entry(k, v.clone())).collect()),
597 ..sample()
598 };
599 let bytes = commit.serialize().unwrap();
600 let (bare, entries) = Commit::parse_with_metadata_entries(&bytes).unwrap();
601 assert_eq!(
602 bare,
603 Commit {
604 metadata: Value::Array(Vec::new()),
605 ..commit
606 }
607 );
608 assert_eq!(entries.len(), values.len());
609 for ((key, raw), (want_key, want)) in entries.iter().zip(&values) {
610 assert_eq!(key, want_key);
611 assert_eq!(&from_bytes(&Type::Variant, raw).unwrap(), want);
612 }
613
614 let mut bad = bytes.clone();
616 bad[0] ^= 0xff;
617 assert!(Commit::parse(&bad).is_err());
618 assert!(Commit::parse_with_metadata_entries(&bad).is_err());
619 }
620
621 #[test]
622 fn round_trips_with_parent_and_metadata() {
623 let commit = sample();
624 let bytes = commit.serialize().unwrap();
625 let parsed = Commit::parse(&bytes).unwrap();
626 assert_eq!(parsed, commit);
627 assert_eq!(parsed.serialize().unwrap(), bytes);
628 assert_eq!(parsed.version(), Some("42"));
629 assert!(parsed.ref_bindings().is_empty());
630 assert_eq!(parsed.collection_binding(), None);
631 }
632
633 #[test]
636 fn serialize_with_metadata_splices_the_dict_bytes() {
637 let commit = sample();
638 let dict = to_bytes(&METADATA_TYPE, &commit.metadata).unwrap();
639 let other = Commit {
640 metadata: Value::Array(Vec::new()),
641 ..sample()
642 };
643 assert_eq!(
644 other.serialize_with_metadata(&dict).unwrap(),
645 commit.serialize().unwrap()
646 );
647 }
648
649 #[test]
650 fn empty_parent_ay_means_a_root_commit() {
651 let commit = Commit {
652 parent: None,
653 ..sample()
654 };
655 let parsed = Commit::parse(&commit.serialize().unwrap()).unwrap();
656 assert_eq!(parsed.parent, None);
657 }
658
659 fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
663 craft_with(parent, root_dirtree, &[2; 32])
664 }
665
666 fn craft_with(parent: &[u8], root_dirtree: &[u8], root_dirmeta: &[u8]) -> Vec<u8> {
668 let ty = Type::parse(<Commit as GvType>::SIGNATURE).unwrap();
669 let value = Value::Tuple(vec![
670 Value::Array(Vec::new()),
671 Value::Bytes(parent.to_vec()),
672 Value::Array(Vec::new()),
673 Value::Str(String::new()),
674 Value::Str(String::new()),
675 Value::U64(0),
676 Value::Bytes(root_dirtree.to_vec()),
677 Value::Bytes(root_dirmeta.to_vec()),
678 ]);
679 to_bytes(&ty, &value).unwrap()
680 }
681
682 #[test]
683 fn parse_rejects_malformed_checksum_widths() {
684 assert_eq!(
685 Commit::parse(&craft(&[0xaa; 31], &[1; 32])),
686 Err(Error::InvalidCommit(
687 "parent checksum is neither empty nor 32 bytes"
688 ))
689 );
690 assert_eq!(
691 Commit::parse(&craft(&[], &[1; 31])),
692 Err(Error::InvalidCommit(
693 "root dirtree checksum is not 32 bytes"
694 ))
695 );
696 }
697
698 #[test]
699 fn parse_link_agrees_with_parse() {
700 let root = Commit {
701 parent: None,
702 ..sample()
703 };
704 for commit in [sample(), root] {
705 let bytes = commit.serialize().unwrap();
706 let parsed = Commit::parse(&bytes).unwrap();
707 assert_eq!(
708 Commit::parse_link(&bytes).unwrap(),
709 CommitLink {
710 parent: parsed.parent,
711 root_dirtree: parsed.root_dirtree,
712 root_dirmeta: parsed.root_dirmeta,
713 }
714 );
715 }
716 }
717
718 #[test]
719 fn parse_link_refuses_what_parse_refuses_in_its_fields() {
720 let whole = sample().serialize().unwrap();
721 for bytes in [
722 craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
723 craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
724 craft_with(&[], &[1; 31], &[2; 32]),
725 craft_with(&[], &[1; 32], &[2; 33]),
726 craft_with(&[], &[1; 32], &[]),
727 whole[..whole.len() - 1].to_vec(),
728 Vec::new(),
729 ] {
730 let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
731 assert_eq!(Commit::parse_link(&bytes), Err(refused));
732 }
733 }
734
735 #[test]
736 fn parse_timestamp_agrees_with_parse() {
737 let root = Commit {
738 parent: None,
739 ..sample()
740 };
741 let wide = Commit {
742 timestamp: 0x0102_0304_0506_0708,
743 ..sample()
744 };
745 for commit in [sample(), root, wide] {
746 let bytes = commit.serialize().unwrap();
747 assert_eq!(
748 Commit::parse_timestamp(&bytes).unwrap(),
749 Commit::parse(&bytes).unwrap().timestamp
750 );
751 }
752 }
753
754 #[test]
755 fn parse_timestamp_refuses_what_parse_refuses_in_its_fields() {
756 let whole = sample().serialize().unwrap();
757 for bytes in [
758 craft_with(&[0xaa; 31], &[1; 32], &[2; 32]),
759 craft_with(&[0xaa; 33], &[1; 32], &[2; 32]),
760 craft_with(&[], &[1; 31], &[2; 32]),
761 craft_with(&[], &[1; 32], &[2; 33]),
762 craft_with(&[], &[1; 32], &[]),
763 whole[..whole.len() - 1].to_vec(),
764 Vec::new(),
765 ] {
766 let refused = Commit::parse(&bytes).expect_err("the full parse refuses the object");
767 assert_eq!(Commit::parse_timestamp(&bytes), Err(refused));
768 }
769 }
770
771 #[test]
772 fn content_checksum_hashes_the_two_root_checksums() {
773 let commit = sample();
774 let mut buf = Vec::new();
775 buf.extend_from_slice(csum(1).as_bytes());
776 buf.extend_from_slice(csum(2).as_bytes());
777 assert_eq!(commit.content_checksum(), Checksum::sha256(&buf));
778 }
779
780 fn entry(key: &str, value: &str) -> (String, Value) {
781 (
782 key.to_owned(),
783 Value::variant(Type::Str, Value::Str(value.to_owned())),
784 )
785 }
786
787 fn text(value: &Value) -> String {
788 ostrya_gvariant::to_text(&METADATA_TYPE, value).unwrap()
789 }
790
791 #[test]
792 fn commit_metadata_orders_entries_then_bindings() {
793 let dict = commit_metadata(
794 [entry("b", "1"), entry("a", "2"), entry("b", "3")],
795 Some(&["zeta", "alpha", "mid", "alpha"]),
796 Some("org.example.C"),
797 );
798 assert_eq!(
799 text(&dict),
800 "{'b': <'1'>, 'a': <'2'>, 'b': <'3'>, \
801 'ostree.ref-binding': <['alpha', 'alpha', 'mid', 'zeta']>, \
802 'ostree.collection-binding': <'org.example.C'>}"
803 );
804 }
805
806 #[test]
807 fn commit_metadata_without_refs_holds_no_binding_key() {
808 let dict = commit_metadata([entry("k", "v")], None, Some("org.example.C"));
809 assert_eq!(text(&dict), "{'k': <'v'>}");
810 assert_eq!(commit_metadata([], None, None), Value::Array(Vec::new()));
811 }
812
813 #[test]
814 fn empty_ref_list_writes_the_empty_array() {
815 let dict = commit_metadata([], Some(&[]), None);
816 assert_eq!(text(&dict), "{'ostree.ref-binding': <@as []>}");
817 assert_eq!(
818 dict,
819 Value::Array(vec![Value::Tuple(vec![
820 Value::Str("ostree.ref-binding".to_owned()),
821 ref_binding(&[]),
822 ])])
823 );
824 }
825
826 #[test]
827 fn timestamp_prefers_explicit_then_source_date_epoch() {
828 assert_eq!(timestamp_from(Some(5), Some("abc".to_owned())), Ok(5));
829 assert_eq!(
830 timestamp_from(None, Some(" 1700000000\n".to_owned())),
831 Ok(1_700_000_000)
832 );
833 let err = timestamp_from(None, Some("abc".to_owned())).unwrap_err();
834 assert_eq!(err, TimestampError::SourceDateEpoch("abc".to_owned()));
835 assert_eq!(
836 err.to_string(),
837 "SOURCE_DATE_EPOCH is not a Unix timestamp: \"abc\""
838 );
839 let now = std::time::SystemTime::now()
840 .duration_since(std::time::UNIX_EPOCH)
841 .unwrap()
842 .as_secs();
843 let got = timestamp_from(None, None).unwrap();
844 assert!(got.abs_diff(now) <= 5, "{got} is near {now}");
845 }
846
847 #[test]
848 fn source_date_epoch_is_trimmed_and_unset_is_none() {
849 assert_eq!(parse_source_date_epoch(None), Ok(None));
850 assert_eq!(
851 parse_source_date_epoch(Some(" 1700000000\n".to_owned())),
852 Ok(Some(1_700_000_000))
853 );
854 for raw in ["", "abc", "-1", "@1"] {
855 assert_eq!(
856 parse_source_date_epoch(Some(raw.to_owned())),
857 Err(TimestampError::SourceDateEpoch(raw.to_owned())),
858 "{raw:?}"
859 );
860 }
861 }
862}