Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 17.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! End-to-end tests of `braid git sync`, with local bare repositories playing
5//! the remote. Git runs without the user's or the system's configuration,
6//! with fixed identities and dates, in the tests and in braid alike.
7
8use std::cell::Cell;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Output};
11
12use serde_json::Value;
13use tempfile::TempDir;
14
15const EPOCH: i64 = 1_700_000_000;
16
17/// Environment variables for every command: git ignores the user's and
18/// the system's configuration and never prompts.
19const GIT_ENV: [(&str, &str); 7] = [
20 ("GIT_CONFIG_GLOBAL", "/dev/null"),
21 ("GIT_CONFIG_NOSYSTEM", "1"),
22 ("GIT_AUTHOR_NAME", "Ada Lovelace"),
23 ("GIT_AUTHOR_EMAIL", "ada@example.org"),
24 ("GIT_COMMITTER_NAME", "Charles Babbage"),
25 ("GIT_COMMITTER_EMAIL", "charles@example.org"),
26 ("GIT_TERMINAL_PROMPT", "0"),
27];
28
29fn git_at(dir: &Path, date: i64, args: &[&str]) -> String {
30 let mut command = Command::new("git");
31 for variable in [
32 "GIT_DIR",
33 "GIT_WORK_TREE",
34 "GIT_INDEX_FILE",
35 "GIT_OBJECT_DIRECTORY",
36 ] {
37 command.env_remove(variable);
38 }
39 let output = command
40 .current_dir(dir)
41 .envs(GIT_ENV)
42 .env("GIT_AUTHOR_DATE", format!("{date} +0100"))
43 .env("GIT_COMMITTER_DATE", format!("{date} +0100"))
44 .args([
45 "-c",
46 "init.defaultBranch=main",
47 "-c",
48 "commit.gpgSign=false",
49 ])
50 .args(args)
51 .output()
52 .expect("git must be installed to run these tests");
53 assert!(
54 output.status.success(),
55 "git {args:?}: {}",
56 String::from_utf8_lossy(&output.stderr)
57 );
58 String::from_utf8(output.stdout).unwrap().trim().to_owned()
59}
60
61fn git(dir: &Path, args: &[&str]) -> String {
62 git_at(dir, EPOCH, args)
63}
64
65/// A bare remote with a reflog, clones of it where people work, and a braid
66/// repository.
67struct World {
68 _dir: TempDir,
69 root: PathBuf,
70 remote: PathBuf,
71 braid: PathBuf,
72 clock: Cell<i64>,
73}
74
75impl World {
76 fn new() -> World {
77 let dir = tempfile::tempdir().unwrap();
78 let root = dir.path().to_path_buf();
79 git(&root, &["init", "--quiet", "--bare", "remote.git"]);
80 let remote = root.join("remote.git");
81 git(&remote, &["config", "core.logAllRefUpdates", "true"]);
82 let braid = root.join("braid");
83 let world = World {
84 _dir: dir,
85 root,
86 remote,
87 braid,
88 clock: Cell::new(EPOCH),
89 };
90 let init = world
91 .braid_command(&["init"])
92 .arg(&world.braid)
93 .output()
94 .unwrap();
95 assert!(init.status.success());
96 world
97 }
98
99 /// A clone of the remote named `name`, made once, on the remote's main.
100 fn clone(&self, name: &str) -> PathBuf {
101 let path = self.root.join(name);
102 if !path.exists() {
103 git(&self.root, &["init", "--quiet", name]);
104 git(
105 &path,
106 &["remote", "add", "origin", self.remote.to_str().unwrap()],
107 );
108 }
109 if !git(&self.remote, &["for-each-ref", "refs/heads/main"]).is_empty() {
110 git(&path, &["fetch", "--quiet", "origin", "main"]);
111 git(&path, &["checkout", "--quiet", "-B", "main", "FETCH_HEAD"]);
112 }
113 path
114 }
115
116 /// Commits `files` in the clone `name`, on top of the remote's main.
117 fn commit(&self, name: &str, files: &[(&str, &str)], message: &str) -> (PathBuf, String) {
118 let path = self.clone(name);
119 for (file, content) in files {
120 std::fs::write(path.join(file), content).unwrap();
121 git(&path, &["add", file]);
122 }
123 self.clock.set(self.clock.get() + 60);
124 git_at(
125 &path,
126 self.clock.get(),
127 &["commit", "--quiet", "-m", message],
128 );
129 let commit = git(&path, &["rev-parse", "HEAD"]);
130 (path, commit)
131 }
132
133 /// Commits `files` in a clone and pushes them to the remote's main.
134 fn push(&self, files: &[(&str, &str)], message: &str) -> String {
135 let (path, commit) = self.commit("work", files, message);
136 git(&path, &["push", "--quiet", "origin", "main"]);
137 commit
138 }
139
140 fn braid_command(&self, args: &[&str]) -> Command {
141 let mut command = Command::new(env!("CARGO_BIN_EXE_braid"));
142 command
143 .envs(GIT_ENV)
144 .env("BRAID_AGENT", "tester")
145 .args(args);
146 command
147 }
148
149 /// Runs braid in the repository.
150 fn braid(&self, args: &[&str]) -> Output {
151 self.braid_command(args)
152 .arg("--repo")
153 .arg(&self.braid)
154 .output()
155 .unwrap()
156 }
157
158 /// Runs braid with `--json` and returns its exit status and output.
159 fn braid_json(&self, args: &[&str]) -> (Option<i32>, Value) {
160 let output = self
161 .braid_command(args)
162 .arg("--repo")
163 .arg(&self.braid)
164 .arg("--json")
165 .output()
166 .unwrap();
167 let value = serde_json::from_slice(&output.stdout).unwrap_or_else(|err| {
168 panic!(
169 "{err}: {}{}",
170 String::from_utf8_lossy(&output.stdout),
171 String::from_utf8_lossy(&output.stderr)
172 )
173 });
174 (output.status.code(), value)
175 }
176
177 fn sync(&self) -> (Option<i32>, Value) {
178 self.braid_json(&["git", "sync", self.remote.to_str().unwrap()])
179 }
180
181 fn refs(&self) -> Value {
182 self.braid_json(&["refs"]).1["refs"].clone()
183 }
184
185 fn operations(&self) -> usize {
186 self.braid_json(&["op", "log", "-n", "1000"])
187 .1
188 .as_array()
189 .unwrap()
190 .len()
191 }
192
193 fn remote_head(&self) -> String {
194 git(&self.remote, &["rev-parse", "refs/heads/main"])
195 }
196
197 /// The remote's main only ever moved forward.
198 fn assert_forward_only(&self) {
199 let log = std::fs::read_to_string(self.remote.join("logs/refs/heads/main")).unwrap();
200 let zero = "0".repeat(40);
201 let mut last = zero.clone();
202 for line in log.lines() {
203 let mut words = line.split(' ');
204 let (old, new) = (words.next().unwrap(), words.next().unwrap());
205 assert_eq!(old, last, "the reflog is continuous");
206 if old != zero {
207 git(&self.remote, &["merge-base", "--is-ancestor", old, new]);
208 }
209 last = new.to_owned();
210 }
211 assert_eq!(last, self.remote_head());
212 }
213}
214
215#[test]
216fn the_first_sync_creates_the_branch_and_the_next_does_nothing() {
217 let world = World::new();
218 world.push(&[("README", "hello\n")], "First");
219 let second = world.push(&[("lib.rs", "pub fn f() {}\n")], "Second");
220
221 let (code, report) = world.sync();
222 assert_eq!(code, Some(0), "{report}");
223 assert_eq!(report["outcome"], "created");
224 assert_eq!(report["imported"], 2);
225 assert_eq!(report["dry_run"], false);
226 assert_eq!(report["fetched"]["commit"], second.as_str());
227 assert_eq!(report["after"], report["fetched"]["changeset"]);
228 assert_eq!(report["operations"].as_array().unwrap().len(), 1);
229 let refs = world.refs();
230 assert_eq!(refs["main"], report["after"]);
231 let remote_ref = report["remote_ref"].as_str().unwrap();
232 assert!(remote_ref.starts_with("remote/remote-"), "{remote_ref}");
233 assert_eq!(refs[remote_ref], report["after"]);
234
235 let (code, again) = world.sync();
236 assert_eq!(code, Some(0));
237 assert_eq!(again["outcome"], "up_to_date");
238 assert_eq!(again["operations"], Value::Array(Vec::new()));
239 assert_eq!(world.refs(), refs);
240
241 let log = world.braid_json(&["log", "main"]).1;
242 assert_eq!(log.as_array().unwrap().len(), 2);
243}
244
245#[test]
246fn the_remote_ahead_fast_forwards() {
247 let world = World::new();
248 world.push(&[("a", "1\n")], "First");
249 world.sync();
250 let next = world.push(&[("a", "2\n")], "Next");
251 let (code, report) = world.sync();
252 assert_eq!(code, Some(0), "{report}");
253 assert_eq!(report["outcome"], "fast_forwarded");
254 assert_eq!(report["fetched"]["commit"], next.as_str());
255 assert_eq!(world.refs()["main"], report["after"]);
256 assert_eq!(report["pushed"], Value::Null);
257}
258
259#[test]
260fn a_concurrent_push_fails_the_lease_and_the_next_sync_converges() {
261 let world = World::new();
262 world.push(&[("a", "1\n"), ("b", "1\n")], "First");
263 world.sync();
264
265 // Braid gets ahead: it imports a commit that is not on the remote yet.
266 let (upstream, ahead) = world.commit("upstream", &[("a", "braid\n")], "Ahead");
267 let import = world.braid(&["git", "import", upstream.to_str().unwrap()]);
268 assert!(import.status.success());
269
270 // Someone else's commit waits on a side branch of the remote, and the
271 // remote's update hook moves main to it while braid's push is under way:
272 // between braid's fetch and its push, someone else landed first.
273 let (side, theirs) = world.commit("side", &[("b", "theirs\n")], "Theirs");
274 git(&side, &["push", "--quiet", "origin", "main:side"]);
275 let hook = world.remote.join("hooks/update");
276 std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
277 std::fs::write(
278 &hook,
279 "#!/bin/sh\n\
280 if [ \"$1\" = refs/heads/main ]; then\n\
281 \x20 git update-ref refs/heads/main refs/heads/side\n\
282 \x20 rm -f \"$0\"\n\
283 fi\n",
284 )
285 .unwrap();
286 make_executable(&hook);
287
288 let refs = world.refs();
289 let operations = world.operations();
290 let (code, report) = world.sync();
291 assert_eq!(code, Some(1), "{report}");
292 assert_eq!(report["outcome"], "remote_moved");
293 assert_eq!(report["found"], theirs.as_str());
294 assert_eq!(report["pushed"], Value::Null);
295 // Nothing moved in braid, and the remote has the other push only.
296 assert_eq!(world.refs(), refs);
297 assert_eq!(world.operations(), operations);
298 assert_eq!(world.remote_head(), theirs);
299 assert!(!hook.exists());
300
301 // The next sync merges both lines and pushes the merge.
302 let (code, report) = world.sync();
303 assert_eq!(code, Some(0), "{report}");
304 assert_eq!(report["outcome"], "merged");
305 let pushed = report["pushed"].as_str().unwrap();
306 assert_eq!(world.remote_head(), pushed);
307 assert_eq!(
308 git(&world.remote, &["rev-list", "--parents", "-n", "1", "main"]),
309 format!("{pushed} {ahead} {theirs}")
310 );
311 assert_eq!(git(&world.remote, &["show", "main:a"]), "braid");
312 assert_eq!(git(&world.remote, &["show", "main:b"]), "theirs");
313 world.assert_forward_only();
314
315 let (code, again) = world.sync();
316 assert_eq!(code, Some(0));
317 assert_eq!(again["outcome"], "up_to_date");
318 assert_eq!(again["operations"], Value::Array(Vec::new()));
319}
320
321#[cfg(unix)]
322fn make_executable(path: &Path) {
323 use std::os::unix::fs::PermissionsExt;
324 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
325}
326
327#[cfg(not(unix))]
328fn make_executable(_path: &Path) {}
329
330#[test]
331fn conflicts_exit_with_2_and_change_nothing() {
332 let world = World::new();
333 world.push(&[("f", "1\n2\n3\n")], "First");
334 world.sync();
335 let (upstream, _) = world.commit("upstream", &[("f", "1\nbraid\n3\n")], "Braid");
336 assert!(
337 world
338 .braid(&["git", "import", upstream.to_str().unwrap()])
339 .status
340 .success()
341 );
342 let theirs = world.push(&[("f", "1\ngit\n3\n")], "Git");
343 let refs = world.refs();
344 let operations = world.operations();
345
346 let (code, report) = world.sync();
347 assert_eq!(code, Some(2), "{report}");
348 assert_eq!(report["outcome"], "conflicts");
349 let conflict = &report["conflicts"][0];
350 assert_eq!(conflict["path"], "f");
351 assert_eq!(conflict["kind"], "CONTENT");
352 assert_eq!(conflict["ours"]["kind"], "file");
353 assert_eq!(conflict["hunks"][0]["ours"]["text"], "braid\n");
354 assert_eq!(conflict["hunks"][0]["theirs"]["text"], "git\n");
355 assert_eq!(conflict["hunks"][0]["base"]["start"], 1);
356 assert_eq!(world.refs(), refs);
357 assert_eq!(world.operations(), operations);
358 assert_eq!(world.remote_head(), theirs);
359
360 // The text form says the same, with the same exit status.
361 let output = world.braid(&["git", "sync", world.remote.to_str().unwrap()]);
362 assert_eq!(output.status.code(), Some(2));
363 let text = String::from_utf8(output.stdout).unwrap();
364 assert!(text.contains("nothing moved"), "{text}");
365 assert!(text.contains("CONTENT f"), "{text}");
366 // And what to do: the two sides meet in git.
367 assert!(
368 text.ends_with(
369 "Merge them in git and push the merge, then sync again: https://braid.elffuss.com/agents.md shows how, under \"Keeping the git remote up to date\".\n"
370 ),
371 "{text}"
372 );
373 world.assert_forward_only();
374}
375
376#[test]
377fn a_dry_run_reports_and_writes_nothing() {
378 let world = World::new();
379 world.push(&[("a", "1\n")], "First");
380 world.sync();
381 world.push(&[("a", "2\n")], "Next");
382 let refs = world.refs();
383 let operations = world.operations();
384 let (code, report) =
385 world.braid_json(&["git", "sync", world.remote.to_str().unwrap(), "--dry-run"]);
386 assert_eq!(code, Some(0), "{report}");
387 assert_eq!(report["dry_run"], true);
388 assert_eq!(report["outcome"], "fast_forwarded");
389 assert_eq!(report["imported"], 1);
390 assert_eq!(world.refs(), refs);
391 assert_eq!(world.operations(), operations);
392
393 let output = world.braid(&["git", "sync", world.remote.to_str().unwrap(), "--dry-run"]);
394 let text = String::from_utf8(output.stdout).unwrap();
395 assert!(text.starts_with("Would fast-forward main"), "{text}");
396}
397
398#[test]
399fn a_remote_branch_by_another_name() {
400 let world = World::new();
401 world.push(&[("a", "1\n")], "First");
402 git(&world.remote, &["branch", "-m", "main", "trunk"]);
403 let (code, report) = world.braid_json(&[
404 "git",
405 "sync",
406 world.remote.to_str().unwrap(),
407 "--branch",
408 "work",
409 "--remote-branch",
410 "trunk",
411 ]);
412 assert_eq!(code, Some(0), "{report}");
413 assert_eq!(report["outcome"], "created");
414 assert_eq!(report["branch"], "work");
415 assert_eq!(report["remote_branch"], "trunk");
416 assert_eq!(world.refs()["work"], report["after"]);
417}
418
419impl World {
420 fn sync_direction(&self, direction: &str) -> (Option<i32>, Value) {
421 self.braid_json(&[
422 "git",
423 "sync",
424 self.remote.to_str().unwrap(),
425 "--direction",
426 direction,
427 ])
428 }
429
430 /// Puts braid ahead of the remote: it imports a commit the remote does
431 /// not have.
432 fn braid_ahead(&self, files: &[(&str, &str)]) {
433 let (upstream, _) = self.commit("upstream", files, "Braid's own");
434 let import = self.braid(&["git", "import", upstream.to_str().unwrap()]);
435 assert!(import.status.success());
436 }
437}
438
439#[test]
440fn publish_stops_when_someone_else_wrote_to_the_remote() {
441 let world = World::new();
442 world.push(&[("a", "1\n"), ("b", "1\n")], "First");
443 world.sync();
444 world.braid_ahead(&[("a", "braid\n")]);
445 let theirs = world.push(&[("b", "theirs\n")], "Pushed past braid");
446
447 let refs = world.refs();
448 let operations = world.operations();
449 for args in [&["--dry-run"][..], &[]] {
450 let mut command = vec!["git", "sync", world.remote.to_str().unwrap()];
451 command.extend(["--direction", "publish"]);
452 command.extend(args);
453 let (code, report) = world.braid_json(&command);
454 assert_eq!(code, Some(3), "{report}");
455 assert_eq!(report["outcome"], "diverged");
456 assert_eq!(report["direction"], "publish");
457 assert!(report["reason"].as_str().unwrap().contains("remote"));
458 assert_eq!(report["pushed"], Value::Null);
459 assert_eq!(report["operations"], Value::Array(Vec::new()));
460 }
461 // Nothing was recorded, merged or pushed.
462 assert_eq!(world.refs(), refs);
463 assert_eq!(world.operations(), operations);
464 assert_eq!(world.remote_head(), theirs);
465}
466
467#[test]
468fn publish_pushes_when_only_braid_moved() {
469 let world = World::new();
470 world.push(&[("a", "1\n")], "First");
471 world.sync();
472 world.braid_ahead(&[("a", "braid\n")]);
473 let (code, report) = world.sync_direction("publish");
474 assert_eq!(code, Some(0), "{report}");
475 assert_eq!(report["outcome"], "pushed");
476 assert_eq!(world.remote_head(), report["pushed"].as_str().unwrap());
477 world.assert_forward_only();
478}
479
480#[test]
481fn follow_takes_the_remote_in_and_stops_on_braid_work_or_a_rewind() {
482 let world = World::new();
483 let first = world.push(&[("a", "1\n")], "First");
484 world.sync();
485
486 // Only the remote moved: follow fast-forwards.
487 world.push(&[("a", "2\n")], "Second");
488 let (code, report) = world.sync_direction("follow");
489 assert_eq!(code, Some(0), "{report}");
490 assert_eq!(report["outcome"], "fast_forwarded");
491
492 // Braid has a changeset of its own: follow stops and pushes nothing.
493 let head = world.remote_head();
494 world.braid_ahead(&[("b", "braid\n")]);
495 let refs = world.refs();
496 let (code, report) = world.sync_direction("follow");
497 assert_eq!(code, Some(3), "{report}");
498 assert_eq!(report["outcome"], "diverged");
499 assert_eq!(world.refs(), refs);
500 assert_eq!(world.remote_head(), head);
501
502 // The remote went back: follow stops too.
503 let world = World::new();
504 world.push(&[("a", "1\n")], "First");
505 world.push(&[("a", "2\n")], "Second");
506 world.sync();
507 git(
508 &world.remote,
509 &["update-ref", "refs/heads/main", first.as_str()],
510 );
511 let (code, report) = world.sync_direction("follow");
512 assert_eq!(code, Some(3), "{report}");
513 assert_eq!(report["outcome"], "diverged");
514}