utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | 0cb9223ef0a0b6a8f73866a6b0d477be18edabeee996614b2c07ccdbd41ff1e3 |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 23:57 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-19 11:31 +02:00 |
| Parents | dc39ccb1ba58 |
9 files changed
modified README.md +9 −0
| @@ -343,9 +343,18 @@ | ||
| 343 | 343 | remote only ever fast-forwards and its history is never rewritten. |
| 344 | 344 | Conflicts move nothing and exit with status 2. |
| 345 | 345 | |
| 346 | + By default a sync goes both ways, so a commit that someone else pushed to | |
| 347 | + the remote is merged into braid. `--direction publish` only pushes: it | |
| 348 | + stops, with exit status 3 and outcome `diverged`, unless the remote branch | |
| 349 | + is braid's or one of its ancestors. `--direction follow` only takes the | |
| 350 | + remote's commits in, and stops the same way when braid has changesets of | |
| 351 | + its own or the remote went back. Neither records, merges or pushes | |
| 352 | + anything when it stops. | |
| 353 | + | |
| 346 | 354 | ```bash |
| 347 | 355 | braid git sync https://github.com/you/project.git --branch main |
| 348 | 356 | braid git sync https://github.com/you/project.git --dry-run --json |
| 357 | + braid git sync https://github.com/you/project.git --direction publish | |
| 349 | 358 | ``` |
| 350 | 359 | - Braid contains no code from git itself, which is GPLv2. It reads and writes |
| 351 | 360 | git data with gitoxide (MIT or Apache-2.0); `git sync` also runs the `git` |
modified crates/cli/src/agents.rs +5 −3
| @@ -333,9 +333,11 @@ | ||
| 333 | 333 | Err(err) => return Err(err.into()), |
| 334 | 334 | }; |
| 335 | 335 | let repo = match (&cli.repo, &location) { |
| 336 | - (Some(root), _) => Some(Repo::open(root)?), | |
| 337 | - (None, Some(Location::Root(dir))) => Some(Repo::open(dir)?), | |
| 338 | - (None, Some(Location::Workspace { link, .. })) => Some(Repo::open(&link.repository)?), | |
| 336 | + (Some(root), _) => Some(Repo::open_with(root, cli.store_options())?), | |
| 337 | + (None, Some(Location::Root(dir))) => Some(Repo::open_with(dir, cli.store_options())?), | |
| 338 | + (None, Some(Location::Workspace { link, .. })) => { | |
| 339 | + Some(Repo::open_with(&link.repository, cli.store_options())?) | |
| 340 | + } | |
| 339 | 341 | (None, None) => None, |
| 340 | 342 | }; |
| 341 | 343 | // What the current directory is in counts only when it belongs to |
modified crates/cli/src/main.rs +115 −8
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | use clap::parser::ValueSource; |
| 25 | 25 | use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand}; |
| 26 | 26 | use serde_json::{Value, json}; |
| 27 | +use sync::Direction; | |
| 27 | 28 | |
| 28 | 29 | /// Version control for many agents landing changes at once. |
| 29 | 30 | #[derive(Debug, Parser)] |
| @@ -51,6 +52,18 @@ | ||
| 51 | 52 | #[arg(long, global = true, value_name = "NAME")] |
| 52 | 53 | workspace: Option<String>, |
| 53 | 54 | |
| 55 | + /// How hard the store pushes writes to stable storage: `ordered` may | |
| 56 | + /// lose the last operations on power loss, never consistency; `full` | |
| 57 | + /// keeps everything a command acknowledged, at some cost. | |
| 58 | + #[arg( | |
| 59 | + long, | |
| 60 | + global = true, | |
| 61 | + value_enum, | |
| 62 | + env = "BRAID_DURABILITY", | |
| 63 | + default_value_t = DurabilityArg::Ordered | |
| 64 | + )] | |
| 65 | + durability: DurabilityArg, | |
| 66 | + | |
| 54 | 67 | #[command(subcommand)] |
| 55 | 68 | command: Command, |
| 56 | 69 | |
| @@ -60,7 +73,27 @@ | ||
| 60 | 73 | given: String, |
| 61 | 74 | } |
| 62 | 75 | |
| 76 | +/// `--durability`. | |
| 77 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] | |
| 78 | +enum DurabilityArg { | |
| 79 | + /// Consistent after a crash; the last operations may be lost. | |
| 80 | + Ordered, | |
| 81 | + /// Everything acknowledged survives a power loss. | |
| 82 | + Full, | |
| 83 | +} | |
| 84 | + | |
| 63 | 85 | impl Cli { |
| 86 | + /// The store options `--durability` asks for. | |
| 87 | + pub(crate) fn store_options(&self) -> braid_store::Options { | |
| 88 | + braid_store::Options { | |
| 89 | + durability: match self.durability { | |
| 90 | + DurabilityArg::Ordered => braid_store::Durability::Ordered, | |
| 91 | + DurabilityArg::Full => braid_store::Durability::Full, | |
| 92 | + }, | |
| 93 | + ..braid_store::Options::default() | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 64 | 97 | /// A command for a hint to print: `braid`, the global flags this |
| 65 | 98 | /// command was given (`--repo`, `--agent`, `--workspace`), then `rest`, |
| 66 | 99 | /// so that a hint followed as written acts on the same workspace, for |
| @@ -311,8 +344,10 @@ | ||
| 311 | 344 | /// Keep a braid branch and a branch of a git remote in step: fetch and |
| 312 | 345 | /// import the remote branch, then fast-forward the braid branch, or push |
| 313 | 346 | /// it (merging first when both moved) as a fast-forward with a lease, so |
| 314 | - /// the remote's history is never rewritten. Exits with 2 on conflicts and | |
| 315 | - /// 1 when the push is refused. | |
| 347 | + /// the remote's history is never rewritten. By default a remote that | |
| 348 | + /// someone else wrote to is merged in; `--direction publish` or `follow` | |
| 349 | + /// stops instead. Exits with 2 on conflicts, 3 when the branches are not | |
| 350 | + /// in the relation `--direction` requires, and 1 when the push is refused. | |
| 316 | 351 | Sync { |
| 317 | 352 | /// The git remote: a URL or a path. |
| 318 | 353 | remote: String, |
| @@ -322,6 +357,13 @@ | ||
| 322 | 357 | /// The branch of the remote (default: the braid branch's name). |
| 323 | 358 | #[arg(long, value_name = "NAME")] |
| 324 | 359 | remote_branch: Option<String>, |
| 360 | + /// Which way changes may go: `both` merges when both sides moved; | |
| 361 | + /// `publish` only pushes, and stops unless the remote branch is the | |
| 362 | + /// braid branch or one of its ancestors; `follow` only takes the | |
| 363 | + /// remote's commits in, and stops unless the braid branch is the | |
| 364 | + /// remote branch or one of its ancestors. | |
| 365 | + #[arg(long, value_enum, default_value_t = Direction::Both)] | |
| 366 | + direction: Direction, | |
| 325 | 367 | /// Report what would happen without writing anything. |
| 326 | 368 | #[arg(long)] |
| 327 | 369 | dry_run: bool, |
| @@ -338,12 +380,21 @@ | ||
| 338 | 380 | }, |
| 339 | 381 | } |
| 340 | 382 | |
| 383 | +/// The exit status of a command whose reader closed standard output early, | |
| 384 | +/// as a shell reports a process that SIGPIPE ended: 128 + 13. | |
| 385 | +const BROKEN_PIPE: i32 = 141; | |
| 386 | + | |
| 341 | 387 | fn main() -> ExitCode { |
| 388 | + quiet_on_broken_pipe(); | |
| 342 | 389 | let matches = Cli::command().get_matches(); |
| 343 | 390 | let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|err| err.exit()); |
| 344 | 391 | cli.given = given_flags(&cli, &matches); |
| 345 | 392 | match run(&cli) { |
| 346 | 393 | Ok(code) => code, |
| 394 | + // A reader that stopped early is no failure: say nothing, as git | |
| 395 | + // does. braid writes to no other pipe (git runs with no input), so a | |
| 396 | + // broken pipe is standard output's. | |
| 397 | + Err(err) if broken_pipe(&err) => ExitCode::from(BROKEN_PIPE as u8), | |
| 347 | 398 | Err(err) => { |
| 348 | 399 | eprintln!("braid: error: {err:#}"); |
| 349 | 400 | ExitCode::FAILURE |
| @@ -351,6 +402,50 @@ | ||
| 351 | 402 | } |
| 352 | 403 | } |
| 353 | 404 | |
| 405 | +/// Whether `err` comes from a write to a reader that went away. | |
| 406 | +fn broken_pipe(err: &anyhow::Error) -> bool { | |
| 407 | + err.chain().any(|cause| { | |
| 408 | + cause | |
| 409 | + .downcast_ref::<io::Error>() | |
| 410 | + .is_some_and(|err| err.kind() == io::ErrorKind::BrokenPipe) | |
| 411 | + || cause | |
| 412 | + .downcast_ref::<serde_json::Error>() | |
| 413 | + .is_some_and(|err| err.io_error_kind() == Some(io::ErrorKind::BrokenPipe)) | |
| 414 | + }) | |
| 415 | +} | |
| 416 | + | |
| 417 | +/// Makes `print!` and `println!` exit quietly, with [`BROKEN_PIPE`], once | |
| 418 | +/// the reader of standard output went away (`braid log | head`), instead | |
| 419 | +/// of panicking. Standard error is left alone. | |
| 420 | +fn quiet_on_broken_pipe() { | |
| 421 | + let default = std::panic::take_hook(); | |
| 422 | + std::panic::set_hook(Box::new(move |info| { | |
| 423 | + let payload = info.payload(); | |
| 424 | + let message = payload | |
| 425 | + .downcast_ref::<String>() | |
| 426 | + .map(String::as_str) | |
| 427 | + .or_else(|| payload.downcast_ref::<&str>().copied()) | |
| 428 | + .unwrap_or(""); | |
| 429 | + if message.starts_with("failed printing to stdout") | |
| 430 | + && (message.contains("Broken pipe") || message.contains("os error 32")) | |
| 431 | + { | |
| 432 | + std::process::exit(BROKEN_PIPE); | |
| 433 | + } | |
| 434 | + default(info); | |
| 435 | + })); | |
| 436 | +} | |
| 437 | + | |
| 438 | +/// Exits quietly with [`BROKEN_PIPE`] when a write to standard output failed | |
| 439 | +/// because its reader went away; any other error is returned. | |
| 440 | +fn stdout_written<T>(result: io::Result<T>) -> io::Result<T> { | |
| 441 | + if let Err(err) = &result | |
| 442 | + && err.kind() == io::ErrorKind::BrokenPipe | |
| 443 | + { | |
| 444 | + std::process::exit(BROKEN_PIPE); | |
| 445 | + } | |
| 446 | + result | |
| 447 | +} | |
| 448 | + | |
| 354 | 449 | fn run(cli: &Cli) -> Result<ExitCode> { |
| 355 | 450 | match &cli.command { |
| 356 | 451 | Command::Init { dir } => init(cli, dir.as_deref()), |
| @@ -384,9 +479,17 @@ | ||
| 384 | 479 | remote, |
| 385 | 480 | branch, |
| 386 | 481 | remote_branch, |
| 482 | + direction, | |
| 387 | 483 | dry_run, |
| 388 | 484 | }, |
| 389 | - } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run), | |
| 485 | + } => sync::git_sync( | |
| 486 | + cli, | |
| 487 | + remote, | |
| 488 | + branch, | |
| 489 | + remote_branch.as_deref(), | |
| 490 | + *direction, | |
| 491 | + *dry_run, | |
| 492 | + ), | |
| 390 | 493 | Command::Fsck => fsck(cli), |
| 391 | 494 | Command::Stats => stats(cli), |
| 392 | 495 | Command::Workspace { action } => work::workspace(cli, action), |
| @@ -402,16 +505,20 @@ | ||
| 402 | 505 | |
| 403 | 506 | fn open_repo(cli: &Cli) -> Result<Repo> { |
| 404 | 507 | let repo = match &cli.repo { |
| 405 | - Some(dir) => Repo::open(dir), | |
| 406 | - None => Repo::discover(&std::env::current_dir()?), | |
| 508 | + Some(dir) => Repo::open_with(dir, cli.store_options()), | |
| 509 | + None => Repo::discover_with(&std::env::current_dir()?, cli.store_options()), | |
| 407 | 510 | }; |
| 408 | 511 | Ok(repo?) |
| 409 | 512 | } |
| 410 | 513 | |
| 411 | 514 | fn print_json(value: &Value) -> Result<()> { |
| 515 | + // Serialized first, so that a closed pipe shows up as an I/O error here | |
| 516 | + // rather than inside serde_json's own error type. | |
| 517 | + let mut text = serde_json::to_vec(value)?; | |
| 518 | + text.push(b'\n'); | |
| 412 | 519 | let mut out = io::stdout().lock(); |
| 413 | - serde_json::to_writer(&mut out, value)?; | |
| 414 | - writeln!(out)?; | |
| 520 | + stdout_written(out.write_all(&text))?; | |
| 521 | + stdout_written(out.flush())?; | |
| 415 | 522 | Ok(()) |
| 416 | 523 | } |
| 417 | 524 | |
| @@ -420,7 +527,7 @@ | ||
| 420 | 527 | Some(dir) => dir.to_path_buf(), |
| 421 | 528 | None => std::env::current_dir()?, |
| 422 | 529 | }; |
| 423 | - let repo = Repo::init(&dir)?; | |
| 530 | + let repo = Repo::init_with(&dir, cli.store_options())?; | |
| 424 | 531 | if cli.json { |
| 425 | 532 | print_json(&json!({ "root": repo.root().to_string_lossy() }))?; |
| 426 | 533 | } else { |
modified crates/cli/src/sync.rs +41 −3
| @@ -7,7 +7,9 @@ | ||
| 7 | 7 | |
| 8 | 8 | use anyhow::Result; |
| 9 | 9 | use braid_format::{EntryKind, ObjectId}; |
| 10 | -use braid_repo::{Conflict, ConflictKind, HunkSide, SyncOptions, SyncOutcome, SyncReport}; | |
| 10 | +use braid_repo::{ | |
| 11 | + Conflict, ConflictKind, HunkSide, SyncDirection, SyncOptions, SyncOutcome, SyncReport, | |
| 12 | +}; | |
| 11 | 13 | use serde_json::{Value, json}; |
| 12 | 14 | |
| 13 | 15 | use crate::{Cli, open_repo, print_json}; |
| @@ -15,6 +17,31 @@ | ||
| 15 | 17 | /// Exit status when the sync found conflicts. |
| 16 | 18 | const CONFLICTS: u8 = 2; |
| 17 | 19 | |
| 20 | +/// Exit status when the branches are not in the relation `--direction` | |
| 21 | +/// requires. | |
| 22 | +const DIVERGED: u8 = 3; | |
| 23 | + | |
| 24 | +/// `--direction`: which way changes may go. | |
| 25 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] | |
| 26 | +pub(crate) enum Direction { | |
| 27 | + /// Both ways, merging when both sides moved. | |
| 28 | + Both, | |
| 29 | + /// Braid to the remote only. | |
| 30 | + Publish, | |
| 31 | + /// The remote to braid only. | |
| 32 | + Follow, | |
| 33 | +} | |
| 34 | + | |
| 35 | +impl From<Direction> for SyncDirection { | |
| 36 | + fn from(direction: Direction) -> Self { | |
| 37 | + match direction { | |
| 38 | + Direction::Both => SyncDirection::Both, | |
| 39 | + Direction::Publish => SyncDirection::Publish, | |
| 40 | + Direction::Follow => SyncDirection::Follow, | |
| 41 | + } | |
| 42 | + } | |
| 43 | +} | |
| 44 | + | |
| 18 | 45 | /// What the text report says to do about conflicts: the two sides meet in |
| 19 | 46 | /// git, and the guide for agents gives the steps. |
| 20 | 47 | const MERGE_IN_GIT: &str = "Merge them in git and push the merge, then sync again: https://braid.elffuss.com/agents.md shows how, under \"Keeping the git remote up to date\"."; |
| @@ -24,22 +51,27 @@ | ||
| 24 | 51 | remote: &str, |
| 25 | 52 | branch: &str, |
| 26 | 53 | remote_branch: Option<&str>, |
| 54 | + direction: Direction, | |
| 27 | 55 | dry_run: bool, |
| 28 | 56 | ) -> Result<ExitCode> { |
| 29 | 57 | let repo = open_repo(cli)?; |
| 30 | 58 | let options = SyncOptions { |
| 31 | 59 | remote_branch: remote_branch.map(str::to_owned), |
| 32 | 60 | dry_run, |
| 61 | + direction: direction.into(), | |
| 33 | 62 | ..SyncOptions::default() |
| 34 | 63 | }; |
| 35 | 64 | let report = repo.git_sync(remote, branch, &cli.agent, &options)?; |
| 36 | 65 | if cli.json { |
| 37 | - print_json(&report_json(&report))?; | |
| 66 | + let mut value = report_json(&report); | |
| 67 | + value["direction"] = Value::String(options.direction.code().to_owned()); | |
| 68 | + print_json(&value)?; | |
| 38 | 69 | } else { |
| 39 | 70 | print_text(&report); |
| 40 | 71 | } |
| 41 | 72 | Ok(match report.outcome { |
| 42 | 73 | SyncOutcome::Conflicts(_) => ExitCode::from(CONFLICTS), |
| 74 | + SyncOutcome::Diverged { .. } => ExitCode::from(DIVERGED), | |
| 43 | 75 | ref outcome if outcome.is_success() => ExitCode::SUCCESS, |
| 44 | 76 | _ => ExitCode::FAILURE, |
| 45 | 77 | }) |
| @@ -84,7 +116,7 @@ | ||
| 84 | 116 | SyncOutcome::RemoteMoved { found } => { |
| 85 | 117 | value["found"] = found.map_or(Value::Null, |oid| Value::String(oid.to_hex())); |
| 86 | 118 | } |
| 87 | - SyncOutcome::Rejected { reason } => { | |
| 119 | + SyncOutcome::Rejected { reason } | SyncOutcome::Diverged { reason } => { | |
| 88 | 120 | value["reason"] = Value::String(reason.clone()); |
| 89 | 121 | } |
| 90 | 122 | _ => {} |
| @@ -234,6 +266,12 @@ | ||
| 234 | 266 | eprintln!("{branch} is at the merge {}.", short(report.after)); |
| 235 | 267 | } |
| 236 | 268 | } |
| 269 | + SyncOutcome::Diverged { reason } => { | |
| 270 | + eprintln!( | |
| 271 | + "braid: error: {reason}: {branch} and {} were left as they were; nothing was recorded, merged or pushed.", | |
| 272 | + report.remote_branch | |
| 273 | + ); | |
| 274 | + } | |
| 237 | 275 | other => println!("{}", other.code()), |
| 238 | 276 | } |
| 239 | 277 | } |
modified crates/cli/src/work.rs +2 −2
| @@ -295,8 +295,8 @@ | ||
| 295 | 295 | match braid_repo::locate(&cwd)? { |
| 296 | 296 | Location::Workspace { dir, link } => { |
| 297 | 297 | let repo = match &cli.repo { |
| 298 | - Some(root) => Repo::open(root)?, | |
| 299 | - None => Repo::open(&link.repository)?, | |
| 298 | + Some(root) => Repo::open_with(root, cli.store_options())?, | |
| 299 | + None => Repo::open_with(&link.repository, cli.store_options())?, | |
| 300 | 300 | }; |
| 301 | 301 | Ok(Target { |
| 302 | 302 | repo, |
modified crates/cli/tests/cli.rs +115 −0
| @@ -544,3 +544,118 @@ | ||
| 544 | 544 | assert_ne!(refs["refs"]["feature"], imported.as_str()); |
| 545 | 545 | assert_eq!(run_json(braid_in(&repo).arg("fsck"))["clean"], true); |
| 546 | 546 | } |
| 547 | + | |
| 548 | +/// A reader that stops early, as `braid log | head` does, is no failure: | |
| 549 | +/// braid exits quietly with 141, as a shell reports a process that SIGPIPE | |
| 550 | +/// ended, in text and in JSON alike. | |
| 551 | +#[cfg(unix)] | |
| 552 | +#[test] | |
| 553 | +fn a_reader_that_stops_early_gets_a_quiet_141() { | |
| 554 | + use std::io::Read; | |
| 555 | + let dir = tempfile::tempdir().unwrap(); | |
| 556 | + let source = dir.path().join("source"); | |
| 557 | + let git = |args: &[&str], cwd: &std::path::Path| { | |
| 558 | + let output = Command::new("git") | |
| 559 | + .args(args) | |
| 560 | + .current_dir(cwd) | |
| 561 | + .env("GIT_CONFIG_GLOBAL", "/dev/null") | |
| 562 | + .env("GIT_CONFIG_NOSYSTEM", "1") | |
| 563 | + .output() | |
| 564 | + .unwrap(); | |
| 565 | + assert!(output.status.success(), "{output:?}"); | |
| 566 | + }; | |
| 567 | + git(&["init", "--quiet", "-b", "main", "source"], dir.path()); | |
| 568 | + // A history long enough that its log fills any pipe buffer. | |
| 569 | + let mut stream = String::new(); | |
| 570 | + for i in 1..=800 { | |
| 571 | + let message = format!("Commit number {i}, with a message long enough to fill the pipe\n"); | |
| 572 | + stream.push_str(&format!( | |
| 573 | + "commit refs/heads/main\nmark :{i}\ncommitter A <a@example.org> {} +0000\ndata {}\n{message}", | |
| 574 | + 1_700_000_000 + i, | |
| 575 | + message.len() | |
| 576 | + )); | |
| 577 | + if i > 1 { | |
| 578 | + stream.push_str(&format!("from :{}\n", i - 1)); | |
| 579 | + } | |
| 580 | + stream.push('\n'); | |
| 581 | + } | |
| 582 | + let mut import = Command::new("git") | |
| 583 | + .args(["fast-import", "--quiet"]) | |
| 584 | + .current_dir(&source) | |
| 585 | + .stdin(Stdio::piped()) | |
| 586 | + .spawn() | |
| 587 | + .unwrap(); | |
| 588 | + import | |
| 589 | + .stdin | |
| 590 | + .take() | |
| 591 | + .unwrap() | |
| 592 | + .write_all(stream.as_bytes()) | |
| 593 | + .unwrap(); | |
| 594 | + assert!(import.wait().unwrap().success()); | |
| 595 | + let repo = dir.path().join("repo"); | |
| 596 | + assert!(braid().arg("init").arg(&repo).status().unwrap().success()); | |
| 597 | + assert!( | |
| 598 | + braid() | |
| 599 | + .args(["git", "import"]) | |
| 600 | + .arg(&source) | |
| 601 | + .arg("--repo") | |
| 602 | + .arg(&repo) | |
| 603 | + .output() | |
| 604 | + .unwrap() | |
| 605 | + .status | |
| 606 | + .success() | |
| 607 | + ); | |
| 608 | + for json in [false, true] { | |
| 609 | + let mut command = braid(); | |
| 610 | + command | |
| 611 | + .args(["log", "main", "-n", "100000", "--repo"]) | |
| 612 | + .arg(&repo); | |
| 613 | + if json { | |
| 614 | + command.arg("--json"); | |
| 615 | + } | |
| 616 | + let mut child = command | |
| 617 | + .stdout(Stdio::piped()) | |
| 618 | + .stderr(Stdio::piped()) | |
| 619 | + .spawn() | |
| 620 | + .unwrap(); | |
| 621 | + let mut start = [0u8; 10]; | |
| 622 | + child.stdout.take().unwrap().read_exact(&mut start).unwrap(); | |
| 623 | + // The reader goes away here, as head does. | |
| 624 | + let output = child.wait_with_output().unwrap(); | |
| 625 | + assert_eq!(output.status.code(), Some(141), "json {json}: {output:?}"); | |
| 626 | + assert!(output.stderr.is_empty(), "json {json}: {output:?}"); | |
| 627 | + } | |
| 628 | +} | |
| 629 | + | |
| 630 | +#[test] | |
| 631 | +fn durability_full_opens_and_writes() { | |
| 632 | + let dir = tempfile::tempdir().unwrap(); | |
| 633 | + let repo = dir.path().join("repo"); | |
| 634 | + let init = braid() | |
| 635 | + .args(["--durability", "full", "init"]) | |
| 636 | + .arg(&repo) | |
| 637 | + .output() | |
| 638 | + .unwrap(); | |
| 639 | + assert!(init.status.success(), "{init:?}"); | |
| 640 | + let file = dir.path().join("a.txt"); | |
| 641 | + std::fs::write(&file, "durable\n").unwrap(); | |
| 642 | + let created = braid() | |
| 643 | + .env("BRAID_DURABILITY", "full") | |
| 644 | + .env("BRAID_AUTHOR", "Ada <ada@example.org>") | |
| 645 | + .args([ | |
| 646 | + "change", "create", "--base", "none", "-m", "First", "--land", "main", | |
| 647 | + ]) | |
| 648 | + .arg("--set") | |
| 649 | + .arg(format!("a.txt=@{}", file.display())) | |
| 650 | + .arg("--repo") | |
| 651 | + .arg(&repo) | |
| 652 | + .output() | |
| 653 | + .unwrap(); | |
| 654 | + assert!(created.status.success(), "{created:?}"); | |
| 655 | + let refused = braid() | |
| 656 | + .args(["--durability", "sometimes", "refs", "--repo"]) | |
| 657 | + .arg(&repo) | |
| 658 | + .output() | |
| 659 | + .unwrap(); | |
| 660 | + assert_eq!(refused.status.code(), Some(2)); | |
| 661 | +} |
modified crates/cli/tests/git_sync.rs +97 −0
| @@ -415,3 +415,100 @@ | ||
| 415 | 415 | assert_eq!(report["remote_branch"], "trunk"); |
| 416 | 416 | assert_eq!(world.refs()["work"], report["after"]); |
| 417 | 417 | } |
| 418 | + | |
| 419 | +impl World { | |
| 420 | + fn sync_direction(&self, direction: &str) -> (Option<i32>, Value) { | |
| 421 | + self.braid_json(&[ | |
| 422 | + "git", | |
| 423 | + "sync", | |
| 424 | + self.remote.to_str().unwrap(), | |
| 425 | + "--direction", | |
| 426 | + direction, | |
| 427 | + ]) | |
| 428 | + } | |
| 429 | + | |
| 430 | + /// Puts braid ahead of the remote: it imports a commit the remote does | |
| 431 | + /// not have. | |
| 432 | + fn braid_ahead(&self, files: &[(&str, &str)]) { | |
| 433 | + let (upstream, _) = self.commit("upstream", files, "Braid's own"); | |
| 434 | + let import = self.braid(&["git", "import", upstream.to_str().unwrap()]); | |
| 435 | + assert!(import.status.success()); | |
| 436 | + } | |
| 437 | +} | |
| 438 | + | |
| 439 | +#[test] | |
| 440 | +fn publish_stops_when_someone_else_wrote_to_the_remote() { | |
| 441 | + let world = World::new(); | |
| 442 | + world.push(&[("a", "1\n"), ("b", "1\n")], "First"); | |
| 443 | + world.sync(); | |
| 444 | + world.braid_ahead(&[("a", "braid\n")]); | |
| 445 | + let theirs = world.push(&[("b", "theirs\n")], "Pushed past braid"); | |
| 446 | + | |
| 447 | + let refs = world.refs(); | |
| 448 | + let operations = world.operations(); | |
| 449 | + for args in [&["--dry-run"][..], &[]] { | |
| 450 | + let mut command = vec!["git", "sync", world.remote.to_str().unwrap()]; | |
| 451 | + command.extend(["--direction", "publish"]); | |
| 452 | + command.extend(args); | |
| 453 | + let (code, report) = world.braid_json(&command); | |
| 454 | + assert_eq!(code, Some(3), "{report}"); | |
| 455 | + assert_eq!(report["outcome"], "diverged"); | |
| 456 | + assert_eq!(report["direction"], "publish"); | |
| 457 | + assert!(report["reason"].as_str().unwrap().contains("remote")); | |
| 458 | + assert_eq!(report["pushed"], Value::Null); | |
| 459 | + assert_eq!(report["operations"], Value::Array(Vec::new())); | |
| 460 | + } | |
| 461 | + // Nothing was recorded, merged or pushed. | |
| 462 | + assert_eq!(world.refs(), refs); | |
| 463 | + assert_eq!(world.operations(), operations); | |
| 464 | + assert_eq!(world.remote_head(), theirs); | |
| 465 | +} | |
| 466 | + | |
| 467 | +#[test] | |
| 468 | +fn publish_pushes_when_only_braid_moved() { | |
| 469 | + let world = World::new(); | |
| 470 | + world.push(&[("a", "1\n")], "First"); | |
| 471 | + world.sync(); | |
| 472 | + world.braid_ahead(&[("a", "braid\n")]); | |
| 473 | + let (code, report) = world.sync_direction("publish"); | |
| 474 | + assert_eq!(code, Some(0), "{report}"); | |
| 475 | + assert_eq!(report["outcome"], "pushed"); | |
| 476 | + assert_eq!(world.remote_head(), report["pushed"].as_str().unwrap()); | |
| 477 | + world.assert_forward_only(); | |
| 478 | +} | |
| 479 | + | |
| 480 | +#[test] | |
| 481 | +fn follow_takes_the_remote_in_and_stops_on_braid_work_or_a_rewind() { | |
| 482 | + let world = World::new(); | |
| 483 | + let first = world.push(&[("a", "1\n")], "First"); | |
| 484 | + world.sync(); | |
| 485 | + | |
| 486 | + // Only the remote moved: follow fast-forwards. | |
| 487 | + world.push(&[("a", "2\n")], "Second"); | |
| 488 | + let (code, report) = world.sync_direction("follow"); | |
| 489 | + assert_eq!(code, Some(0), "{report}"); | |
| 490 | + assert_eq!(report["outcome"], "fast_forwarded"); | |
| 491 | + | |
| 492 | + // Braid has a changeset of its own: follow stops and pushes nothing. | |
| 493 | + let head = world.remote_head(); | |
| 494 | + world.braid_ahead(&[("b", "braid\n")]); | |
| 495 | + let refs = world.refs(); | |
| 496 | + let (code, report) = world.sync_direction("follow"); | |
| 497 | + assert_eq!(code, Some(3), "{report}"); | |
| 498 | + assert_eq!(report["outcome"], "diverged"); | |
| 499 | + assert_eq!(world.refs(), refs); | |
| 500 | + assert_eq!(world.remote_head(), head); | |
| 501 | + | |
| 502 | + // The remote went back: follow stops too. | |
| 503 | + let world = World::new(); | |
| 504 | + world.push(&[("a", "1\n")], "First"); | |
| 505 | + world.push(&[("a", "2\n")], "Second"); | |
| 506 | + world.sync(); | |
| 507 | + git( | |
| 508 | + &world.remote, | |
| 509 | + &["update-ref", "refs/heads/main", first.as_str()], | |
| 510 | + ); | |
| 511 | + let (code, report) = world.sync_direction("follow"); | |
| 512 | + assert_eq!(code, Some(3), "{report}"); | |
| 513 | + assert_eq!(report["outcome"], "diverged"); | |
| 514 | +} |
modified crates/repo/src/lib.rs +21 −5
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | pub use history::{RepoHistory, StoreIndex}; |
| 51 | 51 | pub use link::{Location, WORK_DIR, WORKSPACES_DIR, WorkspaceLink, locate}; |
| 52 | 52 | pub use remote::Remote; |
| 53 | -pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport}; | |
| 53 | +pub use sync::{MIRRORS_DIR, SyncDirection, SyncOptions, SyncOutcome, SyncReport}; | |
| 54 | 54 | |
| 55 | 55 | /// Name of the directory that holds a repository's data. |
| 56 | 56 | pub const DIR: &str = ".braid"; |
| @@ -201,12 +201,18 @@ | ||
| 201 | 201 | impl Repo { |
| 202 | 202 | /// Creates a repository in `dir`, which is created if needed. |
| 203 | 203 | pub fn init(dir: &Path) -> Result<Repo, Error> { |
| 204 | + Repo::init_with(dir, Options::default()) | |
| 205 | + } | |
| 206 | + | |
| 207 | + /// Creates a repository in `dir` with the store opened with `options`: | |
| 208 | + /// a server passes [`Durability::Full`](braid_store::Durability::Full). | |
| 209 | + pub fn init_with(dir: &Path, options: Options) -> Result<Repo, Error> { | |
| 204 | 210 | let store_dir = dir.join(DIR).join(STORE_DIR); |
| 205 | 211 | if store_dir.exists() { |
| 206 | 212 | return Err(Error::AlreadyExists); |
| 207 | 213 | } |
| 208 | 214 | fs::create_dir_all(dir.join(DIR))?; |
| 209 | - let store = Store::init(&store_dir, Options::default())?; | |
| 215 | + let store = Store::init(&store_dir, options)?; | |
| 210 | 216 | Ok(Repo { |
| 211 | 217 | root: dir.to_path_buf(), |
| 212 | 218 | store, |
| @@ -216,11 +222,16 @@ | ||
| 216 | 222 | |
| 217 | 223 | /// Opens the repository whose root is `dir`. |
| 218 | 224 | pub fn open(dir: &Path) -> Result<Repo, Error> { |
| 225 | + Repo::open_with(dir, Options::default()) | |
| 226 | + } | |
| 227 | + | |
| 228 | + /// Opens the repository whose root is `dir`, its store with `options`. | |
| 229 | + pub fn open_with(dir: &Path, options: Options) -> Result<Repo, Error> { | |
| 219 | 230 | let store_dir = dir.join(DIR).join(STORE_DIR); |
| 220 | 231 | if !store_dir.is_dir() { |
| 221 | 232 | return Err(Error::NotFound); |
| 222 | 233 | } |
| 223 | - let store = Store::open(&store_dir, Options::default())?; | |
| 234 | + let store = Store::open(&store_dir, options)?; | |
| 224 | 235 | Ok(Repo { |
| 225 | 236 | root: dir.to_path_buf(), |
| 226 | 237 | store, |
| @@ -232,9 +243,14 @@ | ||
| 232 | 243 | /// nearest parent with a `.braid` directory, or the repository named by |
| 233 | 244 | /// the `.braid` file of the workspace that contains `start`. |
| 234 | 245 | pub fn discover(start: &Path) -> Result<Repo, Error> { |
| 246 | + Repo::discover_with(start, Options::default()) | |
| 247 | + } | |
| 248 | + | |
| 249 | + /// [`Repo::discover`], with the store opened with `options`. | |
| 250 | + pub fn discover_with(start: &Path, options: Options) -> Result<Repo, Error> { | |
| 235 | 251 | match locate(start)? { |
| 236 | - Location::Root(dir) => Repo::open(&dir), | |
| 237 | - Location::Workspace { link, .. } => Repo::open(&link.repository), | |
| 252 | + Location::Root(dir) => Repo::open_with(&dir, options), | |
| 253 | + Location::Workspace { link, .. } => Repo::open_with(&link.repository, options), | |
| 238 | 254 | } |
| 239 | 255 | } |
| 240 | 256 |
modified crates/repo/src/sync.rs +85 −7
| @@ -34,6 +34,40 @@ | ||
| 34 | 34 | /// Environment variables to set for the git commands, on top of the |
| 35 | 35 | /// process's own. |
| 36 | 36 | pub git_env: Vec<(OsString, OsString)>, |
| 37 | + /// Which way changes may go. | |
| 38 | + pub direction: SyncDirection, | |
| 39 | +} | |
| 40 | + | |
| 41 | +/// Which way a sync may move changes. | |
| 42 | +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 43 | +pub enum SyncDirection { | |
| 44 | + /// Both ways: the braid branch takes what the remote has, the remote | |
| 45 | + /// takes what braid has, and when both moved they are merged and the | |
| 46 | + /// merge is pushed. Writes made to the remote by anyone else end up in | |
| 47 | + /// braid. | |
| 48 | + #[default] | |
| 49 | + Both, | |
| 50 | + /// Braid to the remote only: the remote branch must be the braid branch | |
| 51 | + /// or one of its ancestors, or absent. Anything else is | |
| 52 | + /// [`SyncOutcome::Diverged`], and nothing is recorded, merged or pushed. | |
| 53 | + Publish, | |
| 54 | + /// The remote to braid only: the braid branch must be the remote branch | |
| 55 | + /// or one of its ancestors, or absent. Anything else, a remote that went | |
| 56 | + /// back included, is [`SyncOutcome::Diverged`], and nothing is recorded | |
| 57 | + /// or pushed. | |
| 58 | + Follow, | |
| 59 | +} | |
| 60 | + | |
| 61 | +impl SyncDirection { | |
| 62 | + /// The name used on the command line and in reports: `both`, `publish` | |
| 63 | + /// or `follow`. | |
| 64 | + pub fn code(self) -> &'static str { | |
| 65 | + match self { | |
| 66 | + SyncDirection::Both => "both", | |
| 67 | + SyncDirection::Publish => "publish", | |
| 68 | + SyncDirection::Follow => "follow", | |
| 69 | + } | |
| 70 | + } | |
| 37 | 71 | } |
| 38 | 72 | |
| 39 | 73 | /// What a sync did, or would do. |
| @@ -74,12 +108,18 @@ | ||
| 74 | 108 | /// Git's reason. |
| 75 | 109 | reason: String, |
| 76 | 110 | }, |
| 111 | + /// The branches are not in the relation the [`SyncDirection`] requires. | |
| 112 | + /// Nothing was recorded, merged or pushed. | |
| 113 | + Diverged { | |
| 114 | + /// What was found. | |
| 115 | + reason: String, | |
| 116 | + }, | |
| 77 | 117 | } |
| 78 | 118 | |
| 79 | 119 | impl SyncOutcome { |
| 80 | 120 | /// A short, stable name for the outcome, for reports and JSON: |
| 81 | 121 | /// `up_to_date`, `created`, `fast_forwarded`, `pushed`, `merged`, |
| 82 | - /// `conflicts`, `remote_moved` or `rejected`. | |
| 122 | + /// `conflicts`, `remote_moved`, `rejected` or `diverged`. | |
| 83 | 123 | pub fn code(&self) -> &'static str { |
| 84 | 124 | match self { |
| 85 | 125 | SyncOutcome::UpToDate => "up_to_date", |
| @@ -90,17 +130,19 @@ | ||
| 90 | 130 | SyncOutcome::Conflicts(_) => "conflicts", |
| 91 | 131 | SyncOutcome::RemoteMoved { .. } => "remote_moved", |
| 92 | 132 | SyncOutcome::Rejected { .. } => "rejected", |
| 133 | + SyncOutcome::Diverged { .. } => "diverged", | |
| 93 | 134 | } |
| 94 | 135 | } |
| 95 | 136 | |
| 96 | 137 | /// Whether the two branches are in step at the end: every outcome but |
| 97 | - /// conflicts and refused pushes. | |
| 138 | + /// conflicts, refused pushes and divergence. | |
| 98 | 139 | pub fn is_success(&self) -> bool { |
| 99 | 140 | !matches!( |
| 100 | 141 | self, |
| 101 | 142 | SyncOutcome::Conflicts(_) |
| 102 | 143 | | SyncOutcome::RemoteMoved { .. } |
| 103 | 144 | | SyncOutcome::Rejected { .. } |
| 145 | + | SyncOutcome::Diverged { .. } | |
| 104 | 146 | ) |
| 105 | 147 | } |
| 106 | 148 | } |
| @@ -147,6 +189,7 @@ | ||
| 147 | 189 | merged_paths: Vec<Vec<u8>>, |
| 148 | 190 | }, |
| 149 | 191 | Conflicts(Vec<Conflict>), |
| 192 | + Diverged(String), | |
| 150 | 193 | } |
| 151 | 194 | |
| 152 | 195 | /// The state after fetching and importing. |
| @@ -212,6 +255,14 @@ | ||
| 212 | 255 | /// |
| 213 | 256 | /// The braid branch only ever moves with a compare and swap, in one |
| 214 | 257 | /// operation with the git map and `remote/<label>/<branch>`. |
| 258 | + /// | |
| 259 | + /// [`SyncOptions::direction`] restricts this. With | |
| 260 | + /// [`SyncDirection::Publish`] only the first and the fourth case go | |
| 261 | + /// ahead (and creating the remote branch); with | |
| 262 | + /// [`SyncDirection::Follow`] only the first three. Any other case is | |
| 263 | + /// [`SyncOutcome::Diverged`]: no merge is made, and no ref, map entry | |
| 264 | + /// or remote branch moves. The objects of the fetched commits may stay | |
| 265 | + /// in the store, which only appends. | |
| 215 | 266 | /// 4. A push is atomic and leased: `git push --atomic --porcelain |
| 216 | 267 | /// --force-with-lease=refs/heads/<branch>:<fetched> <remote> |
| 217 | 268 | /// <commit>:refs/heads/<branch>`, where `<fetched>` is G's commit as |
| @@ -343,6 +394,8 @@ | ||
| 343 | 394 | tracking_ref: String, |
| 344 | 395 | /// The directory of the mirrors, absolute. |
| 345 | 396 | mirrors: PathBuf, |
| 397 | + /// Which way changes may go. | |
| 398 | + direction: SyncDirection, | |
| 346 | 399 | } |
| 347 | 400 | |
| 348 | 401 | impl<'r> Sync<'r> { |
| @@ -371,6 +424,7 @@ | ||
| 371 | 424 | remote_branch, |
| 372 | 425 | remote, |
| 373 | 426 | agent, |
| 427 | + direction: options.direction, | |
| 374 | 428 | }) |
| 375 | 429 | } |
| 376 | 430 | |
| @@ -481,12 +535,34 @@ | ||
| 481 | 535 | prepared: &Prepared, |
| 482 | 536 | ) -> Result<Decision, Error> { |
| 483 | 537 | let remote = prepared.fetched.map(|(_, changeset)| changeset); |
| 484 | - Ok(match (prepared.head, remote) { | |
| 485 | - (None, None) => { | |
| 486 | - return Err(Error::NothingToSync { | |
| 487 | - branch: self.branch.clone(), | |
| 488 | - }); | |
| 538 | + if let (None, None) = (prepared.head, remote) { | |
| 539 | + return Err(Error::NothingToSync { | |
| 540 | + branch: self.branch.clone(), | |
| 541 | + }); | |
| 542 | + } | |
| 543 | + let diverged = |why: &str| Ok(Decision::Diverged(why.to_owned())); | |
| 544 | + match (self.direction, prepared.head, remote) { | |
| 545 | + (SyncDirection::Both, ..) => {} | |
| 546 | + (SyncDirection::Publish, None, Some(_)) => { | |
| 547 | + return diverged("braid has no such branch, and the remote has one"); | |
| 489 | 548 | } |
| 549 | + (SyncDirection::Publish, Some(head), Some(remote)) | |
| 550 | + if head != remote && !is_ancestor(objects, remote, head)? => | |
| 551 | + { | |
| 552 | + return diverged("the remote branch has commits the braid branch does not have"); | |
| 553 | + } | |
| 554 | + (SyncDirection::Follow, Some(_), None) => { | |
| 555 | + return diverged("the remote has no such branch, and braid has one"); | |
| 556 | + } | |
| 557 | + (SyncDirection::Follow, Some(head), Some(remote)) | |
| 558 | + if head != remote && !is_ancestor(objects, head, remote)? => | |
| 559 | + { | |
| 560 | + return diverged("the braid branch has changesets the remote branch does not have"); | |
| 561 | + } | |
| 562 | + _ => {} | |
| 563 | + } | |
| 564 | + Ok(match (prepared.head, remote) { | |
| 565 | + (None, None) => unreachable!("handled above"), | |
| 490 | 566 | (None, Some(remote)) => Decision::Create(remote), |
| 491 | 567 | (Some(head), None) => Decision::Push(head), |
| 492 | 568 | (Some(head), Some(remote)) if head == remote => Decision::UpToDate, |
| @@ -578,6 +654,7 @@ | ||
| 578 | 654 | SyncOutcome::FastForwarded |
| 579 | 655 | } |
| 580 | 656 | Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts), |
| 657 | + Decision::Diverged(reason) => SyncOutcome::Diverged { reason }, | |
| 581 | 658 | Decision::Push(target) => { |
| 582 | 659 | let commit = self.export(mirror, map, target)?; |
| 583 | 660 | match self.push(mirror, commit, fetched)? { |
| @@ -744,6 +821,7 @@ | ||
| 744 | 821 | } |
| 745 | 822 | } |
| 746 | 823 | Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts), |
| 824 | + Decision::Diverged(reason) => SyncOutcome::Diverged { reason }, | |
| 747 | 825 | }; |
| 748 | 826 | Ok(report) |
| 749 | 827 | } |