Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 21.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Changesets: one change to the repository.
5//!
6//! A changeset names its parents, the root tree it produces, and the files
7//! that changed relative to its **first** parent. The change list makes
8//! history, blame and rebase cheap; the root tree id makes the changeset
9//! commit to the whole repository state. A store only accepts a changeset
10//! whose change list, applied to the first parent's tree, gives exactly that
11//! root (see the admission check in the store).
12
13use core::fmt;
14
15use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_sv, put_uv};
16use crate::id::{Kind, ObjectId};
17use crate::name::{PathError, forbidden_as_symlink, validate_path};
18use crate::tree::{EntryKind, GitId};
19
20/// Format byte of every changeset.
21pub const FORMAT: u8 = 1;
22
23/// A change list whose encoding is at most this many bytes is stored inside
24/// the changeset; a longer one is stored as a separate blob.
25pub const MAX_INLINE_CHANGES_BYTES: usize = 64 * 1024;
26
27/// What happened to one path.
28#[derive(Clone, Debug, PartialEq, Eq, Hash)]
29pub enum ChangeOp {
30 /// The path no longer exists.
31 Delete,
32 /// The path is now this regular file.
33 File { blob: ObjectId, size: u64 },
34 /// The path is now this executable file.
35 Executable { blob: ObjectId, size: u64 },
36 /// The path is now this symlink.
37 Symlink { blob: ObjectId, size: u64 },
38 /// The path is now this git submodule.
39 Gitlink { commit: GitId },
40}
41
42impl ChangeOp {
43 /// The operation that sets a path to a tree entry of this kind. Trees are
44 /// not files, so they have none: changes are always per file.
45 pub fn from_entry(kind: &EntryKind) -> Option<Self> {
46 Some(match kind {
47 EntryKind::File { blob, size } => ChangeOp::File {
48 blob: *blob,
49 size: *size,
50 },
51 EntryKind::Executable { blob, size } => ChangeOp::Executable {
52 blob: *blob,
53 size: *size,
54 },
55 EntryKind::Symlink { blob, size } => ChangeOp::Symlink {
56 blob: *blob,
57 size: *size,
58 },
59 EntryKind::Gitlink { commit } => ChangeOp::Gitlink { commit: *commit },
60 EntryKind::Tree { .. } => return None,
61 })
62 }
63
64 /// The tree entry this operation sets, or `None` for a delete.
65 pub fn to_entry(&self) -> Option<EntryKind> {
66 Some(match self {
67 ChangeOp::Delete => return None,
68 ChangeOp::File { blob, size } => EntryKind::File {
69 blob: *blob,
70 size: *size,
71 },
72 ChangeOp::Executable { blob, size } => EntryKind::Executable {
73 blob: *blob,
74 size: *size,
75 },
76 ChangeOp::Symlink { blob, size } => EntryKind::Symlink {
77 blob: *blob,
78 size: *size,
79 },
80 ChangeOp::Gitlink { commit } => EntryKind::Gitlink { commit: *commit },
81 })
82 }
83}
84
85/// One changed path.
86#[derive(Clone, Debug, PartialEq, Eq, Hash)]
87pub struct Change {
88 /// The full path, names joined by `/`.
89 pub path: Vec<u8>,
90 /// What happened to it.
91 pub op: ChangeOp,
92}
93
94impl Change {
95 fn encode(&self, out: &mut Vec<u8>) {
96 put_bytes(out, &self.path);
97 match &self.op {
98 ChangeOp::Delete => out.push(0),
99 ChangeOp::File { blob, size } => {
100 out.push(1);
101 put_id(out, blob);
102 put_uv(out, *size);
103 }
104 ChangeOp::Executable { blob, size } => {
105 out.push(2);
106 put_id(out, blob);
107 put_uv(out, *size);
108 }
109 ChangeOp::Symlink { blob, size } => {
110 out.push(3);
111 put_id(out, blob);
112 put_uv(out, *size);
113 }
114 ChangeOp::Gitlink { commit } => {
115 out.push(4);
116 commit.encode(out);
117 }
118 }
119 }
120
121 /// Checks the path, and that a symlink does not take a name git or braid reads.
122 fn validate(&self) -> Result<(), ChangesetError> {
123 validate_path(&self.path).map_err(|error| ChangesetError::Path {
124 path: self.path.clone(),
125 error,
126 })?;
127 let last = self.path.rsplit(|byte| *byte == b'/').next().unwrap_or(&[]);
128 if matches!(self.op, ChangeOp::Symlink { .. }) && forbidden_as_symlink(last) {
129 return Err(ChangesetError::SymlinkName(self.path.clone()));
130 }
131 Ok(())
132 }
133
134 fn decode(reader: &mut Reader<'_>) -> Result<Self, ChangesetError> {
135 let path = reader.bytes()?.to_vec();
136 let at = reader.position();
137 let op = match reader.u8()? {
138 0 => ChangeOp::Delete,
139 1 => ChangeOp::File {
140 blob: reader.id()?,
141 size: reader.uv()?,
142 },
143 2 => ChangeOp::Executable {
144 blob: reader.id()?,
145 size: reader.uv()?,
146 },
147 3 => ChangeOp::Symlink {
148 blob: reader.id()?,
149 size: reader.uv()?,
150 },
151 4 => ChangeOp::Gitlink {
152 commit: GitId::decode(reader)?,
153 },
154 _ => {
155 return Err(DecodeError::Invalid {
156 at,
157 what: "change operation",
158 }
159 .into());
160 }
161 };
162 let change = Change { path, op };
163 change.validate()?;
164 Ok(change)
165 }
166}
167
168/// Smallest possible encoded change: a 1-byte path and a delete.
169const MIN_CHANGE_BYTES: usize = 1 + 1 + 1;
170
171/// Who made or committed a change, and when.
172#[derive(Clone, Debug, PartialEq, Eq, Hash)]
173pub struct Signature {
174 /// Name, as raw bytes.
175 pub name: Vec<u8>,
176 /// E-mail address, as raw bytes.
177 pub email: Vec<u8>,
178 /// Seconds since the Unix epoch.
179 pub seconds: i64,
180 /// Offset from UTC in minutes.
181 pub offset_minutes: i64,
182}
183
184impl Signature {
185 fn encode(&self, out: &mut Vec<u8>) {
186 put_bytes(out, &self.name);
187 put_bytes(out, &self.email);
188 put_sv(out, self.seconds);
189 put_sv(out, self.offset_minutes);
190 }
191
192 fn decode(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
193 Ok(Signature {
194 name: reader.bytes()?.to_vec(),
195 email: reader.bytes()?.to_vec(),
196 seconds: reader.sv()?,
197 offset_minutes: reader.sv()?,
198 })
199 }
200}
201
202/// Where the change list is.
203#[derive(Clone, Debug, PartialEq, Eq)]
204pub enum Changes {
205 /// Inside the changeset.
206 Inline(Vec<Change>),
207 /// In a separate blob holding the encoded list.
208 External {
209 /// Id of the blob with the encoded list.
210 list: ObjectId,
211 /// Number of changes in it.
212 count: u64,
213 },
214}
215
216/// A decoded changeset.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct Changeset {
219 /// Parent changesets; the first is the base of the change list.
220 pub parents: Vec<ObjectId>,
221 /// Root tree of the repository after this change.
222 pub root: ObjectId,
223 /// The files that changed relative to the first parent.
224 pub changes: Changes,
225 /// Who wrote the change.
226 pub author: Signature,
227 /// Who recorded it.
228 pub committer: Signature,
229 /// The message, as raw bytes.
230 pub message: Vec<u8>,
231 /// Extra fields, in order, duplicates allowed.
232 pub extras: Vec<(Vec<u8>, Vec<u8>)>,
233 /// For a changeset imported from git: the blob with the original commit.
234 pub git_origin: Option<ObjectId>,
235}
236
237/// Why a changeset or change list is not valid.
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub enum ChangesetError {
240 /// The bytes are not a canonical encoding.
241 Decode(DecodeError),
242 /// A path is not valid.
243 Path { path: Vec<u8>, error: PathError },
244 /// Paths are not strictly ascending; `index` is the first out of order.
245 Unsorted { index: usize },
246 /// A symlink takes a name that git or braid reads.
247 SymlinkName(Vec<u8>),
248 /// An inline change list is longer than [`MAX_INLINE_CHANGES_BYTES`].
249 InlineTooLong(usize),
250}
251
252impl fmt::Display for ChangesetError {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 match self {
255 ChangesetError::Decode(err) => write!(f, "{err}"),
256 ChangesetError::Path { path, error } => {
257 write!(f, "path {:?}: {error}", String::from_utf8_lossy(path))
258 }
259 ChangesetError::Unsorted { index } => {
260 write!(f, "change {index} is out of order or a duplicate")
261 }
262 ChangesetError::SymlinkName(path) => write!(
263 f,
264 "symlink {:?} takes a name that must not be a symlink",
265 String::from_utf8_lossy(path)
266 ),
267 ChangesetError::InlineTooLong(len) => write!(
268 f,
269 "inline change list of {len} bytes is longer than {MAX_INLINE_CHANGES_BYTES}"
270 ),
271 }
272 }
273}
274
275impl std::error::Error for ChangesetError {}
276
277impl From<DecodeError> for ChangesetError {
278 fn from(err: DecodeError) -> Self {
279 ChangesetError::Decode(err)
280 }
281}
282
283fn check_ascending(changes: &[Change]) -> Result<(), ChangesetError> {
284 for (index, pair) in changes.windows(2).enumerate() {
285 if pair[0].path >= pair[1].path {
286 return Err(ChangesetError::Unsorted { index: index + 1 });
287 }
288 }
289 Ok(())
290}
291
292/// Encodes a change list: the count, then each change. This is both the
293/// inline form and the content of an external change-list blob.
294pub fn encode_change_list(changes: &[Change]) -> Vec<u8> {
295 let mut out = Vec::new();
296 put_uv(&mut out, changes.len() as u64);
297 for change in changes {
298 change.encode(&mut out);
299 }
300 out
301}
302
303fn read_change_list(reader: &mut Reader<'_>) -> Result<Vec<Change>, ChangesetError> {
304 let count = reader.count(MIN_CHANGE_BYTES)?;
305 let mut changes = Vec::with_capacity(count);
306 for _ in 0..count {
307 changes.push(Change::decode(reader)?);
308 }
309 check_ascending(&changes)?;
310 Ok(changes)
311}
312
313/// Decodes the content of an external change-list blob.
314pub fn decode_change_list(bytes: &[u8]) -> Result<Vec<Change>, ChangesetError> {
315 let mut reader = Reader::new(bytes);
316 let changes = read_change_list(&mut reader)?;
317 reader.finish()?;
318 Ok(changes)
319}
320
321/// Everything a changeset is made of, before the change list is placed.
322#[derive(Clone, Debug, PartialEq, Eq)]
323pub struct ChangesetParts {
324 /// Parent changesets; the first is the base of the change list.
325 pub parents: Vec<ObjectId>,
326 /// Root tree after the change.
327 pub root: ObjectId,
328 /// The changed paths, in any order.
329 pub changes: Vec<Change>,
330 /// Who wrote the change.
331 pub author: Signature,
332 /// Who recorded it.
333 pub committer: Signature,
334 /// The message.
335 pub message: Vec<u8>,
336 /// Extra fields.
337 pub extras: Vec<(Vec<u8>, Vec<u8>)>,
338 /// For an import from git: the blob with the original commit.
339 pub git_origin: Option<ObjectId>,
340}
341
342/// A changeset in canonical form, ready to store.
343#[derive(Clone, Debug, PartialEq, Eq)]
344pub struct Assembled {
345 /// The changeset.
346 pub changeset: Changeset,
347 /// Its id.
348 pub id: ObjectId,
349 /// Its encoding.
350 pub encoded: Vec<u8>,
351 /// The change-list blob to store alongside it, when the list is external.
352 pub external_list: Option<(ObjectId, Vec<u8>)>,
353}
354
355impl ChangesetParts {
356 /// Sorts and checks the change list, places it inline or in its own blob,
357 /// and encodes the result.
358 pub fn assemble(mut self) -> Result<Assembled, ChangesetError> {
359 self.changes.sort_by(|a, b| a.path.cmp(&b.path));
360 check_ascending(&self.changes)?;
361 for change in &self.changes {
362 change.validate()?;
363 }
364 let list = encode_change_list(&self.changes);
365 let (changes, external_list) = if list.len() <= MAX_INLINE_CHANGES_BYTES {
366 (Changes::Inline(self.changes), None)
367 } else {
368 let id = ObjectId::hash(Kind::Blob, &list);
369 (
370 Changes::External {
371 list: id,
372 count: self.changes.len() as u64,
373 },
374 Some((id, list)),
375 )
376 };
377 let changeset = Changeset {
378 parents: self.parents,
379 root: self.root,
380 changes,
381 author: self.author,
382 committer: self.committer,
383 message: self.message,
384 extras: self.extras,
385 git_origin: self.git_origin,
386 };
387 let encoded = changeset.encode();
388 let id = ObjectId::hash(Kind::Changeset, &encoded);
389 Ok(Assembled {
390 changeset,
391 id,
392 encoded,
393 external_list,
394 })
395 }
396}
397
398impl Changeset {
399 /// The canonical encoding.
400 pub fn encode(&self) -> Vec<u8> {
401 let mut out = vec![FORMAT];
402 put_uv(&mut out, self.parents.len() as u64);
403 for parent in &self.parents {
404 put_id(&mut out, parent);
405 }
406 put_id(&mut out, &self.root);
407 match &self.changes {
408 Changes::Inline(changes) => {
409 out.push(0);
410 out.extend_from_slice(&encode_change_list(changes));
411 }
412 Changes::External { list, count } => {
413 out.push(1);
414 put_id(&mut out, list);
415 put_uv(&mut out, *count);
416 }
417 }
418 self.author.encode(&mut out);
419 self.committer.encode(&mut out);
420 put_bytes(&mut out, &self.message);
421 put_uv(&mut out, self.extras.len() as u64);
422 for (key, value) in &self.extras {
423 put_bytes(&mut out, key);
424 put_bytes(&mut out, value);
425 }
426 match &self.git_origin {
427 None => out.push(0),
428 Some(id) => {
429 out.push(1);
430 put_id(&mut out, id);
431 }
432 }
433 out
434 }
435
436 /// The id of this changeset.
437 pub fn id(&self) -> ObjectId {
438 ObjectId::hash(Kind::Changeset, &self.encode())
439 }
440
441 /// Decodes a changeset and checks everything that can be checked without
442 /// other objects.
443 pub fn decode(bytes: &[u8]) -> Result<Self, ChangesetError> {
444 let mut reader = Reader::new(bytes);
445 let at = reader.position();
446 if reader.u8()? != FORMAT {
447 return Err(DecodeError::Invalid {
448 at,
449 what: "changeset format",
450 }
451 .into());
452 }
453 let parent_count = reader.count(32)?;
454 let mut parents = Vec::with_capacity(parent_count);
455 for _ in 0..parent_count {
456 parents.push(reader.id()?);
457 }
458 let root = reader.id()?;
459 let at = reader.position();
460 let changes = match reader.u8()? {
461 0 => {
462 let start = reader.position();
463 let changes = read_change_list(&mut reader)?;
464 let len = reader.position() - start;
465 if len > MAX_INLINE_CHANGES_BYTES {
466 return Err(ChangesetError::InlineTooLong(len));
467 }
468 Changes::Inline(changes)
469 }
470 1 => Changes::External {
471 list: reader.id()?,
472 count: reader.uv()?,
473 },
474 _ => {
475 return Err(DecodeError::Invalid {
476 at,
477 what: "change list mode",
478 }
479 .into());
480 }
481 };
482 let author = Signature::decode(&mut reader)?;
483 let committer = Signature::decode(&mut reader)?;
484 let message = reader.bytes()?.to_vec();
485 let extra_count = reader.count(2)?;
486 let mut extras = Vec::with_capacity(extra_count);
487 for _ in 0..extra_count {
488 let key = reader.bytes()?.to_vec();
489 let value = reader.bytes()?.to_vec();
490 extras.push((key, value));
491 }
492 let at = reader.position();
493 let git_origin = match reader.u8()? {
494 0 => None,
495 1 => Some(reader.id()?),
496 _ => {
497 return Err(DecodeError::Invalid {
498 at,
499 what: "git origin flag",
500 }
501 .into());
502 }
503 };
504 reader.finish()?;
505 Ok(Changeset {
506 parents,
507 root,
508 changes,
509 author,
510 committer,
511 message,
512 extras,
513 git_origin,
514 })
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521 use crate::tree::build_directory;
522
523 fn blob(text: &str) -> ObjectId {
524 ObjectId::hash(Kind::Blob, text.as_bytes())
525 }
526
527 fn signature() -> Signature {
528 Signature {
529 name: b"Ada Lovelace".to_vec(),
530 email: b"ada@example.org".to_vec(),
531 seconds: 1_700_000_000,
532 offset_minutes: 60,
533 }
534 }
535
536 fn parts(changes: Vec<Change>) -> ChangesetParts {
537 ChangesetParts {
538 parents: Vec::new(),
539 root: build_directory(Vec::new()).unwrap().root(),
540 changes,
541 author: signature(),
542 committer: signature(),
543 message: b"Initial import\n".to_vec(),
544 extras: Vec::new(),
545 git_origin: None,
546 }
547 }
548
549 fn set(path: &str, text: &str) -> Change {
550 Change {
551 path: path.as_bytes().to_vec(),
552 op: ChangeOp::File {
553 blob: blob(text),
554 size: text.len() as u64,
555 },
556 }
557 }
558
559 #[test]
560 fn golden_changeset() {
561 let assembled = parts(vec![set("README.md", "hello\n"), set("src/lib.rs", "")])
562 .assemble()
563 .unwrap();
564 assert!(assembled.external_list.is_none());
565 assert_eq!(
566 assembled.id.to_hex(),
567 "4f8d49034a95a2938d30d13bee5508100211d04e1c125ef567a0c41c27f777d1"
568 );
569 }
570
571 #[test]
572 fn round_trip_with_everything() {
573 let mut p = parts(vec![
574 set("b/x", "1"),
575 Change {
576 path: b"a".to_vec(),
577 op: ChangeOp::Delete,
578 },
579 Change {
580 path: b"c".to_vec(),
581 op: ChangeOp::Gitlink {
582 commit: GitId::Sha256([7; 32]),
583 },
584 },
585 ]);
586 p.parents = vec![blob("p1"), blob("p2")];
587 p.extras = vec![
588 (b"gpgsig".to_vec(), b"sig".to_vec()),
589 (b"gpgsig".to_vec(), b"sig".to_vec()),
590 ];
591 p.git_origin = Some(blob("raw commit"));
592 p.author.seconds = -5;
593 p.committer.offset_minutes = -330;
594 let assembled = p.assemble().unwrap();
595 let decoded = Changeset::decode(&assembled.encoded).unwrap();
596 assert_eq!(decoded, assembled.changeset);
597 assert_eq!(decoded.encode(), assembled.encoded);
598 assert_eq!(decoded.id(), assembled.id);
599 match &decoded.changes {
600 Changes::Inline(changes) => {
601 let paths: Vec<&[u8]> = changes.iter().map(|c| c.path.as_slice()).collect();
602 assert_eq!(paths, [&b"a"[..], b"b/x", b"c"]);
603 }
604 Changes::External { .. } => panic!("expected an inline list"),
605 }
606 }
607
608 #[test]
609 fn large_lists_go_to_a_blob() {
610 let changes: Vec<Change> = (0..3000)
611 .map(|i| set(&format!("dir/file-{i:06}.txt"), "x"))
612 .collect();
613 let assembled = parts(changes.clone()).assemble().unwrap();
614 let (list_id, list) = assembled.external_list.clone().unwrap();
615 assert_eq!(list_id, ObjectId::hash(Kind::Blob, &list));
616 assert_eq!(decode_change_list(&list).unwrap(), changes);
617 assert_eq!(
618 assembled.changeset.changes,
619 Changes::External {
620 list: list_id,
621 count: 3000
622 }
623 );
624 let decoded = Changeset::decode(&assembled.encoded).unwrap();
625 assert_eq!(decoded, assembled.changeset);
626 }
627
628 #[test]
629 fn rejects_bad_lists() {
630 let duplicate = parts(vec![set("a", "1"), set("a", "2")]).assemble();
631 assert_eq!(duplicate, Err(ChangesetError::Unsorted { index: 1 }));
632 let bad_path = parts(vec![set("a/../b", "1")]).assemble();
633 assert!(matches!(bad_path, Err(ChangesetError::Path { .. })));
634 let git_dir = parts(vec![set(".git/config", "1")]).assemble();
635 assert!(matches!(git_dir, Err(ChangesetError::Path { .. })));
636 let symlink = |path: &str| Change {
637 path: path.as_bytes().to_vec(),
638 op: ChangeOp::Symlink {
639 blob: blob("target"),
640 size: 6,
641 },
642 };
643 assert_eq!(
644 parts(vec![symlink("sub/.GITMODULES")]).assemble(),
645 Err(ChangesetError::SymlinkName(b"sub/.GITMODULES".to_vec()))
646 );
647 assert!(
648 parts(vec![symlink("sub/.gitmodules-notes")])
649 .assemble()
650 .is_ok()
651 );
652
653 // An inline list longer than the limit is not canonical.
654 let changes: Vec<Change> = (0..3000)
655 .map(|i| set(&format!("dir/file-{i:06}.txt"), "x"))
656 .collect();
657 let mut forged = parts(Vec::new()).assemble().unwrap().changeset;
658 forged.changes = Changes::Inline(changes);
659 assert!(matches!(
660 Changeset::decode(&forged.encode()),
661 Err(ChangesetError::InlineTooLong(_))
662 ));
663
664 let good = parts(vec![set("a", "1")]).assemble().unwrap().encoded;
665 let mut trailing = good.clone();
666 trailing.push(0);
667 assert!(matches!(
668 Changeset::decode(&trailing),
669 Err(ChangesetError::Decode(DecodeError::TrailingBytes { .. }))
670 ));
671 for cut in 0..good.len() {
672 assert!(Changeset::decode(&good[..cut]).is_err(), "cut at {cut}");
673 }
674 }
675}