1use 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
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 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 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 pub fn serialize(&self) -> Result<Vec<u8>> {
194 Ok(ostrya_gvariant::encode_to_vec(self)?)
195 }
196
197 pub fn checksum(&self) -> Result<Checksum> {
203 Ok(Checksum::sha256(&self.serialize()?))
204 }
205
206 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 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 pub fn version(&self) -> Option<&str> {
235 self.metadata_value("version")?.as_str()
236 }
237
238 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 pub fn collection_binding(&self) -> Option<&str> {
254 self.metadata_value("ostree.collection-binding")?.as_str()
255 }
256}
257
258fn 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
269fn 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
275fn 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
281struct 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 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
329const REF_BINDING_KEY: &str = "ostree.ref-binding";
331const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
333
334pub 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
353pub 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#[derive(Debug, Clone, PartialEq, Eq)]
393pub enum TimestampError {
394 SourceDateEpoch(String),
398 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
417pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
439 timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
440}
441
442fn 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 fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
512 craft_with(parent, root_dirtree, &[2; 32])
513 }
514
515 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}