Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 41.2 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 braid_as("tester", dir, args)
57}
58
59/// Runs braid in `dir` with a fixed author, as the agent `agent`.
60fn braid_as(agent: &str, dir: &Path, args: &[&str]) -> Output {
61 Command::new(env!("CARGO_BIN_EXE_braid"))
62 .current_dir(dir)
63 .args(args)
64 .env("BRAID_AUTHOR", AUTHOR)
65 .env("BRAID_AGENT", agent)
66 .output()
67 .unwrap()
68}
69
70/// Runs braid with `--json` as the agent `agent`, expecting exit status
71/// `code`.
72fn json_as(agent: &str, dir: &Path, args: &[&str], code: i32) -> Value {
73 let mut all = args.to_vec();
74 all.push("--json");
75 let out = braid_as(agent, dir, &all);
76 assert_eq!(
77 out.status.code(),
78 Some(code),
79 "braid {args:?}: {}{}",
80 String::from_utf8_lossy(&out.stdout),
81 stderr(&out)
82 );
83 serde_json::from_slice(&out.stdout).unwrap()
84}
85
86fn stderr(out: &Output) -> String {
87 String::from_utf8_lossy(&out.stderr).into_owned()
88}
89
90/// Runs braid with `--json`, expecting exit status `code`.
91fn json_status(dir: &Path, args: &[&str], code: i32) -> Value {
92 json_as("tester", dir, args, code)
93}
94
95fn json(dir: &Path, args: &[&str]) -> Value {
96 json_status(dir, args, 0)
97}
98
99/// Runs braid expecting failure, and returns its error message.
100fn fails(dir: &Path, args: &[&str]) -> String {
101 let out = braid(dir, args);
102 assert_eq!(out.status.code(), Some(1), "braid {args:?} should fail");
103 stderr(&out)
104}
105
106fn write(dir: &Path, name: &str, content: &str) {
107 let path = dir.join(name);
108 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
109 std::fs::write(path, content).unwrap();
110}
111
112fn read(dir: &Path, name: &str) -> String {
113 std::fs::read_to_string(dir.join(name)).unwrap()
114}
115
116/// Seeds `main` with these files, through `change create`.
117fn seed(repo: &Repo, files: &[(&str, &str)]) -> String {
118 let mut args = vec![
119 "change".to_owned(),
120 "create".to_owned(),
121 "--base".to_owned(),
122 "none".to_owned(),
123 ];
124 for (name, content) in files {
125 let source = repo
126 .root
127 .parent()
128 .unwrap()
129 .join(format!("seed-{}", name.replace('/', "-")));
130 std::fs::write(&source, content).unwrap();
131 args.push("--set".to_owned());
132 args.push(format!("{name}=@{}", source.display()));
133 }
134 args.extend(["-m", "seed", "--land", "main"].map(str::to_owned));
135 let args: Vec<&str> = args.iter().map(String::as_str).collect();
136 let out = json(&repo.root, &args);
137 out["change"].as_str().unwrap().to_owned()
138}
139
140fn status(dir: &Path) -> Value {
141 json(dir, &["status"])
142}
143
144/// Every changeset on `main`'s first-parent chain, newest first.
145fn history(repo: &Repo) -> Vec<Value> {
146 json(&repo.root, &["log", "main", "-n", "100000"])
147 .as_array()
148 .unwrap()
149 .clone()
150}
151
152fn rebased_from(changeset: &Value) -> Option<String> {
153 changeset["extras"]
154 .as_array()
155 .unwrap()
156 .iter()
157 .find_map(|pair| (pair[0] == "rebased-from").then(|| pair[1].as_str().unwrap().to_owned()))
158}
159
160#[test]
161fn disjoint_workspaces_land_in_either_order() {
162 for a_first in [true, false] {
163 let repo = Repo::new();
164 seed(&repo, &[("README.md", "hello\n")]);
165 let a = repo.workspace("a");
166 let b = repo.workspace("b");
167 assert_eq!(read(&a, "README.md"), "hello\n");
168
169 write(&a, "src/a.rs", "pub fn a() {}\n");
170 write(&b, "docs/b.md", "# b\n");
171 let a_commit = json(&a, &["commit", "-m", "add a"]);
172 let b_commit = json(&b, &["commit", "-m", "add b"]);
173 assert_eq!(a_commit["changes"], 1);
174
175 let (first, second) = if a_first { (&a, &b) } else { (&b, &a) };
176 let landed = json(first, &["land"]);
177 assert_eq!(landed["outcome"], "fast-forward");
178 let before = status(second);
179 assert_eq!(before["behind"], true);
180 assert_eq!(before["behind_by"], 1);
181 assert_eq!(before["unlanded"].as_array().unwrap().len(), 1);
182 let landed = json(second, &["land"]);
183 assert_eq!(landed["outcome"], "rebased");
184 assert_eq!(landed["head_before"], json(first, &["status"])["base"]);
185 // Now the first one is behind, by the second's change.
186 let behind = status(first);
187 assert_eq!(behind["behind"], true);
188 assert_eq!(behind["behind_by"], 1);
189 assert_eq!(behind["unlanded"], serde_json::json!([]));
190
191 // Both changes are on main, once each, on a linear history.
192 let log = history(&repo);
193 assert_eq!(log.len(), 3);
194 assert!(
195 log.iter()
196 .all(|c| c["parents"].as_array().unwrap().len() <= 1)
197 );
198 let originals: HashSet<String> = log[..2]
199 .iter()
200 .map(|c| rebased_from(c).unwrap_or_else(|| c["id"].as_str().unwrap().to_owned()))
201 .collect();
202 let made: HashSet<String> = [&a_commit, &b_commit]
203 .iter()
204 .map(|c| c["changeset"].as_str().unwrap().to_owned())
205 .collect();
206 assert_eq!(originals, made);
207
208 // The second workspace has both files; the first catches up.
209 assert_eq!(read(second, "src/a.rs"), "pub fn a() {}\n");
210 assert_eq!(read(second, "docs/b.md"), "# b\n");
211 assert_eq!(json(first, &["update"])["outcome"], "moved");
212 assert_eq!(read(first, "docs/b.md"), "# b\n");
213 assert_eq!(read(first, "src/a.rs"), "pub fn a() {}\n");
214 for dir in [&a, &b] {
215 let now = status(dir);
216 assert_eq!(now["clean"], true);
217 assert_eq!(now["base"].as_str(), repo.main().as_deref());
218 }
219 assert!(repo.fsck_is_clean());
220 }
221}
222
223#[test]
224fn same_lines_conflict_then_resolve() {
225 let repo = Repo::new();
226 seed(&repo, &[("shared.txt", "one\ntwo\nthree\n")]);
227 let a = repo.workspace("a");
228 let b = repo.workspace("b");
229 write(&a, "shared.txt", "one\nTWO from a\nthree\n");
230 write(&b, "shared.txt", "one\nTWO from b\nthree\n");
231 json(&a, &["commit", "-m", "a's two"]);
232 let b_change = json(&b, &["commit", "-m", "b's two"]);
233 assert_eq!(b_change["message_replaced"], false);
234 json(&a, &["land"]);
235 let main_before = repo.main();
236
237 // The second landing conflicts: exit status 2, and main does not move.
238 let landed = json_status(&b, &["land"], 2);
239 assert_eq!(landed["outcome"], "conflicts");
240 let conflict = &landed["conflicts"][0];
241 assert_eq!(conflict["path"], "shared.txt");
242 assert_eq!(conflict["kind"], "CONTENT");
243 assert_eq!(conflict["hunks"][0]["branch"]["text"], "TWO from a\n");
244 assert_eq!(conflict["hunks"][0]["workspace"]["text"], "TWO from b\n");
245 assert_eq!(conflict["base"]["kind"], "file");
246 assert_eq!(conflict["branch"]["kind"], "file");
247 assert!(conflict.get("ours").is_none() && conflict.get("theirs").is_none());
248 assert_eq!(landed["next"], "braid update");
249 assert_eq!(repo.main(), main_before);
250
251 // Update writes the conflict with markers, and a rebase is in progress.
252 let updated = json_status(&b, &["update"], 2);
253 assert_eq!(updated["outcome"], "conflicts");
254 let merged = read(&b, "shared.txt");
255 assert!(merged.contains("<<<<<<< main"), "{merged}");
256 assert!(
257 merged.contains("TWO from a\n=======\nTWO from b\n"),
258 "{merged}"
259 );
260 assert_eq!(updated["next"], "braid commit");
261 assert_eq!(updated["updated_paths"], serde_json::json!(["shared.txt"]));
262 let now = status(&b);
263 assert_eq!(now["rebase"]["conflicts"][0]["markers_remain"], true);
264 assert_eq!(now["base"].as_str(), main_before.as_deref());
265 // The changeset being rebased has not landed yet.
266 assert_eq!(now["unlanded"], serde_json::json!([b_change["changeset"]]));
267 assert_eq!(now["behind"], false);
268 assert_eq!(now["behind_by"], 0);
269 // Nor can it be committed while the markers are there: status and
270 // commit give the same reason.
271 assert_eq!(now["ready_to_commit"], false);
272 assert_eq!(now["blocking"][0]["reason"], "markers");
273 assert_eq!(now["blocking"][0]["path"], "shared.txt");
274 assert_eq!(now["blocking"][0]["kind"], "CONTENT");
275 let reason = now["blocking"][0]["message"].as_str().unwrap();
276 let refused = fails(&b, &["commit", "-m", "resolved"]);
277 assert!(refused.contains("conflict markers remain"), "{refused}");
278 assert!(refused.contains(reason), "{refused}");
279 // Landing waits for the rebase.
280 assert!(fails(&b, &["land"]).contains("rebase is in progress"));
281
282 write(&b, "shared.txt", "one\nTWO from a and b\nthree\n");
283 let now = status(&b);
284 assert_eq!(now["ready_to_commit"], true);
285 assert_eq!(now["blocking"], serde_json::json!([]));
286 // A message given replaces the rebased changeset's own.
287 let committed = json(&b, &["commit", "-m", "both twos"]);
288 assert_eq!(committed["message_replaced"], true);
289 assert_eq!(committed["rebase"]["outcome"], "finished");
290 let landed = json(&b, &["land"]);
291 assert_eq!(landed["outcome"], "fast-forward");
292 assert_eq!(repo.main().as_deref(), committed["changeset"].as_str());
293 // The resolution's first parent is a's change, and it names the change
294 // it resolves.
295 let log = history(&repo);
296 assert_eq!(log[0]["parents"][0].as_str(), main_before.as_deref());
297 assert!(rebased_from(&log[0]).is_some());
298 assert_eq!(log[0]["message"], "both twos");
299 assert_eq!(read(&b, "shared.txt"), "one\nTWO from a and b\nthree\n");
300 assert!(repo.fsck_is_clean());
301}
302
303#[test]
304fn landing_after_main_moved_rebases_and_follows_the_tree() {
305 let repo = Repo::new();
306 seed(&repo, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
307 let ws = repo.workspace("ws");
308 // Main moves without this workspace: a disjoint change, made without a
309 // working copy.
310 let main = repo.main().unwrap();
311 let elsewhere = repo.root.parent().unwrap().join("other.txt");
312 std::fs::write(&elsewhere, "from elsewhere\n").unwrap();
313 json(
314 &repo.root,
315 &[
316 "change",
317 "create",
318 "--base",
319 &main,
320 "--set",
321 &format!("dir/other.txt=@{}", elsewhere.display()),
322 "--delete",
323 "b.txt",
324 "-m",
325 "elsewhere",
326 "--land",
327 "main",
328 ],
329 );
330 write(&ws, "a.txt", "a, edited\n");
331 let committed = json(&ws, &["commit", "-m", "edit a"]);
332 let landed = json(&ws, &["land"]);
333 assert_eq!(landed["outcome"], "rebased");
334 let head = landed["head"].as_str().unwrap().to_owned();
335 assert_eq!(repo.main().as_deref(), Some(head.as_str()));
336 assert_ne!(Some(head.as_str()), committed["changeset"].as_str());
337
338 // The working copy is the landed tree: main's change came in, the
339 // deleted file went away, and nothing is left to commit.
340 assert_eq!(read(&ws, "dir/other.txt"), "from elsewhere\n");
341 assert!(!ws.join("b.txt").exists());
342 assert_eq!(read(&ws, "a.txt"), "a, edited\n");
343 let now = status(&ws);
344 assert_eq!(now["clean"], true);
345 assert_eq!(now["base"].as_str(), Some(head.as_str()));
346 let show = json(&repo.root, &["show", &head]);
347 let paths: Vec<&str> = show["changes"]
348 .as_array()
349 .unwrap()
350 .iter()
351 .map(|c| c["path"].as_str().unwrap())
352 .collect();
353 assert_eq!(paths, ["a.txt"]);
354 assert!(repo.fsck_is_clean());
355}
356
357#[test]
358fn the_secrets_guard() {
359 let repo = Repo::new();
360 seed(&repo, &[("README.md", "hello\n")]);
361 let ws = repo.workspace("ws");
362 write(&ws, ".env", "TOKEN=secret\n");
363 write(&ws, "keys/server.pem", "-----BEGIN-----\n");
364 write(&ws, "keys/id_ed25519", "private\n");
365 std::fs::write(ws.join("big.bin"), vec![7u8; (1 << 20) + 1]).unwrap();
366 write(&ws, "notes.txt", "fine\n");
367 let guarded = [".env", "big.bin", "keys/id_ed25519", "keys/server.pem"];
368
369 let now = status(&ws);
370 assert_eq!(now["added"], serde_json::json!(["notes.txt"]));
371 assert_eq!(now["needs_track"], serde_json::json!(guarded));
372 // They stop a commit of everything, and status says so first.
373 assert_eq!(now["ready_to_commit"], false);
374 let blocking: Vec<(&str, &str)> = now["blocking"]
375 .as_array()
376 .unwrap()
377 .iter()
378 .map(|b| (b["reason"].as_str().unwrap(), b["path"].as_str().unwrap()))
379 .collect();
380 let expected: Vec<(&str, &str)> = guarded.iter().map(|p| ("needs_track", *p)).collect();
381 assert_eq!(blocking, expected);
382 let refused = fails(&ws, &["commit", "-m", "notes"]);
383 for path in guarded {
384 assert!(refused.contains(path), "{refused}");
385 }
386 assert!(refused.contains("braid track"), "{refused}");
387 // The ordinary file alone is committed.
388 let committed = json(&ws, &["commit", "-m", "notes", "notes.txt"]);
389 assert_eq!(committed["changes"], 1);
390 let show = json(
391 &repo.root,
392 &["show", committed["changeset"].as_str().unwrap()],
393 );
394 assert_eq!(show["changes"].as_array().unwrap().len(), 1);
395 // Guarded files are not uncommitted changes: landing goes ahead.
396 json(&ws, &["land"]);
397
398 // Marked, they are committed; with --force, the big file stays out.
399 json(&ws, &["track", ".env", "keys"]);
400 let now = status(&ws);
401 assert_eq!(now["needs_track"], serde_json::json!(["big.bin"]));
402 assert_eq!(
403 now["added"],
404 serde_json::json!([".env", "keys/id_ed25519", "keys/server.pem"])
405 );
406 assert_eq!(now["blocking"][0]["path"], "big.bin");
407 let committed = json(&ws, &["commit", "-m", "keys", "--force"]);
408 assert_eq!(committed["changes"], 3);
409 let now = status(&ws);
410 assert_eq!(now["needs_track"], serde_json::json!(["big.bin"]));
411 assert_eq!(now["ready_to_commit"], false);
412 // Nothing else to commit while only guarded files remain.
413 assert!(fails(&ws, &["commit", "-m", "nothing"]).contains("big.bin"));
414 assert!(fails(&ws, &["commit", "-m", "nothing", "--force"]).contains("nothing to commit"));
415 json(&ws, &["track", "big.bin"]);
416 let now = status(&ws);
417 assert_eq!(now["ready_to_commit"], true);
418 assert_eq!(now["blocking"], serde_json::json!([]));
419}
420
421#[test]
422fn change_create_with_expectations() {
423 let repo = Repo::new();
424 let seeded = seed(&repo, &[("config.toml", "a = 1\n")]);
425 let show = json(&repo.root, &["show", &seeded]);
426 let blob = show["changes"][0]["blob"].as_str().unwrap().to_owned();
427 let new = repo.root.parent().unwrap().join("new.toml");
428 std::fs::write(&new, "a = 2\n").unwrap();
429 let set = format!("config.toml=@{}", new.display());
430
431 // The expectation matches: made and landed.
432 let made = json(
433 &repo.root,
434 &[
435 "change",
436 "create",
437 "--base",
438 "main",
439 "--set",
440 &set,
441 "--expect",
442 &format!("config.toml={blob}"),
443 "--expect",
444 "other.toml=absent",
445 "-m",
446 "a is 2",
447 "--land",
448 "main",
449 ],
450 );
451 assert_eq!(made["land"]["outcome"], "fast-forward");
452 assert_eq!(repo.main().as_deref(), made["change"].as_str());
453 let change = made["change"].as_str().unwrap();
454 assert_eq!(
455 made["land"]["landed"],
456 serde_json::json!([{ "from": change, "to": change }])
457 );
458 assert!(made["land"].get("updated_paths").is_none());
459 let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
460 assert_eq!(
461 op["description"],
462 format!(
463 "land changeset on main: fast-forward {} -> {} (0 paths merged)",
464 &change[..12],
465 &change[..12]
466 )
467 );
468
469 // Another agent, still believing the old content, is stopped before
470 // anything is made: its base holds another blob now.
471 let ops = json(&repo.root, &["op", "log"]).as_array().unwrap().len();
472 let refused = fails(
473 &repo.root,
474 &[
475 "change",
476 "create",
477 "--base",
478 "main",
479 "--set",
480 &set,
481 "--expect",
482 &format!("config.toml={blob}"),
483 "-m",
484 "stale",
485 "--land",
486 "main",
487 ],
488 );
489 assert!(refused.contains("expected"), "{refused}");
490 let refused = fails(
491 &repo.root,
492 &[
493 "change",
494 "create",
495 "--base",
496 "main",
497 "--set",
498 &set,
499 "--expect",
500 "config.toml=absent",
501 "-m",
502 "stale",
503 ],
504 );
505 assert!(refused.contains("absent"), "{refused}");
506 assert_eq!(repo.main().as_deref(), made["change"].as_str());
507 assert_eq!(
508 json(&repo.root, &["op", "log"]).as_array().unwrap().len(),
509 ops
510 );
511
512 // Built on the old base and landed now, the stale edit conflicts: exit
513 // status 2, and main stays.
514 let stale = repo.root.parent().unwrap().join("stale.toml");
515 std::fs::write(&stale, "a = 3\n").unwrap();
516 let conflicted = json_status(
517 &repo.root,
518 &[
519 "change",
520 "create",
521 "--base",
522 &seeded,
523 "--set",
524 &format!("config.toml=@{}", stale.display()),
525 "-m",
526 "a is 3",
527 "--land",
528 "main",
529 ],
530 2,
531 );
532 assert_eq!(conflicted["land"]["outcome"], "conflicts");
533 assert_eq!(conflicted["land"]["conflicts"][0]["kind"], "CONTENT");
534 assert_eq!(
535 conflicted["land"]["conflicts"][0]["workspace"]["size"],
536 "a = 3\n".len()
537 );
538 assert_eq!(
539 conflicted["land"]["next"],
540 "braid change create --base main"
541 );
542 assert_eq!(
543 conflicted["land"]["landed"],
544 serde_json::json!([{ "from": conflicted["change"], "to": null }])
545 );
546 assert_eq!(repo.main().as_deref(), made["change"].as_str());
547
548 // Content from standard input.
549 let mut child = Command::new(env!("CARGO_BIN_EXE_braid"))
550 .current_dir(&repo.root)
551 .args([
552 "change",
553 "create",
554 "--base",
555 "main",
556 "--set",
557 "piped.txt=@-",
558 "-m",
559 "piped",
560 "--json",
561 ])
562 .env("BRAID_AUTHOR", AUTHOR)
563 .stdin(Stdio::piped())
564 .stdout(Stdio::piped())
565 .spawn()
566 .unwrap();
567 std::io::Write::write_all(&mut child.stdin.take().unwrap(), b"from a pipe\n").unwrap();
568 let out = child.wait_with_output().unwrap();
569 assert!(out.status.success());
570 let piped: Value = serde_json::from_slice(&out.stdout).unwrap();
571 let shown = json(&repo.root, &["show", piped["change"].as_str().unwrap()]);
572 assert_eq!(shown["changes"][0]["path"], "piped.txt");
573 assert_eq!(shown["changes"][0]["size"], 12);
574 assert!(repo.fsck_is_clean());
575}
576
577#[test]
578fn the_short_id_commit_prints_works_everywhere() {
579 let repo = Repo::new();
580 seed(&repo, &[("README.md", "hello\n")]);
581 let ws = repo.workspace("ws");
582 write(&ws, "notes.txt", "notes\n");
583 let out = braid(&ws, &["commit", "-m", "notes"]);
584 assert!(out.status.success(), "{}", stderr(&out));
585 let text = String::from_utf8(out.stdout).unwrap();
586 assert!(text.starts_with("Committed "), "{text}");
587 let short = text.split_whitespace().nth(1).unwrap().to_owned();
588 assert_eq!(short.len(), 12, "{text}");
589
590 // show and log take it, and give the full id in JSON.
591 let shown = json(&repo.root, &["show", &short]);
592 let full = shown["id"].as_str().unwrap().to_owned();
593 assert_eq!(full.len(), 64);
594 assert!(full.starts_with(&short));
595 assert_eq!(
596 json(&repo.root, &["log", &short[..6], "-n", "1"])[0]["id"],
597 full.as_str()
598 );
599 // So do --at and --base.
600 let other = repo.root.parent().unwrap().join("other");
601 let added = json(
602 &repo.root,
603 &[
604 "workspace",
605 "add",
606 "other",
607 other.to_str().unwrap(),
608 "--at",
609 &short[..8],
610 ],
611 );
612 assert_eq!(added["base"], full.as_str());
613 assert_eq!(read(&other, "notes.txt"), "notes\n");
614 let made = json(
615 &repo.root,
616 &[
617 "change",
618 "create",
619 "--base",
620 &short[..7],
621 "--delete",
622 "notes.txt",
623 "-m",
624 "no notes",
625 ],
626 );
627 assert_eq!(made["base"], full.as_str());
628 // commit --json gives the full id.
629 write(&ws, "more.txt", "more\n");
630 let committed = json(&ws, &["commit", "-m", "more"]);
631 assert_eq!(committed["changeset"].as_str().unwrap().len(), 64);
632}
633
634#[test]
635fn changesets_name_the_agent_that_made_them() {
636 let repo = Repo::new();
637 seed(&repo, &[("shared.txt", "one\ntwo\nthree\n")]);
638 let a = repo.workspace("a");
639 let b = repo.workspace("b");
640 write(&a, "shared.txt", "one\nTWO from a\nthree\n");
641 json_as("agent-a", &a, &["commit", "-m", "a's two"], 0);
642 json_as("agent-a", &a, &["land"], 0);
643 write(&b, "b.txt", "b\n");
644 json_as("agent-b", &b, &["commit", "-m", "add b"], 0);
645 write(&b, "shared.txt", "one\nTWO from b\nthree\n");
646 json_as("agent-b", &b, &["commit", "-m", "b's two"], 0);
647
648 // Rebased by an update and resolved under another label, b's changes
649 // still name agent-b; landing records the lander in the op log only.
650 json_as("fixer", &b, &["update"], 2);
651 write(&b, "shared.txt", "one\nTWO from a and b\nthree\n");
652 json_as("fixer", &b, &["commit"], 0);
653 let landed = json_as("lander", &b, &["land"], 0);
654 let log = history(&repo);
655 let agents: Vec<&str> = log.iter().map(|c| c["agent"].as_str().unwrap()).collect();
656 assert_eq!(agents, ["agent-b", "agent-b", "agent-a", "tester"]);
657 for changeset in &log[..2] {
658 assert!(rebased_from(changeset).is_some());
659 let extras = changeset["extras"].as_array().unwrap();
660 assert_eq!(extras[0], serde_json::json!(["agent", "agent-b"]));
661 }
662 let ops = json(&repo.root, &["op", "log", "-n", "1"]);
663 assert_eq!(ops[0]["agent"], "lander");
664 assert_eq!(ops[0]["seq"], landed["operation"]);
665
666 // The text forms show it too.
667 let out = braid(&repo.root, &["show", "main"]);
668 let text = String::from_utf8(out.stdout).unwrap();
669 assert!(text.contains("\nagent agent-b\n"), "{text}");
670 let out = braid(&repo.root, &["log", "-n", "1"]);
671 let text = String::from_utf8(out.stdout).unwrap();
672 assert!(text.contains(" Ada (agent-b) b's two"), "{text}");
673}
674
675/// Statuses by path, from the changes of `show --json` or `diff --json`.
676fn statuses(changes: &Value) -> Vec<(String, String)> {
677 changes
678 .as_array()
679 .unwrap()
680 .iter()
681 .map(|c| {
682 (
683 c["path"].as_str().unwrap().to_owned(),
684 c["status"].as_str().unwrap().to_owned(),
685 )
686 })
687 .collect()
688}
689
690fn pairs(expected: &[(&str, &str)]) -> Vec<(String, String)> {
691 expected
692 .iter()
693 .map(|(path, status)| (path.to_string(), status.to_string()))
694 .collect()
695}
696
697#[cfg(unix)]
698#[test]
699fn show_and_diff_tell_added_modified_deleted_and_type_changes() {
700 use std::os::unix::fs::PermissionsExt;
701
702 let repo = Repo::new();
703 let seeded = seed(
704 &repo,
705 &[
706 ("dir/x", "x\n"),
707 ("edit.txt", "1\n"),
708 ("flip", "a file\n"),
709 ("gone.txt", "g\n"),
710 ("run.sh", "#!/bin/sh\n"),
711 ],
712 );
713 let ws = repo.workspace("ws");
714 write(&ws, "edit.txt", "2\n");
715 std::fs::remove_file(ws.join("gone.txt")).unwrap();
716 write(&ws, "new.txt", "n\n");
717 std::fs::set_permissions(ws.join("run.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
718 std::fs::remove_file(ws.join("flip")).unwrap();
719 std::os::unix::fs::symlink("edit.txt", ws.join("flip")).unwrap();
720 std::fs::remove_dir_all(ws.join("dir")).unwrap();
721 write(&ws, "dir", "now a file\n");
722 let committed = json(&ws, &["commit", "-m", "every kind"]);
723 let id = committed["changeset"].as_str().unwrap();
724
725 let expected = pairs(&[
726 ("dir", "A"),
727 ("dir/x", "D"),
728 ("edit.txt", "M"),
729 ("flip", "T"),
730 ("gone.txt", "D"),
731 ("new.txt", "A"),
732 ("run.sh", "M"),
733 ]);
734 let shown = json(&repo.root, &["show", id]);
735 assert_eq!(statuses(&shown["changes"]), expected);
736 // What each path held before is there too.
737 let edit = &shown["changes"][2];
738 assert_eq!(edit["op"], "file");
739 assert_eq!(edit["old"]["op"], "file");
740 assert_eq!(edit["old"]["size"], 2);
741 assert_ne!(edit["old"]["blob"], edit["blob"]);
742 assert_eq!(shown["changes"][0]["old"], Value::Null);
743 assert_eq!(shown["changes"][6]["op"], "executable");
744 // The text form is git's --name-status.
745 let text = String::from_utf8(braid(&repo.root, &["show", id]).stdout).unwrap();
746 let listed: Vec<&str> = text.lines().filter(|line| line.contains('\t')).collect();
747 assert_eq!(
748 listed,
749 [
750 "A\tdir",
751 "D\tdir/x",
752 "M\tedit.txt",
753 "T\tflip",
754 "D\tgone.txt",
755 "A\tnew.txt",
756 "M\trun.sh"
757 ]
758 );
759
760 // diff says the same between the two changesets, and the opposite the
761 // other way round.
762 let diffed = json(&repo.root, &["diff", &seeded[..10], id]);
763 assert_eq!(diffed["from"], seeded.as_str());
764 assert_eq!(diffed["to"], id);
765 assert_eq!(statuses(&diffed["changes"]), expected);
766 let back = json(&repo.root, &["diff", id, "main"]);
767 assert_eq!(
768 statuses(&back["changes"]),
769 pairs(&[
770 ("dir", "D"),
771 ("dir/x", "A"),
772 ("edit.txt", "M"),
773 ("flip", "T"),
774 ("gone.txt", "A"),
775 ("new.txt", "D"),
776 ("run.sh", "M"),
777 ])
778 );
779 let text = String::from_utf8(braid(&repo.root, &["diff", "main", id]).stdout).unwrap();
780 assert_eq!(text.lines().count(), 7);
781 assert!(text.starts_with("A\tdir\nD\tdir/x\n"), "{text}");
782 assert!(
783 json(&repo.root, &["diff", id, id])["changes"]
784 .as_array()
785 .unwrap()
786 .is_empty()
787 );
788}
789
790#[test]
791fn removing_a_workspace() {
792 let repo = Repo::new();
793 seed(&repo, &[("README.md", "hello\n")]);
794 let ws = repo.workspace("ws");
795 write(&ws, "draft.txt", "not committed\n");
796 let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
797 assert!(refused.contains("uncommitted changes"), "{refused}");
798 assert!(ws.join("draft.txt").exists());
799
800 // Committed but not landed: still refused.
801 json(&ws, &["commit", "-m", "draft"]);
802 let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
803 assert!(refused.contains("does not have"), "{refused}");
804
805 // Landed: removed, directory and all.
806 json(&ws, &["land"]);
807 json(&repo.root, &["workspace", "remove", "ws"]);
808 assert!(!ws.exists());
809 assert!(
810 json(&repo.root, &["workspace", "list"])
811 .as_array()
812 .unwrap()
813 .is_empty()
814 );
815
816 // --force removes a dirty one.
817 let other = repo.workspace("other");
818 write(&other, "scratch.txt", "x\n");
819 json(&repo.root, &["workspace", "remove", "other", "--force"]);
820 assert!(!other.exists());
821}
822
823#[test]
824fn workspaces_are_found_from_anywhere_inside() {
825 let repo = Repo::new();
826 seed(&repo, &[("src/lib.rs", "pub fn f() {}\n")]);
827 let ws = repo.workspace("ws");
828 let inside = ws.join("src");
829 write(&ws, "src/lib.rs", "pub fn g() {}\n");
830 let now = status(&inside);
831 assert_eq!(now["workspace"], "ws");
832 assert_eq!(now["modified"], serde_json::json!(["src/lib.rs"]));
833 // Paths are relative to the current directory.
834 write(&ws, "src/new.rs", "x\n");
835 write(&ws, "top.txt", "y\n");
836 let committed = json(&inside, &["commit", "-m", "only src", "new.rs", "lib.rs"]);
837 assert_eq!(committed["changes"], 2);
838 assert_eq!(status(&ws)["added"], serde_json::json!(["top.txt"]));
839 // The repository root is not a workspace.
840 assert!(fails(&repo.root, &["status"]).contains("not inside a workspace"));
841 // --workspace names one from anywhere in the repository.
842 assert_eq!(
843 json(&repo.root, &["status", "--workspace", "ws"])["workspace"],
844 "ws"
845 );
846}
847
848#[test]
849fn stacked_changesets_land_in_order() {
850 let repo = Repo::new();
851 seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]);
852 let ws = repo.workspace("ws");
853 let other = repo.workspace("other");
854 write(&ws, "a.txt", "2\n");
855 let first = json(&ws, &["commit", "-m", "first"]);
856 write(&ws, "a.txt", "3\n");
857 let second = json(&ws, &["commit", "-m", "second"]);
858 assert_eq!(status(&ws)["unlanded"].as_array().unwrap().len(), 2);
859 write(&other, "b.txt", "other\n");
860 json(&other, &["commit", "-m", "other"]);
861 json(&other, &["land"]);
862
863 // Both are rebased onto the other workspace's change, in order.
864 let landed = json(&ws, &["land"]);
865 assert_eq!(landed["outcome"], "rebased");
866 let log = history(&repo);
867 // The report and the op log say where each went.
868 let id = |c: &Value| c["changeset"].as_str().unwrap().to_owned();
869 let moves: Vec<(String, String)> = landed["landed"]
870 .as_array()
871 .unwrap()
872 .iter()
873 .map(|m| {
874 (
875 m["from"].as_str().unwrap().to_owned(),
876 m["to"].as_str().unwrap().to_owned(),
877 )
878 })
879 .collect();
880 assert_eq!(
881 moves,
882 [
883 (id(&first), log[1]["id"].as_str().unwrap().to_owned()),
884 (id(&second), log[0]["id"].as_str().unwrap().to_owned()),
885 ]
886 );
887 let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
888 assert_eq!(
889 op["description"],
890 format!(
891 "land workspace ws on main: rebased 2 changesets: {} -> {}, {} -> {} (0 paths merged)",
892 &moves[0].0[..12],
893 &moves[0].1[..12],
894 &moves[1].0[..12],
895 &moves[1].1[..12]
896 )
897 );
898 let messages: Vec<&str> = log.iter().map(|c| c["message"].as_str().unwrap()).collect();
899 assert_eq!(messages, ["second", "first", "other", "seed"]);
900 assert_eq!(
901 rebased_from(&log[0]).as_deref(),
902 second["changeset"].as_str()
903 );
904 assert_eq!(
905 rebased_from(&log[1]).as_deref(),
906 first["changeset"].as_str()
907 );
908 assert_eq!(read(&ws, "a.txt"), "3\n");
909 assert_eq!(read(&ws, "b.txt"), "other\n");
910 assert!(repo.fsck_is_clean());
911}
912
913#[test]
914fn land_and_update_print_the_same_fields() {
915 let fields = [
916 "base",
917 "branch",
918 "change",
919 "conflicts",
920 "head",
921 "head_before",
922 "landed",
923 "merged_paths",
924 "next",
925 "operation",
926 "outcome",
927 "updated_paths",
928 ];
929 let keys = |report: &Value| {
930 let mut keys: Vec<String> = report.as_object().unwrap().keys().cloned().collect();
931 keys.sort();
932 keys
933 };
934 let repo = Repo::new();
935 seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]);
936 let ws = repo.workspace("ws");
937 let other = repo.workspace("other");
938 write(&ws, "a.txt", "2\n");
939 let first = json(&ws, &["commit", "-m", "first"]);
940 write(&other, "b.txt", "other\n");
941 json(&other, &["commit", "-m", "other"]);
942 let theirs = json(&other, &["land"]);
943 let head = theirs["head"].as_str().unwrap().to_owned();
944
945 // update rebases the workspace's changeset onto the head, and brings
946 // b.txt into the working copy.
947 let updated = json(&ws, &["update"]);
948 assert_eq!(keys(&updated), fields);
949 assert_eq!(updated["outcome"], "rebased");
950 assert_eq!(updated["head_before"], head.as_str());
951 assert_eq!(updated["head"], head.as_str());
952 assert_eq!(updated["operation"], Value::Null);
953 assert_eq!(updated["next"], Value::Null);
954 assert_eq!(updated["updated_paths"], serde_json::json!(["b.txt"]));
955 let rebased = updated["base"].as_str().unwrap().to_owned();
956 assert_eq!(
957 updated["landed"],
958 serde_json::json!([{ "from": first["changeset"], "to": rebased }])
959 );
960
961 // land then fast-forwards to it, and writes nothing.
962 let landed = json(&ws, &["land"]);
963 assert_eq!(keys(&landed), fields);
964 assert_eq!(landed["outcome"], "fast-forward");
965 assert_eq!(landed["head_before"], head.as_str());
966 assert_eq!(landed["head"], rebased.as_str());
967 assert_eq!(landed["base"], rebased.as_str());
968 assert_eq!(
969 landed["landed"],
970 serde_json::json!([{ "from": rebased, "to": rebased }])
971 );
972 assert_eq!(landed["updated_paths"], serde_json::json!([]));
973 let op = &json(&repo.root, &["op", "log", "-n", "1"])[0];
974 assert_eq!(op["seq"], landed["operation"]);
975 assert_eq!(
976 op["description"],
977 format!(
978 "land workspace ws on main: fast-forward {} -> {} (0 paths merged)",
979 &rebased[..12],
980 &rebased[..12]
981 )
982 );
983 // Nothing left: both report it the same way.
984 let nothing = json(&ws, &["land"]);
985 assert_eq!(keys(&nothing), fields);
986 assert_eq!(nothing["outcome"], "nothing");
987 assert_eq!(nothing["landed"], serde_json::json!([]));
988 let up_to_date = json(&ws, &["update"]);
989 assert_eq!(keys(&up_to_date), fields);
990 assert_eq!(up_to_date["outcome"], "up-to-date");
991}
992
993#[test]
994fn a_conflict_that_is_not_about_content_needs_resolve() {
995 let repo = Repo::new();
996 seed(&repo, &[("gone.txt", "1\n"), ("keep.txt", "k\n")]);
997 let a = repo.workspace("a");
998 let b = repo.workspace("b");
999 std::fs::remove_file(a.join("gone.txt")).unwrap();
1000 json(&a, &["commit", "-m", "delete it"]);
1001 json(&a, &["land"]);
1002 write(&b, "gone.txt", "2\n");
1003 json(&b, &["commit", "-m", "edit it"]);
1004 let updated = json_status(&b, &["update"], 2);
1005 assert_eq!(updated["conflicts"][0]["kind"], "MODIFY_DELETE");
1006 // The head's version stays: deleted.
1007 assert!(!b.join("gone.txt").exists());
1008 let now = status(&b);
1009 assert_eq!(now["blocking"][0]["reason"], "unresolved");
1010 assert_eq!(now["blocking"][0]["kind"], "MODIFY_DELETE");
1011 assert_eq!(now["ready_to_commit"], false);
1012 let refused = fails(&b, &["commit", "-m", "x"]);
1013 assert!(refused.contains("braid resolve"), "{refused}");
1014 let resolved = json(&b, &["resolve", "gone.txt"]);
1015 assert!(resolved["remaining"].as_array().unwrap().is_empty());
1016 // Nothing to record, but a rebase to finish: commit can go ahead.
1017 let now = status(&b);
1018 assert_eq!(now["clean"], true);
1019 assert_eq!(now["ready_to_commit"], true);
1020 // Keeping the deletion leaves nothing of the change: the rebase ends
1021 // without a changeset.
1022 let committed = json(&b, &["commit"]);
1023 assert!(committed["changeset"].is_null());
1024 assert_eq!(committed["rebase"]["outcome"], "finished");
1025 assert_eq!(status(&b)["base"].as_str(), repo.main().as_deref());
1026 assert_eq!(json(&b, &["land"])["outcome"], "nothing");
1027}
1028
1029/// Eight processes, each with its own workspace, edit their own file and
1030/// their own line of a shared file, commit and land, round after round,
1031/// all at once. Afterwards every change is on main exactly once, main's
1032/// history is linear, and the store is clean.
1033#[test]
1034fn eight_agents_land_at_once() {
1035 const AGENTS: usize = 8;
1036 const ROUNDS: usize = 4;
1037 let repo = Repo::new();
1038 // One line per agent, with two untouched lines between them, so that
1039 // edits to different agents' lines merge.
1040 let shared: String = (0..AGENTS)
1041 .map(|i| format!("agent {i}: start\n--\n--\n"))
1042 .collect();
1043 seed(&repo, &[("shared.txt", &shared)]);
1044 let dirs: Vec<PathBuf> = (0..AGENTS)
1045 .map(|i| repo.workspace(&format!("agent-{i}")))
1046 .collect();
1047
1048 let made: Vec<Vec<String>> = std::thread::scope(|scope| {
1049 let handles: Vec<_> = dirs
1050 .iter()
1051 .enumerate()
1052 .map(|(i, dir)| {
1053 scope.spawn(move || {
1054 let mut commits = Vec::new();
1055 for round in 0..ROUNDS {
1056 write(
1057 dir,
1058 &format!("own-{i}.txt"),
1059 &format!("agent {i} round {round}\n"),
1060 );
1061 let text = read(dir, "shared.txt");
1062 let lines: Vec<String> = text
1063 .lines()
1064 .enumerate()
1065 .map(|(n, line)| {
1066 if n == i * 3 {
1067 format!("agent {i}: round {round}")
1068 } else {
1069 line.to_owned()
1070 }
1071 })
1072 .collect();
1073 write(dir, "shared.txt", &(lines.join("\n") + "\n"));
1074 let committed =
1075 json(dir, &["commit", "-m", &format!("agent {i} round {round}")]);
1076 commits.push(committed["changeset"].as_str().unwrap().to_owned());
1077 loop {
1078 let out = braid(dir, &["land", "--json"]);
1079 match out.status.code() {
1080 Some(0) => break,
1081 Some(2) => {
1082 // Someone else's change got in the way:
1083 // rebase onto it and try again.
1084 json(dir, &["update"]);
1085 }
1086 _ => panic!("land failed: {}", stderr(&out)),
1087 }
1088 }
1089 }
1090 commits
1091 })
1092 })
1093 .collect();
1094 handles.into_iter().map(|h| h.join().unwrap()).collect()
1095 });
1096
1097 // Every changeset on main maps back to one of the changesets made,
1098 // through the rebases it went through.
1099 let log = history(&repo);
1100 assert_eq!(log.len(), AGENTS * ROUNDS + 1);
1101 let mut seen = HashMap::new();
1102 for changeset in &log[..log.len() - 1] {
1103 assert_eq!(changeset["parents"].as_array().unwrap().len(), 1, "a merge");
1104 let mut id = changeset["id"].as_str().unwrap().to_owned();
1105 let mut current = changeset.clone();
1106 while let Some(from) = rebased_from(&current) {
1107 current = json(&repo.root, &["show", &from]);
1108 id = from;
1109 }
1110 *seen.entry(id).or_insert(0) += 1;
1111 }
1112 let all: HashSet<String> = made.iter().flatten().cloned().collect();
1113 assert_eq!(all.len(), AGENTS * ROUNDS);
1114 assert_eq!(seen.keys().cloned().collect::<HashSet<_>>(), all);
1115 assert!(seen.values().all(|count| *count == 1), "{seen:?}");
1116
1117 // A fresh workspace has every agent's last round.
1118 let check = repo.workspace("check");
1119 let text = read(&check, "shared.txt");
1120 for i in 0..AGENTS {
1121 assert_eq!(
1122 read(&check, &format!("own-{i}.txt")),
1123 format!("agent {i} round {}\n", ROUNDS - 1)
1124 );
1125 assert!(
1126 text.contains(&format!("agent {i}: round {}\n", ROUNDS - 1)),
1127 "{text}"
1128 );
1129 }
1130 assert!(repo.fsck_is_clean());
1131}
1132
1133#[test]
1134fn workspaces_made_before_main_existed_land_without_an_update() {
1135 // Both workspaces start on an empty branch, so their first changesets
1136 // have no parent. The second to land is rebased from the empty tree.
1137 let repo = Repo::new();
1138 let a = repo.workspace("first-a");
1139 let b = repo.workspace("first-b");
1140 write(&a, "a.txt", "from a\n");
1141 write(&b, "b.txt", "from b\n");
1142 json(&a, &["commit", "-m", "a"]);
1143 json(&b, &["commit", "-m", "b"]);
1144 assert_eq!(json(&a, &["land"])["outcome"], "fast-forward");
1145 let landed = json(&b, &["land"]);
1146 assert_eq!(landed["outcome"], "rebased");
1147 assert_eq!(read(&b, "a.txt"), "from a\n");
1148
1149 // The same path added on both sides is a conflict, never an overwrite.
1150 let c = repo.workspace("first-c");
1151 let d = repo.workspace("first-d");
1152 write(&c, "same.txt", "from c\n");
1153 write(&d, "same.txt", "from d\n");
1154 json(&c, &["commit", "-m", "c"]);
1155 json(&d, &["commit", "-m", "d"]);
1156 json(&c, &["land"]);
1157 let conflict = json_status(&d, &["land"], 2);
1158 assert_eq!(conflict["conflicts"][0]["path"], "same.txt");
1159 assert!(repo.fsck_is_clean());
1160}