| 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 | |
| 8 | use std::collections::{HashMap, HashSet}; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::process::{Command, Output, Stdio}; |
| 11 | |
| 12 | use serde_json::Value; |
| 13 | |
| 14 | const AUTHOR: &str = "Ada <ada@example.org>"; |
| 15 | |
| 16 | /// A repository in a temporary directory, driven through the binary. |
| 17 | struct Repo { |
| 18 | _temp: tempfile::TempDir, |
| 19 | root: PathBuf, |
| 20 | } |
| 21 | |
| 22 | impl 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. |
| 55 | fn 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`. |
| 60 | fn 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`. |
| 72 | fn 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 | |
| 86 | fn stderr(out: &Output) -> String { |
| 87 | String::from_utf8_lossy(&out.stderr).into_owned() |
| 88 | } |
| 89 | |
| 90 | /// Runs braid with `--json`, expecting exit status `code`. |
| 91 | fn json_status(dir: &Path, args: &[&str], code: i32) -> Value { |
| 92 | json_as("tester", dir, args, code) |
| 93 | } |
| 94 | |
| 95 | fn json(dir: &Path, args: &[&str]) -> Value { |
| 96 | json_status(dir, args, 0) |
| 97 | } |
| 98 | |
| 99 | /// Runs braid expecting failure, and returns its error message. |
| 100 | fn 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 | |
| 106 | fn 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 | |
| 112 | fn 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`. |
| 117 | fn 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 | |
| 140 | fn status(dir: &Path) -> Value { |
| 141 | json(dir, &["status"]) |
| 142 | } |
| 143 | |
| 144 | /// Every changeset on `main`'s first-parent chain, newest first. |
| 145 | fn history(repo: &Repo) -> Vec<Value> { |
| 146 | json(&repo.root, &["log", "main", "-n", "100000"]) |
| 147 | .as_array() |
| 148 | .unwrap() |
| 149 | .clone() |
| 150 | } |
| 151 | |
| 152 | fn 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] |
| 161 | fn 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] |
| 224 | fn 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] |
| 304 | fn 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] |
| 358 | fn 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] |
| 422 | fn 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] |
| 578 | fn 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] |
| 635 | fn 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`. |
| 676 | fn 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 | |
| 690 | fn 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] |
| 699 | fn 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] |
| 791 | fn 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 | // With none left, the list says so in text, and is empty in JSON. |
| 823 | let out = braid(&repo.root, &["workspace", "list"]); |
| 824 | assert!(out.status.success(), "{}", stderr(&out)); |
| 825 | let text = String::from_utf8(out.stdout).unwrap(); |
| 826 | assert!(text.starts_with("No workspaces yet: "), "{text}"); |
| 827 | assert!(text.contains("`braid workspace add <name>`"), "{text}"); |
| 828 | assert_eq!( |
| 829 | json(&repo.root, &["workspace", "list"]), |
| 830 | serde_json::json!([]) |
| 831 | ); |
| 832 | repo.workspace("again"); |
| 833 | let out = braid(&repo.root, &["workspace", "list"]); |
| 834 | let text = String::from_utf8(out.stdout).unwrap(); |
| 835 | assert!(text.starts_with("again main "), "{text}"); |
| 836 | } |
| 837 | |
| 838 | #[test] |
| 839 | fn removing_a_workspace_never_says_to_commit_a_secret() { |
| 840 | let repo = Repo::new(); |
| 841 | seed(&repo, &[("README.md", "hello\n")]); |
| 842 | let ws = repo.workspace("ws"); |
| 843 | write(&ws, ".env", "TOKEN=secret\n"); |
| 844 | let refused = fails(&repo.root, &["workspace", "remove", "ws"]); |
| 845 | assert!( |
| 846 | refused.contains("a new file the secrets guard holds back, \".env\""), |
| 847 | "{refused}" |
| 848 | ); |
| 849 | assert!( |
| 850 | refused.contains("move it out of the workspace"), |
| 851 | "{refused}" |
| 852 | ); |
| 853 | assert!(!refused.contains("commit them first"), "{refused}"); |
| 854 | // Changes to commit come first, counted on their own. |
| 855 | write(&ws, "notes.txt", "notes\n"); |
| 856 | let refused = fails(&repo.root, &["workspace", "remove", "ws"]); |
| 857 | assert!( |
| 858 | refused.contains("uncommitted changes (1 path, \"notes.txt\"); commit them first"), |
| 859 | "{refused}" |
| 860 | ); |
| 861 | std::fs::remove_file(ws.join("notes.txt")).unwrap(); |
| 862 | // Moved out, the secret no longer holds the workspace. |
| 863 | std::fs::rename(ws.join(".env"), repo.root.parent().unwrap().join(".env")).unwrap(); |
| 864 | json(&repo.root, &["workspace", "remove", "ws"]); |
| 865 | assert!(!ws.exists()); |
| 866 | } |
| 867 | |
| 868 | /// Runs braid in `dir` with no author from the environment unless |
| 869 | /// `author` gives one, and returns its exit status, standard output and |
| 870 | /// standard error. |
| 871 | fn signed(dir: &Path, author: Option<&str>, args: &[&str]) -> (i32, String, String) { |
| 872 | let mut command = Command::new(env!("CARGO_BIN_EXE_braid")); |
| 873 | command |
| 874 | .current_dir(dir) |
| 875 | .args(args) |
| 876 | .env_remove("BRAID_AUTHOR") |
| 877 | .env("BRAID_AGENT", "tester"); |
| 878 | if let Some(author) = author { |
| 879 | command.env("BRAID_AUTHOR", author); |
| 880 | } |
| 881 | let out = command.output().unwrap(); |
| 882 | ( |
| 883 | out.status.code().unwrap_or(-1), |
| 884 | String::from_utf8(out.stdout).unwrap(), |
| 885 | String::from_utf8(out.stderr).unwrap(), |
| 886 | ) |
| 887 | } |
| 888 | |
| 889 | #[test] |
| 890 | fn status_lists_a_missing_author_exactly_when_commit_refuses_for_it() { |
| 891 | const ADA: &str = "Ada <ada@example.org>"; |
| 892 | const GRACE: &str = "name = Grace\nemail = grace@example.org\n"; |
| 893 | // What the setup in agents.md writes where git has no identity. |
| 894 | const EMPTY: &str = "name = \nemail = \n"; |
| 895 | // Where the author comes from (BRAID_AUTHOR, --author and |
| 896 | // .braid/config), and whether commit has one it can use. |
| 897 | let cases = [ |
| 898 | (None, None, None, false), |
| 899 | (Some(ADA), None, None, true), |
| 900 | (None, Some(ADA), None, true), |
| 901 | (Some("Ada"), None, None, false), |
| 902 | (None, Some("Ada <a> b"), None, false), |
| 903 | (None, None, Some(GRACE), true), |
| 904 | (None, None, Some(EMPTY), false), |
| 905 | (None, None, Some("name = Grace\n"), false), |
| 906 | (Some("Ada"), None, Some(GRACE), false), |
| 907 | (Some(ADA), None, Some(EMPTY), true), |
| 908 | ]; |
| 909 | for (env, flag, config, can_sign) in cases { |
| 910 | let case = format!("BRAID_AUTHOR {env:?}, --author {flag:?}, config {config:?}"); |
| 911 | let repo = Repo::new(); |
| 912 | seed(&repo, &[("README.md", "hello\n")]); |
| 913 | let ws = repo.workspace("ws"); |
| 914 | if let Some(config) = config { |
| 915 | std::fs::write(repo.root.join(".braid/config"), config).unwrap(); |
| 916 | } |
| 917 | let with_flag = |args: &[&str]| -> Vec<String> { |
| 918 | let mut all: Vec<String> = args.iter().map(|arg| arg.to_string()).collect(); |
| 919 | if let Some(flag) = flag { |
| 920 | all.extend(["--author".to_owned(), flag.to_owned()]); |
| 921 | } |
| 922 | all |
| 923 | }; |
| 924 | let run = |args: &[&str]| { |
| 925 | let all = with_flag(args); |
| 926 | let all: Vec<&str> = all.iter().map(String::as_str).collect(); |
| 927 | signed(&ws, env, &all) |
| 928 | }; |
| 929 | |
| 930 | // Clean, then with a change: the author blocks a commit either way. |
| 931 | for dirty in [false, true] { |
| 932 | if dirty { |
| 933 | write(&ws, "notes.txt", "notes\n"); |
| 934 | } |
| 935 | let (code, out, err) = run(&["status", "--json"]); |
| 936 | assert_eq!(code, 0, "{case}: {err}"); |
| 937 | let now: Value = serde_json::from_str(&out).unwrap(); |
| 938 | let author: Vec<&Value> = now["blocking"] |
| 939 | .as_array() |
| 940 | .unwrap() |
| 941 | .iter() |
| 942 | .filter(|blocker| blocker["reason"] == "author") |
| 943 | .collect(); |
| 944 | assert_eq!(author.len(), usize::from(!can_sign), "{case}: {out}"); |
| 945 | assert_eq!(now["ready_to_commit"], dirty && can_sign, "{case}: {out}"); |
| 946 | let (code, text, _) = run(&["status"]); |
| 947 | assert_eq!(code, 0, "{case}"); |
| 948 | assert_eq!( |
| 949 | text.contains("Ready to commit."), |
| 950 | dirty && can_sign, |
| 951 | "{case}: {text}" |
| 952 | ); |
| 953 | assert_eq!( |
| 954 | text.contains("Not ready to commit:"), |
| 955 | !can_sign, |
| 956 | "{case}: {text}" |
| 957 | ); |
| 958 | |
| 959 | let (code, _, err) = run(&["commit", "-m", "notes"]); |
| 960 | if can_sign { |
| 961 | assert!(author.is_empty()); |
| 962 | if dirty { |
| 963 | assert_eq!(code, 0, "{case}: {err}"); |
| 964 | } else { |
| 965 | assert_eq!(code, 1, "{case}"); |
| 966 | assert_eq!(err, "braid: error: nothing to commit\n", "{case}"); |
| 967 | } |
| 968 | } else { |
| 969 | // Commit refuses with the very reason status gave, before |
| 970 | // looking for anything to commit. |
| 971 | assert_eq!(code, 1, "{case}"); |
| 972 | let reason = author[0]["message"].as_str().unwrap(); |
| 973 | assert_eq!(author[0]["path"], Value::Null, "{case}"); |
| 974 | assert_eq!(err, format!("braid: error: {reason}\n"), "{case}"); |
| 975 | assert!(text.contains(&format!(" - {reason}\n")), "{case}: {text}"); |
| 976 | // Landing and updating need someone to sign as too. |
| 977 | for command in ["land", "update"] { |
| 978 | let (code, _, refused) = run(&[command]); |
| 979 | assert_eq!(code, 1, "{case}: {command}"); |
| 980 | assert_eq!(refused, err, "{case}: {command}"); |
| 981 | } |
| 982 | } |
| 983 | } |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn workspaces_are_found_from_anywhere_inside() { |
| 989 | let repo = Repo::new(); |
| 990 | seed(&repo, &[("src/lib.rs", "pub fn f() {}\n")]); |
| 991 | let ws = repo.workspace("ws"); |
| 992 | let inside = ws.join("src"); |
| 993 | write(&ws, "src/lib.rs", "pub fn g() {}\n"); |
| 994 | let now = status(&inside); |
| 995 | assert_eq!(now["workspace"], "ws"); |
| 996 | assert_eq!(now["modified"], serde_json::json!(["src/lib.rs"])); |
| 997 | // Paths are relative to the current directory. |
| 998 | write(&ws, "src/new.rs", "x\n"); |
| 999 | write(&ws, "top.txt", "y\n"); |
| 1000 | let committed = json(&inside, &["commit", "-m", "only src", "new.rs", "lib.rs"]); |
| 1001 | assert_eq!(committed["changes"], 2); |
| 1002 | assert_eq!(status(&ws)["added"], serde_json::json!(["top.txt"])); |
| 1003 | // The repository root is not a workspace. |
| 1004 | assert!(fails(&repo.root, &["status"]).contains("not inside a workspace")); |
| 1005 | // --workspace names one from anywhere in the repository. |
| 1006 | assert_eq!( |
| 1007 | json(&repo.root, &["status", "--workspace", "ws"])["workspace"], |
| 1008 | "ws" |
| 1009 | ); |
| 1010 | } |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn stacked_changesets_land_in_order() { |
| 1014 | let repo = Repo::new(); |
| 1015 | seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]); |
| 1016 | let ws = repo.workspace("ws"); |
| 1017 | let other = repo.workspace("other"); |
| 1018 | write(&ws, "a.txt", "2\n"); |
| 1019 | let first = json(&ws, &["commit", "-m", "first"]); |
| 1020 | write(&ws, "a.txt", "3\n"); |
| 1021 | let second = json(&ws, &["commit", "-m", "second"]); |
| 1022 | assert_eq!(status(&ws)["unlanded"].as_array().unwrap().len(), 2); |
| 1023 | write(&other, "b.txt", "other\n"); |
| 1024 | json(&other, &["commit", "-m", "other"]); |
| 1025 | json(&other, &["land"]); |
| 1026 | |
| 1027 | // Both are rebased onto the other workspace's change, in order. |
| 1028 | let landed = json(&ws, &["land"]); |
| 1029 | assert_eq!(landed["outcome"], "rebased"); |
| 1030 | let log = history(&repo); |
| 1031 | // The report and the op log say where each went. |
| 1032 | let id = |c: &Value| c["changeset"].as_str().unwrap().to_owned(); |
| 1033 | let moves: Vec<(String, String)> = landed["landed"] |
| 1034 | .as_array() |
| 1035 | .unwrap() |
| 1036 | .iter() |
| 1037 | .map(|m| { |
| 1038 | ( |
| 1039 | m["from"].as_str().unwrap().to_owned(), |
| 1040 | m["to"].as_str().unwrap().to_owned(), |
| 1041 | ) |
| 1042 | }) |
| 1043 | .collect(); |
| 1044 | assert_eq!( |
| 1045 | moves, |
| 1046 | [ |
| 1047 | (id(&first), log[1]["id"].as_str().unwrap().to_owned()), |
| 1048 | (id(&second), log[0]["id"].as_str().unwrap().to_owned()), |
| 1049 | ] |
| 1050 | ); |
| 1051 | let op = &json(&repo.root, &["op", "log", "-n", "1"])[0]; |
| 1052 | assert_eq!( |
| 1053 | op["description"], |
| 1054 | format!( |
| 1055 | "land workspace ws on main: rebased 2 changesets: {} -> {}, {} -> {} (0 paths merged)", |
| 1056 | &moves[0].0[..12], |
| 1057 | &moves[0].1[..12], |
| 1058 | &moves[1].0[..12], |
| 1059 | &moves[1].1[..12] |
| 1060 | ) |
| 1061 | ); |
| 1062 | let messages: Vec<&str> = log.iter().map(|c| c["message"].as_str().unwrap()).collect(); |
| 1063 | assert_eq!(messages, ["second", "first", "other", "seed"]); |
| 1064 | assert_eq!( |
| 1065 | rebased_from(&log[0]).as_deref(), |
| 1066 | second["changeset"].as_str() |
| 1067 | ); |
| 1068 | assert_eq!( |
| 1069 | rebased_from(&log[1]).as_deref(), |
| 1070 | first["changeset"].as_str() |
| 1071 | ); |
| 1072 | assert_eq!(read(&ws, "a.txt"), "3\n"); |
| 1073 | assert_eq!(read(&ws, "b.txt"), "other\n"); |
| 1074 | assert!(repo.fsck_is_clean()); |
| 1075 | } |
| 1076 | |
| 1077 | #[test] |
| 1078 | fn land_and_update_print_the_same_fields() { |
| 1079 | let fields = [ |
| 1080 | "base", |
| 1081 | "branch", |
| 1082 | "change", |
| 1083 | "conflicts", |
| 1084 | "head", |
| 1085 | "head_before", |
| 1086 | "hub_verify", |
| 1087 | "landed", |
| 1088 | "merged_paths", |
| 1089 | "next", |
| 1090 | "operation", |
| 1091 | "outcome", |
| 1092 | "updated_paths", |
| 1093 | ]; |
| 1094 | let keys = |report: &Value| { |
| 1095 | let mut keys: Vec<String> = report.as_object().unwrap().keys().cloned().collect(); |
| 1096 | keys.sort(); |
| 1097 | keys |
| 1098 | }; |
| 1099 | let repo = Repo::new(); |
| 1100 | seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]); |
| 1101 | let ws = repo.workspace("ws"); |
| 1102 | let other = repo.workspace("other"); |
| 1103 | write(&ws, "a.txt", "2\n"); |
| 1104 | let first = json(&ws, &["commit", "-m", "first"]); |
| 1105 | write(&other, "b.txt", "other\n"); |
| 1106 | json(&other, &["commit", "-m", "other"]); |
| 1107 | let theirs = json(&other, &["land"]); |
| 1108 | let head = theirs["head"].as_str().unwrap().to_owned(); |
| 1109 | |
| 1110 | // update rebases the workspace's changeset onto the head, and brings |
| 1111 | // b.txt into the working copy. |
| 1112 | let updated = json(&ws, &["update"]); |
| 1113 | assert_eq!(keys(&updated), fields); |
| 1114 | assert_eq!(updated["outcome"], "rebased"); |
| 1115 | assert_eq!(updated["head_before"], head.as_str()); |
| 1116 | assert_eq!(updated["head"], head.as_str()); |
| 1117 | assert_eq!(updated["operation"], Value::Null); |
| 1118 | assert_eq!(updated["next"], Value::Null); |
| 1119 | assert_eq!(updated["updated_paths"], serde_json::json!(["b.txt"])); |
| 1120 | let rebased = updated["base"].as_str().unwrap().to_owned(); |
| 1121 | assert_eq!( |
| 1122 | updated["landed"], |
| 1123 | serde_json::json!([{ "from": first["changeset"], "to": rebased }]) |
| 1124 | ); |
| 1125 | |
| 1126 | // land then fast-forwards to it, and writes nothing. |
| 1127 | let landed = json(&ws, &["land"]); |
| 1128 | assert_eq!(keys(&landed), fields); |
| 1129 | assert_eq!(landed["outcome"], "fast-forward"); |
| 1130 | // No hub verifies a local landing. |
| 1131 | assert_eq!(landed["hub_verify"], Value::Null); |
| 1132 | assert_eq!(landed["head_before"], head.as_str()); |
| 1133 | assert_eq!(landed["head"], rebased.as_str()); |
| 1134 | assert_eq!(landed["base"], rebased.as_str()); |
| 1135 | assert_eq!( |
| 1136 | landed["landed"], |
| 1137 | serde_json::json!([{ "from": rebased, "to": rebased }]) |
| 1138 | ); |
| 1139 | assert_eq!(landed["updated_paths"], serde_json::json!([])); |
| 1140 | let op = &json(&repo.root, &["op", "log", "-n", "1"])[0]; |
| 1141 | assert_eq!(op["seq"], landed["operation"]); |
| 1142 | assert_eq!( |
| 1143 | op["description"], |
| 1144 | format!( |
| 1145 | "land workspace ws on main: fast-forward {} -> {} (0 paths merged)", |
| 1146 | &rebased[..12], |
| 1147 | &rebased[..12] |
| 1148 | ) |
| 1149 | ); |
| 1150 | // Nothing left: both report it the same way. |
| 1151 | let nothing = json(&ws, &["land"]); |
| 1152 | assert_eq!(keys(¬hing), fields); |
| 1153 | assert_eq!(nothing["outcome"], "nothing"); |
| 1154 | assert_eq!(nothing["landed"], serde_json::json!([])); |
| 1155 | let up_to_date = json(&ws, &["update"]); |
| 1156 | assert_eq!(keys(&up_to_date), fields); |
| 1157 | assert_eq!(up_to_date["outcome"], "up-to-date"); |
| 1158 | } |
| 1159 | |
| 1160 | #[test] |
| 1161 | fn a_conflict_that_is_not_about_content_needs_resolve() { |
| 1162 | let repo = Repo::new(); |
| 1163 | seed(&repo, &[("gone.txt", "1\n"), ("keep.txt", "k\n")]); |
| 1164 | let a = repo.workspace("a"); |
| 1165 | let b = repo.workspace("b"); |
| 1166 | std::fs::remove_file(a.join("gone.txt")).unwrap(); |
| 1167 | json(&a, &["commit", "-m", "delete it"]); |
| 1168 | json(&a, &["land"]); |
| 1169 | write(&b, "gone.txt", "2\n"); |
| 1170 | json(&b, &["commit", "-m", "edit it"]); |
| 1171 | let updated = json_status(&b, &["update"], 2); |
| 1172 | assert_eq!(updated["conflicts"][0]["kind"], "MODIFY_DELETE"); |
| 1173 | // The head's version stays: deleted. |
| 1174 | assert!(!b.join("gone.txt").exists()); |
| 1175 | let now = status(&b); |
| 1176 | assert_eq!(now["blocking"][0]["reason"], "unresolved"); |
| 1177 | assert_eq!(now["blocking"][0]["kind"], "MODIFY_DELETE"); |
| 1178 | assert_eq!(now["ready_to_commit"], false); |
| 1179 | let refused = fails(&b, &["commit", "-m", "x"]); |
| 1180 | assert!(refused.contains("braid resolve"), "{refused}"); |
| 1181 | let resolved = json(&b, &["resolve", "gone.txt"]); |
| 1182 | assert!(resolved["remaining"].as_array().unwrap().is_empty()); |
| 1183 | // Nothing to record, but a rebase to finish: commit can go ahead. |
| 1184 | let now = status(&b); |
| 1185 | assert_eq!(now["clean"], true); |
| 1186 | assert_eq!(now["ready_to_commit"], true); |
| 1187 | // Keeping the deletion leaves nothing of the change: the rebase ends |
| 1188 | // without a changeset. |
| 1189 | let committed = json(&b, &["commit"]); |
| 1190 | assert!(committed["changeset"].is_null()); |
| 1191 | assert_eq!(committed["rebase"]["outcome"], "finished"); |
| 1192 | assert_eq!(status(&b)["base"].as_str(), repo.main().as_deref()); |
| 1193 | assert_eq!(json(&b, &["land"])["outcome"], "nothing"); |
| 1194 | } |
| 1195 | |
| 1196 | /// Eight processes, each with its own workspace, edit their own file and |
| 1197 | /// their own line of a shared file, commit and land, round after round, |
| 1198 | /// all at once. Afterwards every change is on main exactly once, main's |
| 1199 | /// history is linear, and the store is clean. |
| 1200 | #[test] |
| 1201 | fn eight_agents_land_at_once() { |
| 1202 | const AGENTS: usize = 8; |
| 1203 | const ROUNDS: usize = 4; |
| 1204 | let repo = Repo::new(); |
| 1205 | // One line per agent, with two untouched lines between them, so that |
| 1206 | // edits to different agents' lines merge. |
| 1207 | let shared: String = (0..AGENTS) |
| 1208 | .map(|i| format!("agent {i}: start\n--\n--\n")) |
| 1209 | .collect(); |
| 1210 | seed(&repo, &[("shared.txt", &shared)]); |
| 1211 | let dirs: Vec<PathBuf> = (0..AGENTS) |
| 1212 | .map(|i| repo.workspace(&format!("agent-{i}"))) |
| 1213 | .collect(); |
| 1214 | |
| 1215 | let made: Vec<Vec<String>> = std::thread::scope(|scope| { |
| 1216 | let handles: Vec<_> = dirs |
| 1217 | .iter() |
| 1218 | .enumerate() |
| 1219 | .map(|(i, dir)| { |
| 1220 | scope.spawn(move || { |
| 1221 | let mut commits = Vec::new(); |
| 1222 | for round in 0..ROUNDS { |
| 1223 | write( |
| 1224 | dir, |
| 1225 | &format!("own-{i}.txt"), |
| 1226 | &format!("agent {i} round {round}\n"), |
| 1227 | ); |
| 1228 | let text = read(dir, "shared.txt"); |
| 1229 | let lines: Vec<String> = text |
| 1230 | .lines() |
| 1231 | .enumerate() |
| 1232 | .map(|(n, line)| { |
| 1233 | if n == i * 3 { |
| 1234 | format!("agent {i}: round {round}") |
| 1235 | } else { |
| 1236 | line.to_owned() |
| 1237 | } |
| 1238 | }) |
| 1239 | .collect(); |
| 1240 | write(dir, "shared.txt", &(lines.join("\n") + "\n")); |
| 1241 | let committed = |
| 1242 | json(dir, &["commit", "-m", &format!("agent {i} round {round}")]); |
| 1243 | commits.push(committed["changeset"].as_str().unwrap().to_owned()); |
| 1244 | loop { |
| 1245 | let out = braid(dir, &["land", "--json"]); |
| 1246 | match out.status.code() { |
| 1247 | Some(0) => break, |
| 1248 | Some(2) => { |
| 1249 | // Someone else's change got in the way: |
| 1250 | // rebase onto it and try again. |
| 1251 | json(dir, &["update"]); |
| 1252 | } |
| 1253 | _ => panic!("land failed: {}", stderr(&out)), |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | commits |
| 1258 | }) |
| 1259 | }) |
| 1260 | .collect(); |
| 1261 | handles.into_iter().map(|h| h.join().unwrap()).collect() |
| 1262 | }); |
| 1263 | |
| 1264 | // Every changeset on main maps back to one of the changesets made, |
| 1265 | // through the rebases it went through. |
| 1266 | let log = history(&repo); |
| 1267 | assert_eq!(log.len(), AGENTS * ROUNDS + 1); |
| 1268 | let mut seen = HashMap::new(); |
| 1269 | for changeset in &log[..log.len() - 1] { |
| 1270 | assert_eq!(changeset["parents"].as_array().unwrap().len(), 1, "a merge"); |
| 1271 | let mut id = changeset["id"].as_str().unwrap().to_owned(); |
| 1272 | let mut current = changeset.clone(); |
| 1273 | while let Some(from) = rebased_from(¤t) { |
| 1274 | current = json(&repo.root, &["show", &from]); |
| 1275 | id = from; |
| 1276 | } |
| 1277 | *seen.entry(id).or_insert(0) += 1; |
| 1278 | } |
| 1279 | let all: HashSet<String> = made.iter().flatten().cloned().collect(); |
| 1280 | assert_eq!(all.len(), AGENTS * ROUNDS); |
| 1281 | assert_eq!(seen.keys().cloned().collect::<HashSet<_>>(), all); |
| 1282 | assert!(seen.values().all(|count| *count == 1), "{seen:?}"); |
| 1283 | |
| 1284 | // A fresh workspace has every agent's last round. |
| 1285 | let check = repo.workspace("check"); |
| 1286 | let text = read(&check, "shared.txt"); |
| 1287 | for i in 0..AGENTS { |
| 1288 | assert_eq!( |
| 1289 | read(&check, &format!("own-{i}.txt")), |
| 1290 | format!("agent {i} round {}\n", ROUNDS - 1) |
| 1291 | ); |
| 1292 | assert!( |
| 1293 | text.contains(&format!("agent {i}: round {}\n", ROUNDS - 1)), |
| 1294 | "{text}" |
| 1295 | ); |
| 1296 | } |
| 1297 | assert!(repo.fsck_is_clean()); |
| 1298 | } |
| 1299 | |
| 1300 | #[test] |
| 1301 | fn workspaces_made_before_main_existed_land_without_an_update() { |
| 1302 | // Both workspaces start on an empty branch, so their first changesets |
| 1303 | // have no parent. The second to land is rebased from the empty tree. |
| 1304 | let repo = Repo::new(); |
| 1305 | let a = repo.workspace("first-a"); |
| 1306 | let b = repo.workspace("first-b"); |
| 1307 | write(&a, "a.txt", "from a\n"); |
| 1308 | write(&b, "b.txt", "from b\n"); |
| 1309 | json(&a, &["commit", "-m", "a"]); |
| 1310 | json(&b, &["commit", "-m", "b"]); |
| 1311 | assert_eq!(json(&a, &["land"])["outcome"], "fast-forward"); |
| 1312 | let landed = json(&b, &["land"]); |
| 1313 | assert_eq!(landed["outcome"], "rebased"); |
| 1314 | assert_eq!(read(&b, "a.txt"), "from a\n"); |
| 1315 | |
| 1316 | // The same path added on both sides is a conflict, never an overwrite. |
| 1317 | let c = repo.workspace("first-c"); |
| 1318 | let d = repo.workspace("first-d"); |
| 1319 | write(&c, "same.txt", "from c\n"); |
| 1320 | write(&d, "same.txt", "from d\n"); |
| 1321 | json(&c, &["commit", "-m", "c"]); |
| 1322 | json(&d, &["commit", "-m", "d"]); |
| 1323 | json(&c, &["land"]); |
| 1324 | let conflict = json_status(&d, &["land"], 2); |
| 1325 | assert_eq!(conflict["conflicts"][0]["path"], "same.txt"); |
| 1326 | assert!(repo.fsck_is_clean()); |
| 1327 | } |