1use 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
23static METADATA_TYPE: LazyLock<Type> =
26 LazyLock::new(|| Type::parse("a{sv}").expect("a{sv} is a valid signature"));
27
28#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Commit {
32 pub metadata: Value,
35 pub parent: Option<Checksum>,
37 pub related: Vec<(String, Vec<u8>)>,
40 pub subject: String,
42 pub body: String,
44 pub timestamp: u64,
46 pub root_dirtree: Checksum,
48 pub root_dirmeta: Checksum,
50}
51
52type 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 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 pub fn serialize(&self) -> Result<Vec<u8>> {
98 Ok(ostrya_gvariant::encode_to_vec(self)?)
99 }
100
101 pub fn checksum(&self) -> Result<Checksum> {
103 Ok(Checksum::sha256(&self.serialize()?))
104 }
105
106 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 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 pub fn version(&self) -> Option<&str> {
127 self.metadata_value("version")?.as_str()
128 }
129
130 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 pub fn collection_binding(&self) -> Option<&str> {
140 self.metadata_value("ostree.collection-binding")?.as_str()
141 }
142}
143
144struct 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 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 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}