Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 13.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Git repositories for the tests, built with the git command line.
5//!
6//! Every repository is bare and built with plumbing only, so a test never
7//! depends on how a file system treats names, modes or symlinks. Commands run
8//! without the user's or the system's configuration, with fixed identities
9//! and a clock that ticks once per commit or tag, so every id is reproducible.
10
11#![allow(dead_code)]
12
13use std::collections::BTreeMap;
14use std::io::Write;
15use std::path::{Path, PathBuf};
16use std::process::{Command, Stdio};
17
18use tempfile::TempDir;
19
20/// What a path holds in a tree.
21#[derive(Clone, Debug)]
22pub enum Item {
23 /// A regular file.
24 File(Vec<u8>),
25 /// An executable file.
26 Exec(Vec<u8>),
27 /// A symlink to this target.
28 Link(Vec<u8>),
29 /// A submodule at this commit.
30 Submodule(String),
31}
32
33/// A path and what it holds.
34pub type Entry = (Vec<u8>, Item);
35
36/// A path, what it holds, and the id of its blob once stored.
37type Stored = (Vec<u8>, Item, Option<String>);
38
39pub fn file(path: impl AsRef<[u8]>, content: impl AsRef<[u8]>) -> Entry {
40 (
41 path.as_ref().to_vec(),
42 Item::File(content.as_ref().to_vec()),
43 )
44}
45
46pub fn exec(path: impl AsRef<[u8]>, content: impl AsRef<[u8]>) -> Entry {
47 (
48 path.as_ref().to_vec(),
49 Item::Exec(content.as_ref().to_vec()),
50 )
51}
52
53pub fn link(path: impl AsRef<[u8]>, target: impl AsRef<[u8]>) -> Entry {
54 (path.as_ref().to_vec(), Item::Link(target.as_ref().to_vec()))
55}
56
57pub fn submodule(path: impl AsRef<[u8]>, commit: &str) -> Entry {
58 (path.as_ref().to_vec(), Item::Submodule(commit.to_string()))
59}
60
61/// Raw tree bytes from `(mode, name, id)` entries, written as given: any
62/// mode, any order, duplicates allowed.
63pub fn raw_tree(entries: &[(&str, &[u8], &str)]) -> Vec<u8> {
64 let mut out = Vec::new();
65 for (mode, name, id) in entries {
66 out.extend_from_slice(mode.as_bytes());
67 out.push(b' ');
68 out.extend_from_slice(name);
69 out.push(0);
70 out.extend_from_slice(&hex(id));
71 }
72 out
73}
74
75fn hex(text: &str) -> Vec<u8> {
76 (0..text.len())
77 .step_by(2)
78 .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap())
79 .collect()
80}
81
82/// The first commit time; each commit or tag adds a minute.
83const EPOCH: i64 = 1_700_000_000;
84
85/// Variables that would point git somewhere else, or change what it reads.
86const LEAKY_VARIABLES: [&str; 12] = [
87 "GIT_DIR",
88 "GIT_WORK_TREE",
89 "GIT_INDEX_FILE",
90 "GIT_OBJECT_DIRECTORY",
91 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
92 "GIT_COMMON_DIR",
93 "GIT_NAMESPACE",
94 "GIT_CEILING_DIRECTORIES",
95 "GIT_REPLACE_REF_BASE",
96 "GIT_NO_REPLACE_OBJECTS",
97 "GIT_GRAFT_FILE",
98 "GIT_SHALLOW_FILE",
99];
100
101/// A bare repository in a temporary directory.
102pub struct Repo {
103 dir: TempDir,
104 path: PathBuf,
105 clock: i64,
106}
107
108impl Repo {
109 /// An empty SHA-1 repository whose default branch is `main`.
110 pub fn new() -> Self {
111 Self::init(&[])
112 }
113
114 /// An empty repository created with extra `git init` arguments.
115 pub fn init(args: &[&str]) -> Self {
116 let dir = tempfile::tempdir().unwrap();
117 let path = dir.path().join("repo.git");
118 let mut init = git_command(dir.path(), EPOCH);
119 init.args(["init", "--quiet", "--bare"])
120 .args(args)
121 .arg(&path);
122 run(init, None);
123 Self {
124 dir,
125 path,
126 clock: EPOCH,
127 }
128 }
129
130 pub fn path(&self) -> &Path {
131 &self.path
132 }
133
134 /// A scratch directory next to the repository.
135 pub fn scratch(&self) -> PathBuf {
136 let path = self.dir.path().join("scratch");
137 std::fs::create_dir_all(&path).unwrap();
138 path
139 }
140
141 /// A git command that runs in the repository.
142 pub fn command(&self) -> Command {
143 git_command(&self.path, self.clock)
144 }
145
146 /// Runs git and returns its output, trimmed.
147 pub fn git(&self, args: &[&str]) -> String {
148 let mut command = self.command();
149 command.args(args);
150 trimmed(run(command, None))
151 }
152
153 /// Runs git with `input` on its standard input.
154 pub fn git_input(&self, args: &[&str], input: &[u8]) -> String {
155 let mut command = self.command();
156 command.args(args);
157 trimmed(run(command, Some(input)))
158 }
159
160 /// Runs git and returns its raw output.
161 pub fn git_bytes(&self, args: &[&str]) -> Vec<u8> {
162 let mut command = self.command();
163 command.args(args);
164 run(command, None)
165 }
166
167 pub fn blob(&self, content: &[u8]) -> String {
168 self.git_input(&["hash-object", "-w", "--stdin"], content)
169 }
170
171 /// Writes many blobs with one git process, in order.
172 pub fn blobs(&self, contents: &[&[u8]]) -> Vec<String> {
173 if contents.is_empty() {
174 return Vec::new();
175 }
176 let scratch = self.scratch();
177 let mut paths = String::new();
178 for (index, content) in contents.iter().enumerate() {
179 let path = scratch.join(format!("blob-{index}"));
180 std::fs::write(&path, content).unwrap();
181 paths.push_str(path.to_str().unwrap());
182 paths.push('\n');
183 }
184 let out = self.git_input(&["hash-object", "-w", "--stdin-paths"], paths.as_bytes());
185 let ids: Vec<String> = out.lines().map(str::to_string).collect();
186 assert_eq!(ids.len(), contents.len());
187 ids
188 }
189
190 /// Stores any bytes as an object of `kind`, without git's checks.
191 pub fn literally(&self, kind: &str, bytes: &[u8]) -> String {
192 self.git_input(
193 &["hash-object", "-t", kind, "-w", "--literally", "--stdin"],
194 bytes,
195 )
196 }
197
198 /// A tree from `(mode, type, id, name)` entries, written by `git mktree`.
199 pub fn mktree(&self, entries: &[(&str, &str, &str, &[u8])]) -> String {
200 let mut input = Vec::new();
201 for (mode, kind, id, name) in entries {
202 write!(input, "{mode} {kind} {id}\t").unwrap();
203 input.extend_from_slice(name);
204 input.push(0);
205 }
206 self.git_input(&["mktree", "-z", "--missing"], &input)
207 }
208
209 /// The tree holding exactly `entries`, with directories made from the
210 /// paths.
211 pub fn tree(&self, entries: &[Entry]) -> String {
212 let contents: Vec<&[u8]> = entries
213 .iter()
214 .filter_map(|(_, item)| match item {
215 Item::File(content) | Item::Exec(content) | Item::Link(content) => {
216 Some(content.as_slice())
217 }
218 Item::Submodule(_) => None,
219 })
220 .collect();
221 let mut ids = self.blobs(&contents).into_iter();
222 let with_ids: Vec<Stored> = entries
223 .iter()
224 .map(|(path, item)| {
225 let id = match item {
226 Item::Submodule(_) => None,
227 _ => ids.next(),
228 };
229 (path.clone(), item.clone(), id)
230 })
231 .collect();
232 self.tree_level(&with_ids)
233 }
234
235 fn tree_level(&self, entries: &[Stored]) -> String {
236 let mut dirs: BTreeMap<Vec<u8>, Vec<Stored>> = BTreeMap::new();
237 let mut input = Vec::new();
238 for (path, item, id) in entries {
239 if let Some(slash) = path.iter().position(|byte| *byte == b'/') {
240 dirs.entry(path[..slash].to_vec()).or_default().push((
241 path[slash + 1..].to_vec(),
242 item.clone(),
243 id.clone(),
244 ));
245 continue;
246 }
247 let (mode, kind, id) = match item {
248 Item::File(_) => ("100644", "blob", id.clone().unwrap()),
249 Item::Exec(_) => ("100755", "blob", id.clone().unwrap()),
250 Item::Link(_) => ("120000", "blob", id.clone().unwrap()),
251 Item::Submodule(commit) => ("160000", "commit", commit.clone()),
252 };
253 write!(input, "{mode} {kind} {id}\t").unwrap();
254 input.extend_from_slice(path);
255 input.push(0);
256 }
257 for (name, children) in &dirs {
258 let id = self.tree_level(children);
259 write!(input, "040000 tree {id}\t").unwrap();
260 input.extend_from_slice(name);
261 input.push(0);
262 }
263 self.git_input(&["mktree", "-z", "--missing"], &input)
264 }
265
266 /// The tree `git write-tree` writes from a fresh index filled with
267 /// `git update-index --add --cacheinfo <mode>,<id>,<path>` for each entry.
268 pub fn index_tree(&self, cacheinfo: &[String]) -> String {
269 let index = self.scratch().join("index");
270 let _ = std::fs::remove_file(&index);
271 for info in cacheinfo {
272 let mut command = self.command();
273 command.env("GIT_INDEX_FILE", &index);
274 command.args(["update-index", "--add", "--cacheinfo", info]);
275 run(command, None);
276 }
277 let mut command = self.command();
278 command.env("GIT_INDEX_FILE", &index).arg("write-tree");
279 trimmed(run(command, None))
280 }
281
282 fn tick(&mut self) {
283 self.clock += 60;
284 }
285
286 /// A commit of `tree` with these parents and message.
287 pub fn commit(&mut self, tree: &str, parents: &[&str], message: &str) -> String {
288 self.tick();
289 let mut args = vec!["commit-tree", tree];
290 for parent in parents {
291 args.extend(["-p", parent]);
292 }
293 args.extend(["-m", message]);
294 self.git(&args)
295 }
296
297 /// The commit a branch points to, if the branch exists.
298 pub fn head(&self, branch: &str) -> Option<String> {
299 let mut command = self.command();
300 command.args(["rev-parse", "--verify", "--quiet"]);
301 command.arg(format!("refs/heads/{branch}"));
302 let output = command.output().unwrap();
303 output.status.success().then(|| trimmed(output.stdout))
304 }
305
306 /// Commits exactly `entries` on `branch`, after its current head.
307 pub fn snapshot(&mut self, branch: &str, entries: &[Entry], message: &str) -> String {
308 self.merge(branch, &[], entries, message)
309 }
310
311 /// Commits `entries` on `branch` with the heads of `others` as further
312 /// parents.
313 pub fn merge(
314 &mut self,
315 branch: &str,
316 others: &[&str],
317 entries: &[Entry],
318 message: &str,
319 ) -> String {
320 let tree = self.tree(entries);
321 let mut parents: Vec<String> = self.head(branch).into_iter().collect();
322 for other in others {
323 parents.push(self.head(other).unwrap());
324 }
325 let parents: Vec<&str> = parents.iter().map(String::as_str).collect();
326 let commit = self.commit(&tree, &parents, message);
327 self.set_ref(&format!("refs/heads/{branch}"), &commit);
328 commit
329 }
330
331 pub fn set_ref(&self, name: &str, id: &str) {
332 self.git(&["update-ref", name, id]);
333 }
334
335 /// An annotated tag named `name` on `target`; returns the tag object.
336 pub fn annotated_tag(&mut self, name: &str, target: &str, message: &str) -> String {
337 self.tick();
338 self.git(&["tag", "--annotate", "-m", message, name, target]);
339 self.git(&["rev-parse", &format!("refs/tags/{name}")])
340 }
341
342 /// Commits reachable from branches and tags, as git counts them without
343 /// replacement objects or grafts.
344 pub fn count_commits(&self) -> usize {
345 self.git(&[
346 "--no-replace-objects",
347 "rev-list",
348 "--count",
349 "--branches",
350 "--tags",
351 ])
352 .parse()
353 .unwrap()
354 }
355}
356
357/// A git command with a fixed environment, run in `dir`.
358fn git_command(dir: &Path, clock: i64) -> Command {
359 let mut command = Command::new("git");
360 command.current_dir(dir);
361 for variable in LEAKY_VARIABLES {
362 command.env_remove(variable);
363 }
364 let date = format!("{clock} +0100");
365 command
366 .env("GIT_CONFIG_GLOBAL", "/dev/null")
367 .env("GIT_CONFIG_NOSYSTEM", "1")
368 .env("GIT_GRAFT_FILE", dir.join("no-grafts"))
369 .env("GIT_AUTHOR_NAME", "Ada Lovelace")
370 .env("GIT_AUTHOR_EMAIL", "ada@example.org")
371 .env("GIT_AUTHOR_DATE", &date)
372 .env("GIT_COMMITTER_NAME", "Charles Babbage")
373 .env("GIT_COMMITTER_EMAIL", "charles@example.org")
374 .env("GIT_COMMITTER_DATE", &date)
375 .args([
376 "-c",
377 "init.defaultBranch=main",
378 "-c",
379 "commit.gpgSign=false",
380 "-c",
381 "tag.gpgSign=false",
382 "-c",
383 "gc.auto=0",
384 "-c",
385 "core.autocrlf=false",
386 "-c",
387 "advice.nestedTag=false",
388 ]);
389 command
390}
391
392fn run(mut command: Command, input: Option<&[u8]>) -> Vec<u8> {
393 command
394 .stdin(if input.is_some() {
395 Stdio::piped()
396 } else {
397 Stdio::null()
398 })
399 .stdout(Stdio::piped())
400 .stderr(Stdio::piped());
401 let mut child = command
402 .spawn()
403 .expect("git must be installed to run these tests");
404 if let Some(input) = input {
405 child.stdin.take().unwrap().write_all(input).unwrap();
406 }
407 let output = child.wait_with_output().unwrap();
408 assert!(
409 output.status.success(),
410 "{command:?} failed: {}",
411 String::from_utf8_lossy(&output.stderr)
412 );
413 output.stdout
414}
415
416fn trimmed(bytes: Vec<u8>) -> String {
417 String::from_utf8(bytes).unwrap().trim().to_string()
418}