Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 6.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Helpers for the unit tests: an in-memory repository with short ways to
5//! write files, trees and changesets, and to read them back.
6
7use std::cell::{Cell, RefCell};
8use std::collections::BTreeMap;
9use std::convert::Infallible;
10
11use braid_format::{
12 Change, ChangeOp, EntryKind, GitId, Kind, MemoryObjects, ObjectId, Objects, Signature,
13};
14
15/// Objects in memory that remember the hints they get: the id stored and
16/// the id it was said to be similar to.
17#[derive(Default)]
18pub(crate) struct Hinted {
19 pub(crate) objects: MemoryObjects,
20 pub(crate) hints: RefCell<Vec<(ObjectId, ObjectId)>>,
21}
22
23impl Objects for Hinted {
24 type Error = Infallible;
25
26 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
27 self.objects.get(id)
28 }
29
30 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
31 self.objects.put(kind, payload)
32 }
33
34 fn put_similar(
35 &self,
36 kind: Kind,
37 payload: &[u8],
38 similar: &ObjectId,
39 ) -> Result<ObjectId, Self::Error> {
40 let id = self.objects.put(kind, payload)?;
41 self.hints.borrow_mut().push((id, *similar));
42 Ok(id)
43 }
44}
45
46/// Objects in memory that count the objects read and written.
47#[derive(Default)]
48pub(crate) struct Counted {
49 pub(crate) objects: MemoryObjects,
50 pub(crate) reads: Cell<usize>,
51 pub(crate) writes: Cell<usize>,
52}
53
54impl Counted {
55 /// The reads and writes since the last call, and starts counting again.
56 pub(crate) fn take(&self) -> (usize, usize) {
57 (self.reads.replace(0), self.writes.replace(0))
58 }
59}
60
61impl Objects for Counted {
62 type Error = Infallible;
63
64 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
65 self.reads.set(self.reads.get() + 1);
66 self.objects.get(id)
67 }
68
69 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
70 self.writes.set(self.writes.get() + 1);
71 self.objects.put(kind, payload)
72 }
73}
74
75use crate::access::{EMPTY_TREE, read_blob, read_changeset, read_tree};
76use crate::apply::apply;
77use crate::commit::commit;
78use crate::path::join;
79
80pub(crate) fn signature(name: &str) -> Signature {
81 Signature {
82 name: name.as_bytes().to_vec(),
83 email: format!("{name}@example.org").into_bytes(),
84 seconds: 1_700_000_000,
85 offset_minutes: 60,
86 }
87}
88
89pub(crate) fn delete(path: &str) -> Change {
90 Change {
91 path: path.as_bytes().to_vec(),
92 op: ChangeOp::Delete,
93 }
94}
95
96pub(crate) fn gitlink(path: &str, byte: u8) -> Change {
97 Change {
98 path: path.as_bytes().to_vec(),
99 op: ChangeOp::Gitlink {
100 commit: GitId::Sha1([byte; 20]),
101 },
102 }
103}
104
105pub(crate) struct Repo {
106 pub(crate) objects: MemoryObjects,
107}
108
109impl Repo {
110 pub(crate) fn new() -> Self {
111 Repo {
112 objects: MemoryObjects::new(),
113 }
114 }
115
116 pub(crate) fn blob(&self, content: &str) -> ObjectId {
117 self.objects.put(Kind::Blob, content.as_bytes()).unwrap()
118 }
119
120 pub(crate) fn file_kind(&self, content: &str) -> EntryKind {
121 EntryKind::File {
122 blob: self.blob(content),
123 size: content.len() as u64,
124 }
125 }
126
127 pub(crate) fn set(&self, path: &str, content: &str) -> Change {
128 Change {
129 path: path.as_bytes().to_vec(),
130 op: ChangeOp::File {
131 blob: self.blob(content),
132 size: content.len() as u64,
133 },
134 }
135 }
136
137 pub(crate) fn exec(&self, path: &str, content: &str) -> Change {
138 Change {
139 path: path.as_bytes().to_vec(),
140 op: ChangeOp::Executable {
141 blob: self.blob(content),
142 size: content.len() as u64,
143 },
144 }
145 }
146
147 pub(crate) fn symlink(&self, path: &str, target: &str) -> Change {
148 Change {
149 path: path.as_bytes().to_vec(),
150 op: ChangeOp::Symlink {
151 blob: self.blob(target),
152 size: target.len() as u64,
153 },
154 }
155 }
156
157 /// A tree with these regular files.
158 pub(crate) fn tree(&self, files: &[(&str, &str)]) -> ObjectId {
159 let changes: Vec<Change> = files
160 .iter()
161 .map(|(path, content)| self.set(path, content))
162 .collect();
163 apply(&self.objects, EMPTY_TREE, &changes).unwrap()
164 }
165
166 pub(crate) fn commit(&self, parents: &[ObjectId], changes: Vec<Change>) -> ObjectId {
167 commit(
168 &self.objects,
169 parents.to_vec(),
170 changes,
171 signature("author"),
172 signature("author"),
173 b"change\n".to_vec(),
174 Vec::new(),
175 )
176 .unwrap()
177 }
178
179 pub(crate) fn root(&self, changeset: ObjectId) -> ObjectId {
180 read_changeset(&self.objects, changeset).unwrap().root
181 }
182
183 /// Every file under `root`, as text: regular files by content,
184 /// executables as `exec:<content>`, symlinks as `link:<target>` and
185 /// gitlinks as `gitlink:<first byte>`.
186 pub(crate) fn files(&self, root: ObjectId) -> BTreeMap<String, String> {
187 let mut files = BTreeMap::new();
188 let mut pending = vec![(Vec::new(), root)];
189 while let Some((dir, tree)) = pending.pop() {
190 for entry in read_tree(&self.objects, tree).unwrap() {
191 let path = join(&dir, &entry.name);
192 let text = |blob: ObjectId| {
193 String::from_utf8(read_blob(&self.objects, blob).unwrap()).unwrap()
194 };
195 let value = match entry.kind {
196 EntryKind::Tree { tree } => {
197 pending.push((path, tree));
198 continue;
199 }
200 EntryKind::File { blob, .. } => text(blob),
201 EntryKind::Executable { blob, .. } => format!("exec:{}", text(blob)),
202 EntryKind::Symlink { blob, .. } => format!("link:{}", text(blob)),
203 EntryKind::Gitlink { commit } => format!("gitlink:{}", commit.as_bytes()[0]),
204 };
205 files.insert(String::from_utf8(path).unwrap(), value);
206 }
207 }
208 files
209 }
210}
211
212/// A path with `depth` names: `d/d/…/d/file`.
213pub(crate) fn deep_path(depth: usize) -> String {
214 let mut names = vec!["d"; depth - 1];
215 names.push("file");
216 names.join("/")
217}
218
219/// A map from path to text, for comparing with [`Repo::files`].
220pub(crate) fn text_map(files: &[(&str, &str)]) -> BTreeMap<String, String> {
221 files
222 .iter()
223 .map(|(path, value)| (path.to_string(), value.to_string()))
224 .collect()
225}