Elffuss BraidHub

utopia-ia/elffuss-braid public

c03d76685fb3 · 26.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! End-to-end tests of workspaces: several of them on one repository,
5//! committing and landing in any order, conflicts, the secrets guard,
6//! changesets made without a working copy, and many processes at once.
7
8use std::collections::{HashMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::process::{Command, Output, Stdio};
11
12use serde_json::Value;
13
14const AUTHOR: &str = "Ada <ada@example.org>";
15
16/// A repository in a temporary directory, driven through the binary.
17struct Repo {
18 _temp: tempfile::TempDir,
19 root: PathBuf,
20}
21
22impl Repo {
23 fn new() -> Repo {
24 let temp = tempfile::tempdir().unwrap();
25 // Canonical, so paths compare equal to what braid records.
26 let base = std::fs::canonicalize(temp.path()).unwrap();
27 let root = base.join("repo");
28 let out = braid(&base, &["init", root.to_str().unwrap()]);
29 assert!(out.status.success(), "{}", stderr(&out));
30 Repo { _temp: temp, root }
31 }
32
33 /// Creates a workspace next to the repository's own directory.
34 fn workspace(&self, name: &str) -> PathBuf {
35 let dir = self.root.parent().unwrap().join(name);
36 json(
37 &self.root,
38 &["workspace", "add", name, dir.to_str().unwrap()],
39 );
40 dir
41 }
42
43 fn main(&self) -> Option<String> {
44 json(&self.root, &["refs"])["refs"]["main"]
45 .as_str()
46 .map(str::to_owned)
47 }
48
49 fn fsck_is_clean(&self) -> bool {
50 json(&self.root, &["fsck"])["clean"] == true
51 }
52}
53
54/// Runs braid in `dir` with a fixed author and agent.
55fn braid(dir: &Path, args: &[&str]) -> Output {
56 Command::new(env!("CARGO_BIN_EXE_braid"))
57 .current_dir(dir)
58 .args(args)
59 .env("BRAID_AUTHOR", AUTHOR)
60 .env("BRAID_AGENT", "tester")
61 .output()
62 .unwrap()
63}
64
65fn stderr(out: &Output) -> String {
66 String::from_utf8_lossy(&out.stderr).into_owned()
67}
68
69/// Runs braid with `--json`, expecting exit status `code`.
70fn json_status(dir: &Path, args: &[&str], code: i32) -> Value {
71 let mut all = args.to_vec();
72 all.push("--json");
73 let out = braid(dir, &all);
74 assert_eq!(
75 out.status.code(),
76 Some(code),
77 "braid {args:?}: {}{}",
78 String::from_utf8_lossy(&out.stdout),
79 stderr(&out)
80 );
81 serde_json::from_slice(&out.stdout).unwrap()
82}
83
84fn json(dir: &Path, args: &[&str]) -> Value {
85 json_status(dir, args, 0)
86}
87
88/// Runs braid expecting failure, and returns its error message.
89fn fails(dir: &Path, args: &[&str]) -> String {
90 let out = braid(dir, args);
91 assert_eq!(out.status.code(), Some(1), "braid {args:?} should fail");
92 stderr(&out)
93}
94
95fn write(dir: &Path, name: &str, content: &str) {
96 let path = dir.join(name);
97 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
98 std::fs::write(path, content).unwrap();
99}
100
101fn read(dir: &Path, name: &str) -> String {
102 std::fs::read_to_string(dir.join(name)).unwrap()
103}
104
105/// Seeds `main` with these files, through `change create`.
106fn seed(repo: &Repo, files: &[(&str, &str)]) -> String {
107 let mut args = vec![
108 "change".to_owned(),
109 "create".to_owned(),
110 "--base".to_owned(),
111 "none".to_owned(),
112 ];
113 for (name, content) in files {
114 let source = repo
115 .root
116 .parent()
117 .unwrap()
118 .join(format!("seed-{}", name.replace('/', "-")));
119 std::fs::write(&source, content).unwrap();
120 args.push("--set".to_owned());
121 args.push(format!("{name}=@{}", source.display()));
122 }
123 args.extend(["-m", "seed", "--land", "main"].map(str::to_owned));
124 let args: Vec<&str> = args.iter().map(String::as_str).collect();
125 let out = json(&repo.root, &args);
126 out["change"].as_str().unwrap().to_owned()
127}
128
129fn status(dir: &Path) -> Value {
130 json(dir, &["status"])
131}
132
133/// Every changeset on `main`'s first-parent chain, newest first.
134fn history(repo: &Repo) -> Vec<Value> {
135 json(&repo.root, &["log", "main", "-n", "100000"])
136 .as_array()
137 .unwrap()
138 .clone()
139}
140
141fn rebased_from(changeset: &Value) -> Option<String> {
142 changeset["extras"]
143 .as_array()
144 .unwrap()
145 .iter()
146 .find_map(|pair| (pair[0] == "rebased-from").then(|| pair[1].as_str().unwrap().to_owned()))
147}
148
149#[test]
150fn disjoint_workspaces_land_in_either_order() {
151 for a_first in [true, false] {
152 let repo = Repo::new();
153 seed(&repo, &[("README.md", "hello\n")]);
154 let a = repo.workspace("a");
155 let b = repo.workspace("b");
156 assert_eq!(read(&a, "README.md"), "hello\n");
157
158 write(&a, "src/a.rs", "pub fn a() {}\n");
159 write(&b, "docs/b.md", "# b\n");
160 let a_commit = json(&a, &["commit", "-m", "add a"]);
161 let b_commit = json(&b, &["commit", "-m", "add b"]);
162 assert_eq!(a_commit["changes"], 1);
163
164 let (first, second) = if a_first { (&a, &b) } else { (&b, &a) };
165 let landed = json(first, &["land"]);
166 assert_eq!(landed["outcome"], "fast-forward");
167 let landed = json(second, &["land"]);
168 assert_eq!(landed["outcome"], "rebased");
169 assert_eq!(landed["previous"], json(first, &["status"])["base"]);
170
171 // Both changes are on main, once each, on a linear history.
172 let log = history(&repo);
173 assert_eq!(log.len(), 3);
174 assert!(
175 log.iter()
176 .all(|c| c["parents"].as_array().unwrap().len() <= 1)
177 );
178 let originals: HashSet<String> = log[..2]
179 .iter()
180 .map(|c| rebased_from(c).unwrap_or_else(|| c["id"].as_str().unwrap().to_owned()))
181 .collect();
182 let made: HashSet<String> = [&a_commit, &b_commit]
183 .iter()
184 .map(|c| c["changeset"].as_str().unwrap().to_owned())
185 .collect();
186 assert_eq!(originals, made);
187
188 // The second workspace has both files; the first catches up.
189 assert_eq!(read(second, "src/a.rs"), "pub fn a() {}\n");
190 assert_eq!(read(second, "docs/b.md"), "# b\n");
191 assert_eq!(json(first, &["update"])["outcome"], "moved");
192 assert_eq!(read(first, "docs/b.md"), "# b\n");
193 assert_eq!(read(first, "src/a.rs"), "pub fn a() {}\n");
194 for dir in [&a, &b] {
195 let now = status(dir);
196 assert_eq!(now["clean"], true);
197 assert_eq!(now["base"].as_str(), repo.main().as_deref());
198 }
199 assert!(repo.fsck_is_clean());
200 }
201}
202
203#[test]
204fn same_lines_conflict_then_resolve() {
205 let repo = Repo::new();
206 seed(&repo, &[("shared.txt", "one\ntwo\nthree\n")]);
207 let a = repo.workspace("a");
208 let b = repo.workspace("b");
209 write(&a, "shared.txt", "one\nTWO from a\nthree\n");
210 write(&b, "shared.txt", "one\nTWO from b\nthree\n");
211 json(&a, &["commit", "-m", "a's two"]);
212 json(&b, &["commit", "-m", "b's two"]);
213 json(&a, &["land"]);
214 let main_before = repo.main();
215
216 // The second landing conflicts: exit status 2, and main does not move.
217 let landed = json_status(&b, &["land"], 2);
218 assert_eq!(landed["outcome"], "conflicts");
219 let conflict = &landed["conflicts"][0];
220 assert_eq!(conflict["path"], "shared.txt");
221 assert_eq!(conflict["kind"], "CONTENT");
222 assert_eq!(conflict["hunks"][0]["ours"]["text"], "TWO from a\n");
223 assert_eq!(conflict["hunks"][0]["theirs"]["text"], "TWO from b\n");
224 assert_eq!(conflict["base"]["kind"], "file");
225 assert_eq!(repo.main(), main_before);
226
227 // Update writes the conflict with markers, and a rebase is in progress.
228 let updated = json_status(&b, &["update"], 2);
229 assert_eq!(updated["outcome"], "conflicts");
230 let merged = read(&b, "shared.txt");
231 assert!(merged.contains("<<<<<<< main"), "{merged}");
232 assert!(
233 merged.contains("TWO from a\n=======\nTWO from b\n"),
234 "{merged}"
235 );
236 let now = status(&b);
237 assert_eq!(now["rebase"]["conflicts"][0]["markers_remain"], true);
238 assert_eq!(now["base"].as_str(), main_before.as_deref());
239 // Landing waits for the rebase.
240 assert!(fails(&b, &["land"]).contains("rebase is in progress"));
241
242 // Committing with the markers still there is refused.
243 let refused = fails(&b, &["commit", "-m", "resolved"]);
244 assert!(refused.contains("conflict markers remain"), "{refused}");
245
246 write(&b, "shared.txt", "one\nTWO from a and b\nthree\n");
247 let committed = json(&b, &["commit", "-m", "both twos"]);
248 assert_eq!(committed["rebase"]["outcome"], "finished");
249 let landed = json(&b, &["land"]);
250 assert_eq!(landed["outcome"], "fast-forward");
251 assert_eq!(repo.main().as_deref(), committed["changeset"].as_str());
252 // The resolution's first parent is a's change, and it names the change
253 // it resolves.
254 let log = history(&repo);
255 assert_eq!(log[0]["parents"][0].as_str(), main_before.as_deref());
256 assert!(rebased_from(&log[0]).is_some());
257 assert_eq!(read(&b, "shared.txt"), "one\nTWO from a and b\nthree\n");
258 assert!(repo.fsck_is_clean());
259}
260
261#[test]
262fn landing_after_main_moved_rebases_and_follows_the_tree() {
263 let repo = Repo::new();
264 seed(&repo, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
265 let ws = repo.workspace("ws");
266 // Main moves without this workspace: a disjoint change, made without a
267 // working copy.
268 let main = repo.main().unwrap();
269 let elsewhere = repo.root.parent().unwrap().join("other.txt");
270 std::fs::write(&elsewhere, "from elsewhere\n").unwrap();
271 json(
272 &repo.root,
273 &[
274 "change",
275 "create",
276 "--base",
277 &main,
278 "--set",
279 &format!("dir/other.txt=@{}", elsewhere.display()),
280 "--delete",
281 "b.txt",
282 "-m",
283 "elsewhere",
284 "--land",
285 "main",
286 ],
287 );
288 write(&ws, "a.txt", "a, edited\n");
289 let committed = json(&ws, &["commit", "-m", "edit a"]);
290 let landed = json(&ws, &["land"]);
291 assert_eq!(landed["outcome"], "rebased");
292 let head = landed["head"].as_str().unwrap().to_owned();
293 assert_eq!(repo.main().as_deref(), Some(head.as_str()));
294 assert_ne!(Some(head.as_str()), committed["changeset"].as_str());
295
296 // The working copy is the landed tree: main's change came in, the
297 // deleted file went away, and nothing is left to commit.
298 assert_eq!(read(&ws, "dir/other.txt"), "from elsewhere\n");
299 assert!(!ws.join("b.txt").exists());
300 assert_eq!(read(&ws, "a.txt"), "a, edited\n");
301 let now = status(&ws);
302 assert_eq!(now["clean"], true);
303 assert_eq!(now["base"].as_str(), Some(head.as_str()));
304 let show = json(&repo.root, &["show", &head]);
305 let paths: Vec<&str> = show["changes"]
306 .as_array()
307 .unwrap()
308 .iter()
309 .map(|c| c["path"].as_str().unwrap())
310 .collect();
311 assert_eq!(paths, ["a.txt"]);
312 assert!(repo.fsck_is_clean());
313}
314
315#[test]
316fn the_secrets_guard() {
317 let repo = Repo::new();
318 seed(&repo, &[("README.md", "hello\n")]);
319 let ws = repo.workspace("ws");
320 write(&ws, ".env", "TOKEN=secret\n");
321 write(&ws, "keys/server.pem", "-----BEGIN-----\n");
322 write(&ws, "keys/id_ed25519", "private\n");
323 std::fs::write(ws.join("big.bin"), vec![7u8; (1 << 20) + 1]).unwrap();
324 write(&ws, "notes.txt", "fine\n");
325
326 let now = status(&ws);
327 assert_eq!(now["added"], serde_json::json!(["notes.txt"]));
328 assert_eq!(
329 now["needs_track"],
330 serde_json::json!([".env", "big.bin", "keys/id_ed25519", "keys/server.pem"])
331 );
332 // Only the ordinary file is committed.
333 let committed = json(&ws, &["commit", "-m", "notes"]);
334 assert_eq!(committed["changes"], 1);
335 let show = json(
336 &repo.root,
337 &["show", committed["changeset"].as_str().unwrap()],
338 );
339 assert_eq!(show["changes"].as_array().unwrap().len(), 1);
340 // Guarded files are not uncommitted changes: landing goes ahead.
341 json(&ws, &["land"]);
342
343 // Marked, they are committed.
344 json(&ws, &["track", ".env", "keys"]);
345 let now = status(&ws);
346 assert_eq!(now["needs_track"], serde_json::json!(["big.bin"]));
347 assert_eq!(
348 now["added"],
349 serde_json::json!([".env", "keys/id_ed25519", "keys/server.pem"])
350 );
351 let committed = json(&ws, &["commit", "-m", "keys"]);
352 assert_eq!(committed["changes"], 3);
353 assert_eq!(status(&ws)["needs_track"], serde_json::json!(["big.bin"]));
354 // Nothing else to commit while only guarded files remain.
355 assert!(fails(&ws, &["commit", "-m", "nothing"]).contains("nothing to commit"));
356}
357
358#[test]
359fn change_create_with_expectations() {
360 let repo = Repo::new();
361 let seeded = seed(&repo, &[("config.toml", "a = 1\n")]);
362 let show = json(&repo.root, &["show", &seeded]);
363 let blob = show["changes"][0]["blob"].as_str().unwrap().to_owned();
364 let new = repo.root.parent().unwrap().join("new.toml");
365 std::fs::write(&new, "a = 2\n").unwrap();
366 let set = format!("config.toml=@{}", new.display());
367
368 // The expectation matches: made and landed.
369 let made = json(
370 &repo.root,
371 &[
372 "change",
373 "create",
374 "--base",
375 "main",
376 "--set",
377 &set,
378 "--expect",
379 &format!("config.toml={blob}"),
380 "--expect",
381 "other.toml=absent",
382 "-m",
383 "a is 2",
384 "--land",
385 "main",
386 ],
387 );
388 assert_eq!(made["land"]["outcome"], "fast-forward");
389 assert_eq!(repo.main().as_deref(), made["change"].as_str());
390
391 // Another agent, still believing the old content, is stopped before
392 // anything is made: its base holds another blob now.
393 let ops = json(&repo.root, &["op", "log"]).as_array().unwrap().len();
394 let refused = fails(
395 &repo.root,
396 &[
397 "change",
398 "create",
399 "--base",
400 "main",
401 "--set",
402 &set,
403 "--expect",
404 &format!("config.toml={blob}"),
405 "-m",
406 "stale",
407 "--land",
408 "main",
409 ],
410 );
411 assert!(refused.contains("expected"), "{refused}");
412 let refused = fails(
413 &repo.root,
414 &[
415 "change",
416 "create",
417 "--base",
418 "main",
419 "--set",
420 &set,
421 "--expect",
422 "config.toml=absent",
423 "-m",
424 "stale",
425 ],
426 );
427 assert!(refused.contains("absent"), "{refused}");
428 assert_eq!(repo.main().as_deref(), made["change"].as_str());
429 assert_eq!(
430 json(&repo.root, &["op", "log"]).as_array().unwrap().len(),
431 ops
432 );
433
434 // Built on the old base and landed now, the stale edit conflicts: exit
435 // status 2, and main stays.
436 let stale = repo.root.parent().unwrap().join("stale.toml");
437 std::fs::write(&stale, "a = 3\n").unwrap();
438 let conflicted = json_status(
439 &repo.root,
440 &[
441 "change",
442 "create",
443 "--base",
444 &seeded,
445 "--set",
446 &format!("config.toml=@{}", stale.display()),
447 "-m",
448 "a is 3",
449 "--land",
450 "main",
451 ],
452 2,
453 );
454 assert_eq!(conflicted["land"]["outcome"], "conflicts");
455 assert_eq!(conflicted["land"]["conflicts"][0]["kind"], "CONTENT");
456 assert_eq!(repo.main().as_deref(), made["change"].as_str());
457
458 // Content from standard input.
459 let mut child = Command::new(env!("CARGO_BIN_EXE_braid"))
460 .current_dir(&repo.root)
461 .args([
462 "change",
463 "create",
464 "--base",
465 "main",
466 "--set",
467 "piped.txt=@-",
468 "-m",
469 "piped",
470 "--json",
471 ])
472 .env("BRAID_AUTHOR", AUTHOR)
473 .stdin(Stdio::piped())
474 .stdout(Stdio::piped())
475 .spawn()
476 .unwrap();
477 std::io::Write::write_all(&mut child.stdin.take().unwrap(), b"from a pipe\n").unwrap();
478 let out = child.wait_with_output().unwrap();
479 assert!(out.status.success());
480 let piped: Value = serde_json::from_slice(&out.stdout).unwrap();
481 let shown = json(&repo.root, &["show", piped["change"].as_str().unwrap()]);
482 assert_eq!(shown["changes"][0]["path"], "piped.txt");
483 assert_eq!(shown["changes"][0]["size"], 12);
484 assert!(repo.fsck_is_clean());
485}
486
487#[test]
488fn the_short_id_commit_prints_works_everywhere() {
489 let repo = Repo::new();
490 seed(&repo, &[("README.md", "hello\n")]);
491 let ws = repo.workspace("ws");
492 write(&ws, "notes.txt", "notes\n");
493 let out = braid(&ws, &["commit", "-m", "notes"]);
494 assert!(out.status.success(), "{}", stderr(&out));
495 let text = String::from_utf8(out.stdout).unwrap();
496 assert!(text.starts_with("Committed "), "{text}");
497 let short = text.split_whitespace().nth(1).unwrap().to_owned();
498 assert_eq!(short.len(), 12, "{text}");
499
500 // show and log take it, and give the full id in JSON.
501 let shown = json(&repo.root, &["show", &short]);
502 let full = shown["id"].as_str().unwrap().to_owned();
503 assert_eq!(full.len(), 64);
504 assert!(full.starts_with(&short));
505 assert_eq!(
506 json(&repo.root, &["log", &short[..6], "-n", "1"])[0]["id"],
507 full.as_str()
508 );
509 // So do --at and --base.
510 let other = repo.root.parent().unwrap().join("other");
511 let added = json(
512 &repo.root,
513 &[
514 "workspace",
515 "add",
516 "other",
517 other.to_str().unwrap(),
518 "--at",
519 &short[..8],
520 ],
521 );
522 assert_eq!(added["base"], full.as_str());
523 assert_eq!(read(&other, "notes.txt"), "notes\n");
524 let made = json(
525 &repo.root,
526 &[
527 "change",
528 "create",
529 "--base",
530 &short[..7],
531 "--delete",
532 "notes.txt",
533 "-m",
534 "no notes",
535 ],
536 );
537 assert_eq!(made["base"], full.as_str());
538 // commit --json gives the full id.
539 write(&ws, "more.txt", "more\n");
540 let committed = json(&ws, &["commit", "-m", "more"]);
541 assert_eq!(committed["changeset"].as_str().unwrap().len(), 64);
542}
543
544#[test]
545fn removing_a_workspace() {
546 let repo = Repo::new();
547 seed(&repo, &[("README.md", "hello\n")]);
548 let ws = repo.workspace("ws");
549 write(&ws, "draft.txt", "not committed\n");
550 let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
551 assert!(refused.contains("uncommitted changes"), "{refused}");
552 assert!(ws.join("draft.txt").exists());
553
554 // Committed but not landed: still refused.
555 json(&ws, &["commit", "-m", "draft"]);
556 let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
557 assert!(refused.contains("does not have"), "{refused}");
558
559 // Landed: removed, directory and all.
560 json(&ws, &["land"]);
561 json(&repo.root, &["workspace", "remove", "ws"]);
562 assert!(!ws.exists());
563 assert!(
564 json(&repo.root, &["workspace", "list"])
565 .as_array()
566 .unwrap()
567 .is_empty()
568 );
569
570 // --force removes a dirty one.
571 let other = repo.workspace("other");
572 write(&other, "scratch.txt", "x\n");
573 json(&repo.root, &["workspace", "remove", "other", "--force"]);
574 assert!(!other.exists());
575}
576
577#[test]
578fn workspaces_are_found_from_anywhere_inside() {
579 let repo = Repo::new();
580 seed(&repo, &[("src/lib.rs", "pub fn f() {}\n")]);
581 let ws = repo.workspace("ws");
582 let inside = ws.join("src");
583 write(&ws, "src/lib.rs", "pub fn g() {}\n");
584 let now = status(&inside);
585 assert_eq!(now["workspace"], "ws");
586 assert_eq!(now["modified"], serde_json::json!(["src/lib.rs"]));
587 // Paths are relative to the current directory.
588 write(&ws, "src/new.rs", "x\n");
589 write(&ws, "top.txt", "y\n");
590 let committed = json(&inside, &["commit", "-m", "only src", "new.rs", "lib.rs"]);
591 assert_eq!(committed["changes"], 2);
592 assert_eq!(status(&ws)["added"], serde_json::json!(["top.txt"]));
593 // The repository root is not a workspace.
594 assert!(fails(&repo.root, &["status"]).contains("not inside a workspace"));
595 // --workspace names one from anywhere in the repository.
596 assert_eq!(
597 json(&repo.root, &["status", "--workspace", "ws"])["workspace"],
598 "ws"
599 );
600}
601
602#[test]
603fn stacked_changesets_land_in_order() {
604 let repo = Repo::new();
605 seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]);
606 let ws = repo.workspace("ws");
607 let other = repo.workspace("other");
608 write(&ws, "a.txt", "2\n");
609 let first = json(&ws, &["commit", "-m", "first"]);
610 write(&ws, "a.txt", "3\n");
611 let second = json(&ws, &["commit", "-m", "second"]);
612 assert_eq!(status(&ws)["unlanded"].as_array().unwrap().len(), 2);
613 write(&other, "b.txt", "other\n");
614 json(&other, &["commit", "-m", "other"]);
615 json(&other, &["land"]);
616
617 // Both are rebased onto the other workspace's change, in order.
618 let landed = json(&ws, &["land"]);
619 assert_eq!(landed["outcome"], "rebased");
620 let log = history(&repo);
621 let messages: Vec<&str> = log.iter().map(|c| c["message"].as_str().unwrap()).collect();
622 assert_eq!(messages, ["second", "first", "other", "seed"]);
623 assert_eq!(
624 rebased_from(&log[0]).as_deref(),
625 second["changeset"].as_str()
626 );
627 assert_eq!(
628 rebased_from(&log[1]).as_deref(),
629 first["changeset"].as_str()
630 );
631 assert_eq!(read(&ws, "a.txt"), "3\n");
632 assert_eq!(read(&ws, "b.txt"), "other\n");
633 assert!(repo.fsck_is_clean());
634}
635
636#[test]
637fn a_conflict_that_is_not_about_content_needs_resolve() {
638 let repo = Repo::new();
639 seed(&repo, &[("gone.txt", "1\n"), ("keep.txt", "k\n")]);
640 let a = repo.workspace("a");
641 let b = repo.workspace("b");
642 std::fs::remove_file(a.join("gone.txt")).unwrap();
643 json(&a, &["commit", "-m", "delete it"]);
644 json(&a, &["land"]);
645 write(&b, "gone.txt", "2\n");
646 json(&b, &["commit", "-m", "edit it"]);
647 let updated = json_status(&b, &["update"], 2);
648 assert_eq!(updated["conflicts"][0]["kind"], "MODIFY_DELETE");
649 // The head's version stays: deleted.
650 assert!(!b.join("gone.txt").exists());
651 let refused = fails(&b, &["commit", "-m", "x"]);
652 assert!(refused.contains("braid resolve"), "{refused}");
653 let resolved = json(&b, &["resolve", "gone.txt"]);
654 assert!(resolved["remaining"].as_array().unwrap().is_empty());
655 // Keeping the deletion leaves nothing of the change: the rebase ends
656 // without a changeset.
657 let committed = json(&b, &["commit"]);
658 assert!(committed["changeset"].is_null());
659 assert_eq!(committed["rebase"]["outcome"], "finished");
660 assert_eq!(status(&b)["base"].as_str(), repo.main().as_deref());
661 assert_eq!(json(&b, &["land"])["outcome"], "nothing");
662}
663
664/// Eight processes, each with its own workspace, edit their own file and
665/// their own line of a shared file, commit and land, round after round,
666/// all at once. Afterwards every change is on main exactly once, main's
667/// history is linear, and the store is clean.
668#[test]
669fn eight_agents_land_at_once() {
670 const AGENTS: usize = 8;
671 const ROUNDS: usize = 4;
672 let repo = Repo::new();
673 // One line per agent, with two untouched lines between them, so that
674 // edits to different agents' lines merge.
675 let shared: String = (0..AGENTS)
676 .map(|i| format!("agent {i}: start\n--\n--\n"))
677 .collect();
678 seed(&repo, &[("shared.txt", &shared)]);
679 let dirs: Vec<PathBuf> = (0..AGENTS)
680 .map(|i| repo.workspace(&format!("agent-{i}")))
681 .collect();
682
683 let made: Vec<Vec<String>> = std::thread::scope(|scope| {
684 let handles: Vec<_> = dirs
685 .iter()
686 .enumerate()
687 .map(|(i, dir)| {
688 scope.spawn(move || {
689 let mut commits = Vec::new();
690 for round in 0..ROUNDS {
691 write(
692 dir,
693 &format!("own-{i}.txt"),
694 &format!("agent {i} round {round}\n"),
695 );
696 let text = read(dir, "shared.txt");
697 let lines: Vec<String> = text
698 .lines()
699 .enumerate()
700 .map(|(n, line)| {
701 if n == i * 3 {
702 format!("agent {i}: round {round}")
703 } else {
704 line.to_owned()
705 }
706 })
707 .collect();
708 write(dir, "shared.txt", &(lines.join("\n") + "\n"));
709 let committed =
710 json(dir, &["commit", "-m", &format!("agent {i} round {round}")]);
711 commits.push(committed["changeset"].as_str().unwrap().to_owned());
712 loop {
713 let out = braid(dir, &["land", "--json"]);
714 match out.status.code() {
715 Some(0) => break,
716 Some(2) => {
717 // Someone else's change got in the way:
718 // rebase onto it and try again.
719 json(dir, &["update"]);
720 }
721 _ => panic!("land failed: {}", stderr(&out)),
722 }
723 }
724 }
725 commits
726 })
727 })
728 .collect();
729 handles.into_iter().map(|h| h.join().unwrap()).collect()
730 });
731
732 // Every changeset on main maps back to one of the changesets made,
733 // through the rebases it went through.
734 let log = history(&repo);
735 assert_eq!(log.len(), AGENTS * ROUNDS + 1);
736 let mut seen = HashMap::new();
737 for changeset in &log[..log.len() - 1] {
738 assert_eq!(changeset["parents"].as_array().unwrap().len(), 1, "a merge");
739 let mut id = changeset["id"].as_str().unwrap().to_owned();
740 let mut current = changeset.clone();
741 while let Some(from) = rebased_from(&current) {
742 current = json(&repo.root, &["show", &from]);
743 id = from;
744 }
745 *seen.entry(id).or_insert(0) += 1;
746 }
747 let all: HashSet<String> = made.iter().flatten().cloned().collect();
748 assert_eq!(all.len(), AGENTS * ROUNDS);
749 assert_eq!(seen.keys().cloned().collect::<HashSet<_>>(), all);
750 assert!(seen.values().all(|count| *count == 1), "{seen:?}");
751
752 // A fresh workspace has every agent's last round.
753 let check = repo.workspace("check");
754 let text = read(&check, "shared.txt");
755 for i in 0..AGENTS {
756 assert_eq!(
757 read(&check, &format!("own-{i}.txt")),
758 format!("agent {i} round {}\n", ROUNDS - 1)
759 );
760 assert!(
761 text.contains(&format!("agent {i}: round {}\n", ROUNDS - 1)),
762 "{text}"
763 );
764 }
765 assert!(repo.fsck_is_clean());
766}