Skip to main content

ostrya_core/
commit.rs

1//! Commit objects.
2//!
3//! Wire form `(a{sv}aya(say)sstayay)`: the metadata dict, the parent commit
4//! checksum (an empty `ay` for a root commit), the related-objects array
5//! (written empty, retained verbatim on parse), subject, body, the big-endian
6//! timestamp, and the root dirtree and dirmeta checksums.
7//!
8//! Commits are read a handful at a time and their fields are retained, so
9//! there is no borrowed view type: [`Commit::parse`] produces the owned
10//! struct. The dynamic `a{sv}` metadata is held as a [`Value`] tree, which
11//! round-trips byte-identically because both codec paths emit normal form.
12
13use std::sync::LazyLock;
14
15use ostrya_gvariant::{
16    ArrayIter, GvDecode, GvEncode, GvType, Slice, Type, Value, from_bytes, to_bytes,
17};
18
19use crate::be::Be64;
20use crate::checksum::Checksum;
21use crate::error::{Error, Result};
22
23/// The `a{sv}` metadata dict type, parsed once and shared. `Type` is
24/// `Send + Sync`, so the same value serves every parse and serialize call.
25static METADATA_TYPE: LazyLock<Type> =
26    LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));
27
28/// An owned commit object. The timestamp is host-order seconds since the
29/// Unix epoch, UTC.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Commit {
32    /// The `a{sv}` metadata dict as a [`Value`] tree (an array of two-element
33    /// tuples, in on-disk order).
34    pub metadata: Value,
35    /// Parent commit, `None` for a root commit (an empty `ay` on the wire).
36    pub parent: Option<Checksum>,
37    /// Related objects: written as an empty array by the tool; parsed
38    /// entries are retained verbatim for byte-exact reserialization.
39    pub related: Vec<(String, Vec<u8>)>,
40    /// The commit subject, the first line of its message.
41    pub subject: String,
42    /// The commit body, the rest of its message.
43    pub body: String,
44    /// The commit time, in seconds since the Unix epoch, UTC.
45    pub timestamp: u64,
46    /// The checksum of the root directory's dirtree object.
47    pub root_dirtree: Checksum,
48    /// The checksum of the root directory's dirmeta object.
49    pub root_dirmeta: Checksum,
50}
51
52/// The commit shape with the metadata and checksum fields as raw slices; the
53/// value-level conventions are applied on top of this view.
54type CommitView<'a> = (
55    &'a [u8],
56    &'a [u8],
57    ArrayIter<'a, (&'a str, &'a [u8])>,
58    &'a str,
59    &'a str,
60    Be64,
61    &'a [u8],
62    &'a [u8],
63);
64
65impl Commit {
66    /// Parse a serialized commit object.
67    pub fn parse(data: &[u8]) -> Result<Commit> {
68        let (metadata, parent, related, subject, body, timestamp, root_dirtree, root_dirmeta): CommitView = GvDecode::decode(data)?;
69        let metadata = from_bytes(&METADATA_TYPE, metadata)?;
70        let parent = match parent.len() {
71            0 => None,
72            32 => Some(Checksum::from_ay(parent)?),
73            _ => {
74                return Err(Error::InvalidCommit(
75                    "parent checksum is neither empty nor 32 bytes",
76                ));
77            }
78        };
79        let related = related
80            .map(|item| item.map(|(name, bytes)| (name.to_owned(), bytes.to_vec())))
81            .collect::<ostrya_gvariant::Result<Vec<_>>>()?;
82        Ok(Commit {
83            metadata,
84            parent,
85            related,
86            subject: subject.to_owned(),
87            body: body.to_owned(),
88            timestamp: timestamp.0,
89            root_dirtree: Checksum::from_ay(root_dirtree)
90                .map_err(|_| Error::InvalidCommit("root dirtree checksum is not 32 bytes"))?,
91            root_dirmeta: Checksum::from_ay(root_dirmeta)
92                .map_err(|_| Error::InvalidCommit("root dirmeta checksum is not 32 bytes"))?,
93        })
94    }
95
96    /// Serialize to normal-form bytes; their SHA-256 is the commit checksum.
97    pub fn serialize(&self) -> Result<Vec<u8>> {
98        Ok(ostrya_gvariant::encode_to_vec(self)?)
99    }
100
101    /// The commit checksum: SHA-256 of the serialized bytes.
102    pub fn checksum(&self) -> Result<Checksum> {
103        Ok(Checksum::sha256(&self.serialize()?))
104    }
105
106    /// The commit content checksum: SHA-256 over the binary root dirtree and
107    /// dirmeta checksums, a content identity independent of commit metadata
108    /// and timestamp.
109    pub fn content_checksum(&self) -> Checksum {
110        let mut buf = [0u8; 64];
111        buf[..32].copy_from_slice(self.root_dirtree.as_bytes());
112        buf[32..].copy_from_slice(self.root_dirmeta.as_bytes());
113        Checksum::sha256(&buf)
114    }
115
116    /// The variant value stored under `key` in the metadata dict.
117    pub fn metadata_value(&self, key: &str) -> Option<&Value> {
118        self.metadata
119            .dict_get(key)?
120            .as_variant()
121            .map(|(_, value)| value)
122    }
123
124    /// The `version` metadata key (the only well-known key without the
125    /// `ostree.` prefix).
126    pub fn version(&self) -> Option<&str> {
127        self.metadata_value("version")?.as_str()
128    }
129
130    /// The refs named by `ostree.ref-binding`, empty when unbound.
131    pub fn ref_bindings(&self) -> Vec<&str> {
132        self.metadata_value("ostree.ref-binding")
133            .and_then(Value::as_array)
134            .map(|refs| refs.iter().filter_map(Value::as_str).collect())
135            .unwrap_or_default()
136    }
137
138    /// The `ostree.collection-binding` metadata key.
139    pub fn collection_binding(&self) -> Option<&str> {
140        self.metadata_value("ostree.collection-binding")?.as_str()
141    }
142}
143
144/// A pre-serialized `a{sv}` spliced in as the first tuple member.
145struct RawDict<'a>(&'a [u8]);
146
147impl GvType for RawDict<'_> {
148    const ALIGNMENT: usize = 8;
149    const FIXED_SIZE: Option<usize> = None;
150}
151
152impl GvEncode for RawDict<'_> {
153    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
154        out.extend_from_slice(self.0);
155        Ok(())
156    }
157}
158
159impl GvType for Commit {
160    const SIGNATURE: &'static str = "(a{sv}aya(say)sstayay)";
161    // Greatest member alignment: the metadata dict and the timestamp.
162    const ALIGNMENT: usize = 8;
163    const FIXED_SIZE: Option<usize> = None;
164}
165
166impl GvEncode for Commit {
167    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
168        let metadata = to_bytes(&METADATA_TYPE, &self.metadata)?;
169        let parent: &[u8] = match &self.parent {
170            Some(checksum) => checksum.as_bytes(),
171            None => &[],
172        };
173        let related: Vec<(&str, &[u8])> = self
174            .related
175            .iter()
176            .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
177            .collect();
178        (
179            RawDict(&metadata),
180            parent,
181            Slice(&related),
182            self.subject.as_str(),
183            self.body.as_str(),
184            Be64(self.timestamp),
185            self.root_dirtree,
186            self.root_dirmeta,
187        )
188            .encode(out)
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    fn csum(byte: u8) -> Checksum {
197        Checksum::from_bytes([byte; 32])
198    }
199
200    fn sample() -> Commit {
201        Commit {
202            metadata: Value::Array(vec![Value::Tuple(vec![
203                Value::Str("version".to_owned()),
204                Value::variant(Type::Str, Value::Str("42".to_owned())),
205            ])]),
206            parent: Some(csum(0xaa)),
207            related: Vec::new(),
208            subject: "subject".to_owned(),
209            body: "body".to_owned(),
210            timestamp: 1_700_000_000,
211            root_dirtree: csum(1),
212            root_dirmeta: csum(2),
213        }
214    }
215
216    #[test]
217    fn round_trips_with_parent_and_metadata() {
218        let commit = sample();
219        let bytes = commit.serialize().unwrap();
220        let parsed = Commit::parse(&bytes).unwrap();
221        assert_eq!(parsed, commit);
222        assert_eq!(parsed.serialize().unwrap(), bytes);
223        assert_eq!(parsed.version(), Some("42"));
224        assert!(parsed.ref_bindings().is_empty());
225        assert_eq!(parsed.collection_binding(), None);
226    }
227
228    #[test]
229    fn empty_parent_ay_means_a_root_commit() {
230        let commit = Commit {
231            parent: None,
232            ..sample()
233        };
234        let parsed = Commit::parse(&commit.serialize().unwrap()).unwrap();
235        assert_eq!(parsed.parent, None);
236    }
237
238    /// Serialize a commit through the `Value` tree with an arbitrary parent
239    /// and root checksum widths, bypassing the struct's validation.
240    fn craft(parent: &[u8], root_dirtree: &[u8]) -> Vec<u8> {
241        let ty = Type::parse(<Commit as GvType>::SIGNATURE).unwrap();
242        let value = Value::Tuple(vec![
243            Value::Array(Vec::new()),
244            Value::Bytes(parent.to_vec()),
245            Value::Array(Vec::new()),
246            Value::Str(String::new()),
247            Value::Str(String::new()),
248            Value::U64(0),
249            Value::Bytes(root_dirtree.to_vec()),
250            Value::Bytes(vec![2; 32]),
251        ]);
252        to_bytes(&ty, &value).unwrap()
253    }
254
255    #[test]
256    fn parse_rejects_malformed_checksum_widths() {
257        assert_eq!(
258            Commit::parse(&craft(&[0xaa; 31], &[1; 32])),
259            Err(Error::InvalidCommit(
260                "parent checksum is neither empty nor 32 bytes"
261            ))
262        );
263        assert_eq!(
264            Commit::parse(&craft(&[], &[1; 31])),
265            Err(Error::InvalidCommit(
266                "root dirtree checksum is not 32 bytes"
267            ))
268        );
269    }
270
271    #[test]
272    fn content_checksum_hashes_the_two_root_checksums() {
273        let commit = sample();
274        let mut buf = Vec::new();
275        buf.extend_from_slice(csum(1).as_bytes());
276        buf.extend_from_slice(csum(2).as_bytes());
277        assert_eq!(commit.content_checksum(), Checksum::sha256(&buf));
278    }
279}