Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 8.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The change list of a changeset: every file whose entry differs between two
5//! braid trees.
6
7use std::sync::Arc;
8
9use braid_format::{Change, ChangeOp, Entry, EntryKind, ObjectId, Objects};
10
11use crate::error::Error;
12use crate::fetch::TreeCache;
13
14/// The per-file changes from `old` to `new`, in no particular order. `None`
15/// stands for the empty tree. Subtrees with equal ids are skipped without
16/// being read, so the cost follows what changed. A directory replaced by a
17/// file is a delete for every file below it and one set for the file.
18/// Directories are read through `trees`.
19pub(crate) fn changes<O: Objects>(
20 objects: &O,
21 trees: &TreeCache,
22 old: Option<ObjectId>,
23 new: ObjectId,
24) -> Result<Vec<Change>, Error> {
25 let mut changes = Vec::new();
26 // Directories still to compare: path prefix, old side, new side.
27 let mut pending: Vec<(Vec<u8>, Option<ObjectId>, Option<ObjectId>)> =
28 vec![(Vec::new(), old, Some(new))];
29 let read = |side: Option<ObjectId>| -> Result<Arc<[Entry]>, Error> {
30 match side {
31 Some(id) => trees.entries(objects, id),
32 None => Ok(Arc::from(Vec::new())),
33 }
34 };
35 while let Some((prefix, old, new)) = pending.pop() {
36 if old == new {
37 continue;
38 }
39 let old_entries = read(old)?;
40 let new_entries = read(new)?;
41 let mut olds = old_entries.iter().peekable();
42 let mut news = new_entries.iter().peekable();
43 loop {
44 // Both sides are sorted by name bytes.
45 let (before, after) = match (olds.peek(), news.peek()) {
46 (None, None) => break,
47 (Some(_), None) => (olds.next(), None),
48 (None, Some(_)) => (None, news.next()),
49 (Some(o), Some(n)) => match o.name.cmp(&n.name) {
50 core::cmp::Ordering::Less => (olds.next(), None),
51 core::cmp::Ordering::Greater => (None, news.next()),
52 core::cmp::Ordering::Equal => (olds.next(), news.next()),
53 },
54 };
55 let name = match (&before, &after) {
56 (Some(entry), _) | (None, Some(entry)) => entry.name.clone(),
57 (None, None) => unreachable!("one side always has an entry"),
58 };
59 let path = join(&prefix, &name);
60 compare(
61 path,
62 before.map(|e: &Entry| e.kind.clone()),
63 after.map(|e: &Entry| e.kind.clone()),
64 &mut changes,
65 &mut pending,
66 );
67 }
68 }
69 Ok(changes)
70}
71
72/// Records the changes for one name, queueing directories to compare.
73fn compare(
74 path: Vec<u8>,
75 before: Option<EntryKind>,
76 after: Option<EntryKind>,
77 changes: &mut Vec<Change>,
78 pending: &mut Vec<(Vec<u8>, Option<ObjectId>, Option<ObjectId>)>,
79) {
80 let tree_of = |kind: &Option<EntryKind>| match kind {
81 Some(EntryKind::Tree { tree }) => Some(*tree),
82 _ => None,
83 };
84 let (old_tree, new_tree) = (tree_of(&before), tree_of(&after));
85 if old_tree != new_tree {
86 pending.push((path.clone(), old_tree, new_tree));
87 }
88 let old_file = before.filter(|kind| !matches!(kind, EntryKind::Tree { .. }));
89 let new_file = after.and_then(|kind| ChangeOp::from_entry(&kind));
90 match (old_file, new_file) {
91 (None, None) => {}
92 (Some(_), None) => changes.push(Change {
93 path,
94 op: ChangeOp::Delete,
95 }),
96 (old, Some(op)) => {
97 if old.and_then(|kind| ChangeOp::from_entry(&kind)).as_ref() != Some(&op) {
98 changes.push(Change { path, op });
99 }
100 }
101 }
102}
103
104fn join(prefix: &[u8], name: &[u8]) -> Vec<u8> {
105 if prefix.is_empty() {
106 return name.to_vec();
107 }
108 let mut path = Vec::with_capacity(prefix.len() + 1 + name.len());
109 path.extend_from_slice(prefix);
110 path.push(b'/');
111 path.extend_from_slice(name);
112 path
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use braid_format::{GitId, Kind, MemoryObjects, build_directory};
119
120 fn put_tree(objects: &MemoryObjects, entries: Vec<Entry>) -> ObjectId {
121 let dir = build_directory(entries).unwrap();
122 for (_, bytes) in &dir.nodes {
123 objects.put(Kind::Tree, bytes).unwrap();
124 }
125 dir.root()
126 }
127
128 fn file(name: &str, text: &str) -> Entry {
129 Entry {
130 name: name.as_bytes().to_vec(),
131 kind: EntryKind::File {
132 blob: ObjectId::hash(Kind::Blob, text.as_bytes()),
133 size: text.len() as u64,
134 },
135 }
136 }
137
138 fn dir(name: &str, tree: ObjectId) -> Entry {
139 Entry {
140 name: name.as_bytes().to_vec(),
141 kind: EntryKind::Tree { tree },
142 }
143 }
144
145 fn summary(mut changes: Vec<Change>) -> Vec<(String, &'static str)> {
146 changes.sort_by(|a, b| a.path.cmp(&b.path));
147 changes
148 .into_iter()
149 .map(|change| {
150 let op = match change.op {
151 ChangeOp::Delete => "delete",
152 ChangeOp::File { .. } => "file",
153 ChangeOp::Executable { .. } => "exec",
154 ChangeOp::Symlink { .. } => "symlink",
155 ChangeOp::Gitlink { .. } => "gitlink",
156 };
157 (String::from_utf8(change.path).unwrap(), op)
158 })
159 .collect()
160 }
161
162 #[test]
163 fn from_nothing_lists_every_file() {
164 let objects = MemoryObjects::new();
165 let sub = put_tree(&objects, vec![file("b", "2"), file("c", "3")]);
166 let root = put_tree(&objects, vec![file("a", "1"), dir("sub", sub)]);
167 assert_eq!(
168 summary(changes(&objects, &TreeCache::default(), None, root).unwrap()),
169 [
170 ("a".into(), "file"),
171 ("sub/b".into(), "file"),
172 ("sub/c".into(), "file")
173 ]
174 );
175 assert!(
176 changes(&objects, &TreeCache::default(), Some(root), root)
177 .unwrap()
178 .is_empty()
179 );
180 }
181
182 #[test]
183 fn edits_kinds_and_directory_swaps() {
184 let objects = MemoryObjects::new();
185 let empty = put_tree(&objects, Vec::new());
186 let inner = put_tree(&objects, vec![file("x", "1"), file("y", "2")]);
187 let shared = put_tree(&objects, vec![file("s", "same")]);
188 let old = put_tree(
189 &objects,
190 vec![
191 file("edit", "old"),
192 file("mode", "m"),
193 dir("gone", inner),
194 file("becomes-dir", "f"),
195 dir("same", shared),
196 dir("empty", empty),
197 Entry {
198 name: b"sub".to_vec(),
199 kind: EntryKind::Gitlink {
200 commit: GitId::Sha1([1; 20]),
201 },
202 },
203 ],
204 );
205 let new = put_tree(
206 &objects,
207 vec![
208 file("edit", "new"),
209 Entry {
210 name: b"mode".to_vec(),
211 kind: EntryKind::Executable {
212 blob: ObjectId::hash(Kind::Blob, b"m"),
213 size: 1,
214 },
215 },
216 file("gone", "now a file"),
217 dir("becomes-dir", inner),
218 dir("same", shared),
219 Entry {
220 name: b"sub".to_vec(),
221 kind: EntryKind::Gitlink {
222 commit: GitId::Sha1([2; 20]),
223 },
224 },
225 ],
226 );
227 assert_eq!(
228 summary(changes(&objects, &TreeCache::default(), Some(old), new).unwrap()),
229 [
230 ("becomes-dir".into(), "delete"),
231 ("becomes-dir/x".into(), "file"),
232 ("becomes-dir/y".into(), "file"),
233 ("edit".into(), "file"),
234 ("gone".into(), "file"),
235 ("gone/x".into(), "delete"),
236 ("gone/y".into(), "delete"),
237 ("mode".into(), "exec"),
238 ("sub".into(), "gitlink"),
239 ]
240 );
241 }
242
243 #[test]
244 fn missing_trees_are_errors() {
245 let objects = MemoryObjects::new();
246 let missing = ObjectId::hash(Kind::Tree, b"nowhere");
247 assert!(matches!(
248 changes(&objects, &TreeCache::default(), None, missing),
249 Err(Error::MissingBraidObject { .. })
250 ));
251 }
252}