Elffuss BraidHub

utopia-ia/elffuss-braid public

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