Elffuss BraidHub

utopia-ia/elffuss-braid public

git sync --direction, --durability full, and a quiet exit on a closed pipe

git sync went both ways only: a commit someone else pushed to the remote
was merged into braid and the merge pushed back, with exit status 0.
--direction publish only pushes and stops unless the remote branch is
braid's or one of its ancestors; --direction follow only takes the
remote's commits in and stops when braid has changesets of its own or the
remote went back. Either stops with exit status 3 and outcome "diverged",
and records, merges and pushes nothing. Both, the default, is unchanged
and the README now says what it does with someone else's commits.

--durability full (or BRAID_DURABILITY=full) opens the store so that
everything a command acknowledged survives a power loss, through
Repo::init_with, open_with and discover_with.

A reader that stops early, as in braid log | head, now gets a quiet exit
with status 141 instead of "Broken pipe" and status 1, in text and JSON.
Changeset0cb9223ef0a0b6a8f73866a6b0d477be18edabeee996614b2c07ccdbd41ff1e3
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-17 23:57 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-19 11:31 +02:00
Parentsdc39ccb1ba58

Browse the files at this changeset

9 files changed

modified README.md +9 −0
@@ -343,9 +343,18 @@
343343 remote only ever fast-forwards and its history is never rewritten.
344344 Conflicts move nothing and exit with status 2.
345345
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+
346354 ```bash
347355 braid git sync https://github.com/you/project.git --branch main
348356 braid git sync https://github.com/you/project.git --dry-run --json
357+ braid git sync https://github.com/you/project.git --direction publish
349358 ```
350359 - Braid contains no code from git itself, which is GPLv2. It reads and writes
351360 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 @@
333333 Err(err) => return Err(err.into()),
334334 };
335335 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+ }
339341 (None, None) => None,
340342 };
341343 // What the current directory is in counts only when it belongs to
modified crates/cli/src/main.rs +115 −8
@@ -24,6 +24,7 @@
2424 use clap::parser::ValueSource;
2525 use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand};
2626 use serde_json::{Value, json};
27+use sync::Direction;
2728
2829 /// Version control for many agents landing changes at once.
2930 #[derive(Debug, Parser)]
@@ -51,6 +52,18 @@
5152 #[arg(long, global = true, value_name = "NAME")]
5253 workspace: Option<String>,
5354
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+
5467 #[command(subcommand)]
5568 command: Command,
5669
@@ -60,7 +73,27 @@
6073 given: String,
6174 }
6275
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+
6385 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+
6497 /// A command for a hint to print: `braid`, the global flags this
6598 /// command was given (`--repo`, `--agent`, `--workspace`), then `rest`,
6699 /// so that a hint followed as written acts on the same workspace, for
@@ -311,8 +344,10 @@
311344 /// Keep a braid branch and a branch of a git remote in step: fetch and
312345 /// import the remote branch, then fast-forward the braid branch, or push
313346 /// 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.
316351 Sync {
317352 /// The git remote: a URL or a path.
318353 remote: String,
@@ -322,6 +357,13 @@
322357 /// The branch of the remote (default: the braid branch's name).
323358 #[arg(long, value_name = "NAME")]
324359 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,
325367 /// Report what would happen without writing anything.
326368 #[arg(long)]
327369 dry_run: bool,
@@ -338,12 +380,21 @@
338380 },
339381 }
340382
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+
341387 fn main() -> ExitCode {
388+ quiet_on_broken_pipe();
342389 let matches = Cli::command().get_matches();
343390 let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|err| err.exit());
344391 cli.given = given_flags(&cli, &matches);
345392 match run(&cli) {
346393 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),
347398 Err(err) => {
348399 eprintln!("braid: error: {err:#}");
349400 ExitCode::FAILURE
@@ -351,6 +402,50 @@
351402 }
352403 }
353404
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+
354449 fn run(cli: &Cli) -> Result<ExitCode> {
355450 match &cli.command {
356451 Command::Init { dir } => init(cli, dir.as_deref()),
@@ -384,9 +479,17 @@
384479 remote,
385480 branch,
386481 remote_branch,
482+ direction,
387483 dry_run,
388484 },
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+ ),
390493 Command::Fsck => fsck(cli),
391494 Command::Stats => stats(cli),
392495 Command::Workspace { action } => work::workspace(cli, action),
@@ -402,16 +505,20 @@
402505
403506 fn open_repo(cli: &Cli) -> Result<Repo> {
404507 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()),
407510 };
408511 Ok(repo?)
409512 }
410513
411514 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');
412519 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())?;
415522 Ok(())
416523 }
417524
@@ -420,7 +527,7 @@
420527 Some(dir) => dir.to_path_buf(),
421528 None => std::env::current_dir()?,
422529 };
423- let repo = Repo::init(&dir)?;
530+ let repo = Repo::init_with(&dir, cli.store_options())?;
424531 if cli.json {
425532 print_json(&json!({ "root": repo.root().to_string_lossy() }))?;
426533 } else {
modified crates/cli/src/sync.rs +41 −3
@@ -7,7 +7,9 @@
77
88 use anyhow::Result;
99 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+};
1113 use serde_json::{Value, json};
1214
1315 use crate::{Cli, open_repo, print_json};
@@ -15,6 +17,31 @@
1517 /// Exit status when the sync found conflicts.
1618 const CONFLICTS: u8 = 2;
1719
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+
1845 /// What the text report says to do about conflicts: the two sides meet in
1946 /// git, and the guide for agents gives the steps.
2047 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 @@
2451 remote: &str,
2552 branch: &str,
2653 remote_branch: Option<&str>,
54+ direction: Direction,
2755 dry_run: bool,
2856 ) -> Result<ExitCode> {
2957 let repo = open_repo(cli)?;
3058 let options = SyncOptions {
3159 remote_branch: remote_branch.map(str::to_owned),
3260 dry_run,
61+ direction: direction.into(),
3362 ..SyncOptions::default()
3463 };
3564 let report = repo.git_sync(remote, branch, &cli.agent, &options)?;
3665 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)?;
3869 } else {
3970 print_text(&report);
4071 }
4172 Ok(match report.outcome {
4273 SyncOutcome::Conflicts(_) => ExitCode::from(CONFLICTS),
74+ SyncOutcome::Diverged { .. } => ExitCode::from(DIVERGED),
4375 ref outcome if outcome.is_success() => ExitCode::SUCCESS,
4476 _ => ExitCode::FAILURE,
4577 })
@@ -84,7 +116,7 @@
84116 SyncOutcome::RemoteMoved { found } => {
85117 value["found"] = found.map_or(Value::Null, |oid| Value::String(oid.to_hex()));
86118 }
87- SyncOutcome::Rejected { reason } => {
119+ SyncOutcome::Rejected { reason } | SyncOutcome::Diverged { reason } => {
88120 value["reason"] = Value::String(reason.clone());
89121 }
90122 _ => {}
@@ -234,6 +266,12 @@
234266 eprintln!("{branch} is at the merge {}.", short(report.after));
235267 }
236268 }
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+ }
237275 other => println!("{}", other.code()),
238276 }
239277 }
modified crates/cli/src/work.rs +2 −2
@@ -295,8 +295,8 @@
295295 match braid_repo::locate(&cwd)? {
296296 Location::Workspace { dir, link } => {
297297 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())?,
300300 };
301301 Ok(Target {
302302 repo,
modified crates/cli/tests/cli.rs +115 −0
@@ -544,3 +544,118 @@
544544 assert_ne!(refs["refs"]["feature"], imported.as_str());
545545 assert_eq!(run_json(braid_in(&repo).arg("fsck"))["clean"], true);
546546 }
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 @@
415415 assert_eq!(report["remote_branch"], "trunk");
416416 assert_eq!(world.refs()["work"], report["after"]);
417417 }
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 @@
5050 pub use history::{RepoHistory, StoreIndex};
5151 pub use link::{Location, WORK_DIR, WORKSPACES_DIR, WorkspaceLink, locate};
5252 pub use remote::Remote;
53-pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport};
53+pub use sync::{MIRRORS_DIR, SyncDirection, SyncOptions, SyncOutcome, SyncReport};
5454
5555 /// Name of the directory that holds a repository's data.
5656 pub const DIR: &str = ".braid";
@@ -201,12 +201,18 @@
201201 impl Repo {
202202 /// Creates a repository in `dir`, which is created if needed.
203203 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> {
204210 let store_dir = dir.join(DIR).join(STORE_DIR);
205211 if store_dir.exists() {
206212 return Err(Error::AlreadyExists);
207213 }
208214 fs::create_dir_all(dir.join(DIR))?;
209- let store = Store::init(&store_dir, Options::default())?;
215+ let store = Store::init(&store_dir, options)?;
210216 Ok(Repo {
211217 root: dir.to_path_buf(),
212218 store,
@@ -216,11 +222,16 @@
216222
217223 /// Opens the repository whose root is `dir`.
218224 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> {
219230 let store_dir = dir.join(DIR).join(STORE_DIR);
220231 if !store_dir.is_dir() {
221232 return Err(Error::NotFound);
222233 }
223- let store = Store::open(&store_dir, Options::default())?;
234+ let store = Store::open(&store_dir, options)?;
224235 Ok(Repo {
225236 root: dir.to_path_buf(),
226237 store,
@@ -232,9 +243,14 @@
232243 /// nearest parent with a `.braid` directory, or the repository named by
233244 /// the `.braid` file of the workspace that contains `start`.
234245 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> {
235251 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),
238254 }
239255 }
240256
modified crates/repo/src/sync.rs +85 −7
@@ -34,6 +34,40 @@
3434 /// Environment variables to set for the git commands, on top of the
3535 /// process's own.
3636 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+ }
3771 }
3872
3973 /// What a sync did, or would do.
@@ -74,12 +108,18 @@
74108 /// Git's reason.
75109 reason: String,
76110 },
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+ },
77117 }
78118
79119 impl SyncOutcome {
80120 /// A short, stable name for the outcome, for reports and JSON:
81121 /// `up_to_date`, `created`, `fast_forwarded`, `pushed`, `merged`,
82- /// `conflicts`, `remote_moved` or `rejected`.
122+ /// `conflicts`, `remote_moved`, `rejected` or `diverged`.
83123 pub fn code(&self) -> &'static str {
84124 match self {
85125 SyncOutcome::UpToDate => "up_to_date",
@@ -90,17 +130,19 @@
90130 SyncOutcome::Conflicts(_) => "conflicts",
91131 SyncOutcome::RemoteMoved { .. } => "remote_moved",
92132 SyncOutcome::Rejected { .. } => "rejected",
133+ SyncOutcome::Diverged { .. } => "diverged",
93134 }
94135 }
95136
96137 /// Whether the two branches are in step at the end: every outcome but
97- /// conflicts and refused pushes.
138+ /// conflicts, refused pushes and divergence.
98139 pub fn is_success(&self) -> bool {
99140 !matches!(
100141 self,
101142 SyncOutcome::Conflicts(_)
102143 | SyncOutcome::RemoteMoved { .. }
103144 | SyncOutcome::Rejected { .. }
145+ | SyncOutcome::Diverged { .. }
104146 )
105147 }
106148 }
@@ -147,6 +189,7 @@
147189 merged_paths: Vec<Vec<u8>>,
148190 },
149191 Conflicts(Vec<Conflict>),
192+ Diverged(String),
150193 }
151194
152195 /// The state after fetching and importing.
@@ -212,6 +255,14 @@
212255 ///
213256 /// The braid branch only ever moves with a compare and swap, in one
214257 /// 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.
215266 /// 4. A push is atomic and leased: `git push --atomic --porcelain
216267 /// --force-with-lease=refs/heads/<branch>:<fetched> <remote>
217268 /// <commit>:refs/heads/<branch>`, where `<fetched>` is G's commit as
@@ -343,6 +394,8 @@
343394 tracking_ref: String,
344395 /// The directory of the mirrors, absolute.
345396 mirrors: PathBuf,
397+ /// Which way changes may go.
398+ direction: SyncDirection,
346399 }
347400
348401 impl<'r> Sync<'r> {
@@ -371,6 +424,7 @@
371424 remote_branch,
372425 remote,
373426 agent,
427+ direction: options.direction,
374428 })
375429 }
376430
@@ -481,12 +535,34 @@
481535 prepared: &Prepared,
482536 ) -> Result<Decision, Error> {
483537 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");
489548 }
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"),
490566 (None, Some(remote)) => Decision::Create(remote),
491567 (Some(head), None) => Decision::Push(head),
492568 (Some(head), Some(remote)) if head == remote => Decision::UpToDate,
@@ -578,6 +654,7 @@
578654 SyncOutcome::FastForwarded
579655 }
580656 Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
657+ Decision::Diverged(reason) => SyncOutcome::Diverged { reason },
581658 Decision::Push(target) => {
582659 let commit = self.export(mirror, map, target)?;
583660 match self.push(mirror, commit, fetched)? {
@@ -744,6 +821,7 @@
744821 }
745822 }
746823 Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
824+ Decision::Diverged(reason) => SyncOutcome::Diverged { reason },
747825 };
748826 Ok(report)
749827 }