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};
static METADATA_TYPE: LazyLock<Type> =
LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Commit {
pub metadata: Value,
pub parent: Option<Checksum>,
pub related: Vec<(String, Vec<u8>)>,
pub subject: String,
pub body: String,
pub timestamp: u64,
pub root_dirtree: Checksum,
pub root_dirmeta: Checksum,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommitLink {
pub parent: Option<Checksum>,
pub root_dirtree: Checksum,
pub root_dirmeta: Checksum,
}
type CommitView<'a> = (
&'a [u8],
&'a [u8],
ArrayIter<'a, (&'a str, &'a [u8])>,
&'a str,
&'a str,
Be64,
&'a [u8],
&'a [u8],
);
impl Commit {
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)?,
})
}
#[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))
}
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)?,
})
}
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)
}
pub fn serialize(&self) -> Result<Vec<u8>> {
Ok(ostrya_gvariant::encode_to_vec(self)?)
}
pub fn serialize_with_metadata(&self, metadata: &[u8]) -> Result<Vec<u8>> {
let mut out = Vec::new();
self.encode_with(metadata, &mut out)?;
Ok(out)
}
pub fn checksum(&self) -> Result<Checksum> {
Ok(Checksum::sha256(&self.serialize()?))
}
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)
}
pub fn metadata_value(&self, key: &str) -> Option<&Value> {
self.metadata
.dict_get(key)?
.as_variant()
.map(|(_, value)| value)
}
pub fn version(&self) -> Option<&str> {
self.metadata_value("version")?.as_str()
}
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()
}
pub fn collection_binding(&self) -> Option<&str> {
self.metadata_value("ostree.collection-binding")?.as_str()
}
}
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",
)),
}
}
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"))
}
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"))
}
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)";
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 {
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)
}
}
const REF_BINDING_KEY: &str = "ostree.ref-binding";
const COLLECTION_BINDING_KEY: &str = "ostree.collection-binding";
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(),
),
)
}
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)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimestampError {
SourceDateEpoch(String),
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 {}
pub fn commit_timestamp(explicit: Option<u64>) -> std::result::Result<u64, TimestampError> {
timestamp_from(explicit, std::env::var("SOURCE_DATE_EPOCH").ok())
}
pub fn source_date_epoch() -> std::result::Result<Option<u64>, TimestampError> {
parse_source_date_epoch(std::env::var("SOURCE_DATE_EPOCH").ok())
}
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()
}
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),
}
}
#[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);
}
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);
}
#[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);
}
fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
craft_with(parent, root_dirtree, &[2; 32])
}
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:?}"
);
}
}
}