Elffuss BraidHub

utopia-ia/elffuss-braid public

Merge dev: git sync, engine merges and the repository config
Changeset290ce4f0990fec25b7b7213a433e4a96e966e0b37773f5d5ee72c73617fa29be
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:02 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:02 +02:00
Parents341013e85103, a1ce929d164d

Browse the files at this changeset

24 files changed

modified Cargo.lock +2 −0
@@ -525,6 +525,8 @@
525525 name = "elffuss-braid-repo"
526526 version = "0.0.1"
527527 dependencies = [
528+ "blake3",
529+ "elffuss-braid-engine",
528530 "elffuss-braid-format",
529531 "elffuss-braid-git",
530532 "elffuss-braid-store",
modified README.md +10 −2
@@ -168,8 +168,16 @@
168168 - `braid git import` reads a git repository through
169169 [gitoxide](https://github.com/GitoxideLabs/gitoxide). Each commit is exported
170170 again and compared with the original, so the round trip is bit for bit.
171-- `braid git export` and `braid git sync` keep GitHub or Gitea up to date as a
172- fast-forward with a lease. Braid never force-pushes.
171+- `braid git sync` keeps a branch of GitHub, Gitea or any git remote in step
172+ with a braid branch: it fetches and imports the remote branch, then
173+ fast-forwards braid, or pushes braid's branch as a fast-forward with a
174+ lease, merging first when both moved. Conflicts move nothing and exit with
175+ status 2. Braid never force-pushes.
176+
177+ ```bash
178+ braid git sync https://github.com/you/project.git --branch main
179+ braid git sync https://github.com/you/project.git --dry-run --json
180+ ```
173181 - Braid contains no code from git itself, which is GPLv2. It reads and writes
174182 git data with gitoxide (MIT or Apache-2.0) and runs the `git` binary only as
175183 a subprocess to push.
modified crates/cli/src/main.rs +28 −0
@@ -3,6 +3,7 @@
33
44 //! `braid`, the command-line tool.
55
6+mod sync;
67 mod work;
78
89 use std::fs::File;
@@ -174,6 +175,24 @@
174175 #[arg(long = "ref", value_name = "NAME")]
175176 refs: Vec<String>,
176177 },
178+ /// Keep a braid branch and a branch of a git remote in step: fetch and
179+ /// import the remote branch, then fast-forward the braid branch, or push
180+ /// it (merging first when both moved) as a fast-forward with a lease.
181+ /// Never force-pushes. Exits with 2 on conflicts and 1 when the push is
182+ /// refused.
183+ Sync {
184+ /// The git remote: a URL or a path.
185+ remote: String,
186+ /// The braid branch.
187+ #[arg(long, default_value = "main")]
188+ branch: String,
189+ /// The branch of the remote (default: the braid branch's name).
190+ #[arg(long, value_name = "NAME")]
191+ remote_branch: Option<String>,
192+ /// Report what would happen without writing anything.
193+ #[arg(long)]
194+ dry_run: bool,
195+ },
177196 }
178197
179198 #[derive(Debug, Subcommand)]
@@ -216,6 +235,15 @@
216235 Command::Git {
217236 action: GitAction::Export { path, refs },
218237 } => git_export(cli, path, refs),
238+ Command::Git {
239+ action:
240+ GitAction::Sync {
241+ remote,
242+ branch,
243+ remote_branch,
244+ dry_run,
245+ },
246+ } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run),
219247 Command::Fsck => fsck(cli),
220248 Command::Workspace { action } => work::workspace(cli, action),
221249 Command::Status => work::status(cli),
added crates/cli/src/sync.rs +234 −0
@@ -0,0 +1,234 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! `braid git sync`: the report of `Repo::git_sync`, as text or JSON.
5+
6+use std::process::ExitCode;
7+
8+use anyhow::Result;
9+use braid_format::{EntryKind, ObjectId};
10+use braid_repo::{Conflict, ConflictKind, HunkSide, SyncOptions, SyncOutcome, SyncReport};
11+use serde_json::{Value, json};
12+
13+use crate::{Cli, open_repo, print_json};
14+
15+/// Exit status when the sync found conflicts.
16+const CONFLICTS: u8 = 2;
17+
18+pub(crate) fn git_sync(
19+ cli: &Cli,
20+ remote: &str,
21+ branch: &str,
22+ remote_branch: Option<&str>,
23+ dry_run: bool,
24+) -> Result<ExitCode> {
25+ let repo = open_repo(cli)?;
26+ let options = SyncOptions {
27+ remote_branch: remote_branch.map(str::to_owned),
28+ dry_run,
29+ ..SyncOptions::default()
30+ };
31+ let report = repo.git_sync(remote, branch, &cli.agent, &options)?;
32+ if cli.json {
33+ print_json(&report_json(&report))?;
34+ } else {
35+ print_text(&report);
36+ }
37+ Ok(match report.outcome {
38+ SyncOutcome::Conflicts(_) => ExitCode::from(CONFLICTS),
39+ ref outcome if outcome.is_success() => ExitCode::SUCCESS,
40+ _ => ExitCode::FAILURE,
41+ })
42+}
43+
44+fn hex(id: Option<ObjectId>) -> Value {
45+ id.map_or(Value::Null, |id| Value::String(id.to_hex()))
46+}
47+
48+fn report_json(report: &SyncReport) -> Value {
49+ let mut value = json!({
50+ "outcome": report.outcome.code(),
51+ "dry_run": report.dry_run,
52+ "label": report.label,
53+ "branch": report.branch,
54+ "remote_branch": report.remote_branch,
55+ "remote_ref": report.remote_ref,
56+ "before": hex(report.before),
57+ "after": hex(report.after),
58+ "fetched": report.fetched.map(|(commit, changeset)| json!({
59+ "commit": commit.to_hex(),
60+ "changeset": changeset.to_hex(),
61+ })),
62+ "pushed": report.pushed.map(|commit| commit.to_hex()),
63+ "imported": report.imported,
64+ "operations": report.operations.iter().map(|op| op.seq).collect::<Vec<_>>(),
65+ });
66+ match &report.outcome {
67+ SyncOutcome::Merged {
68+ merge,
69+ merged_paths,
70+ } => {
71+ value["merge"] = Value::String(merge.to_hex());
72+ value["merged_paths"] = merged_paths
73+ .iter()
74+ .map(|path| Value::String(String::from_utf8_lossy(path).into_owned()))
75+ .collect();
76+ }
77+ SyncOutcome::Conflicts(conflicts) => {
78+ value["conflicts"] = conflicts.iter().map(conflict_json).collect();
79+ }
80+ SyncOutcome::RemoteMoved { found } => {
81+ value["found"] = found.map_or(Value::Null, |oid| Value::String(oid.to_hex()));
82+ }
83+ SyncOutcome::Rejected { reason } => {
84+ value["reason"] = Value::String(reason.clone());
85+ }
86+ _ => {}
87+ }
88+ value
89+}
90+
91+fn entry_json(entry: &Option<EntryKind>) -> Value {
92+ let Some(entry) = entry else {
93+ return Value::Null;
94+ };
95+ match entry {
96+ EntryKind::File { blob, size } => {
97+ json!({ "kind": "file", "blob": blob.to_hex(), "size": size })
98+ }
99+ EntryKind::Executable { blob, size } => {
100+ json!({ "kind": "executable", "blob": blob.to_hex(), "size": size })
101+ }
102+ EntryKind::Symlink { blob, size } => {
103+ json!({ "kind": "symlink", "blob": blob.to_hex(), "size": size })
104+ }
105+ EntryKind::Tree { tree } => json!({ "kind": "tree", "tree": tree.to_hex() }),
106+ EntryKind::Gitlink { commit } => json!({
107+ "kind": "gitlink",
108+ "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
109+ }),
110+ }
111+}
112+
113+fn side_json(side: &HunkSide) -> Value {
114+ json!({
115+ "start": side.lines.start,
116+ "end": side.lines.end,
117+ "text": String::from_utf8_lossy(&side.text),
118+ })
119+}
120+
121+fn conflict_json(conflict: &Conflict) -> Value {
122+ let mut value = json!({
123+ "path": String::from_utf8_lossy(&conflict.path),
124+ "kind": conflict.kind.code(),
125+ "base": entry_json(&conflict.base),
126+ "ours": entry_json(&conflict.ours),
127+ "theirs": entry_json(&conflict.theirs),
128+ });
129+ match &conflict.kind {
130+ ConflictKind::Content { hunks } => {
131+ value["hunks"] = hunks
132+ .iter()
133+ .map(|hunk| {
134+ json!({
135+ "base": side_json(&hunk.base),
136+ "ours": side_json(&hunk.ours),
137+ "theirs": side_json(&hunk.theirs),
138+ })
139+ })
140+ .collect();
141+ }
142+ ConflictKind::DirectoryRemoved { directory } => {
143+ value["directory"] = Value::String(String::from_utf8_lossy(directory).into_owned());
144+ }
145+ ConflictKind::Case { existing } => {
146+ value["existing"] = Value::String(String::from_utf8_lossy(existing).into_owned());
147+ }
148+ _ => {}
149+ }
150+ value
151+}
152+
153+fn short(id: Option<ObjectId>) -> String {
154+ id.map_or_else(|| "(none)".to_owned(), |id| id.short())
155+}
156+
157+fn print_text(report: &SyncReport) {
158+ let (branch, remote) = (&report.branch, &report.remote_ref);
159+ let would = |done: &str, planned: &str| {
160+ if report.dry_run {
161+ planned.to_owned()
162+ } else {
163+ done.to_owned()
164+ }
165+ };
166+ let pushed = report
167+ .pushed
168+ .map_or_else(String::new, |commit| commit.to_hex()[..12].to_owned());
169+ match &report.outcome {
170+ SyncOutcome::UpToDate => println!(
171+ "{branch} is up to date with {remote} ({}).",
172+ short(report.after)
173+ ),
174+ SyncOutcome::Created => println!(
175+ "{} {branch} at {} from {remote}; {} commits imported.",
176+ would("Created", "Would create"),
177+ short(report.after),
178+ report.imported
179+ ),
180+ SyncOutcome::FastForwarded => println!(
181+ "{} {branch} to {}; {} commits imported.",
182+ would("Fast-forwarded", "Would fast-forward"),
183+ short(report.after),
184+ report.imported
185+ ),
186+ SyncOutcome::Pushed => println!(
187+ "{} {branch} ({}) to {} as {pushed}.",
188+ would("Pushed", "Would push"),
189+ short(report.after),
190+ report.remote_branch
191+ ),
192+ SyncOutcome::Merged {
193+ merge,
194+ merged_paths,
195+ } => {
196+ println!(
197+ "{} {remote} into {branch} as {}, and {} it as {pushed}.",
198+ would("Merged", "Would merge"),
199+ merge.short(),
200+ would("pushed", "push")
201+ );
202+ for path in merged_paths {
203+ println!("merged {}", String::from_utf8_lossy(path));
204+ }
205+ }
206+ SyncOutcome::Conflicts(conflicts) => {
207+ println!("Conflicts between {branch} and {remote}; nothing moved, nothing was pushed.");
208+ for conflict in conflicts {
209+ println!(
210+ "{:<13} {}",
211+ conflict.kind.code(),
212+ String::from_utf8_lossy(&conflict.path)
213+ );
214+ }
215+ }
216+ SyncOutcome::RemoteMoved { found } => {
217+ eprintln!(
218+ "braid: error: {} moved after the fetch (it is at {} now); nothing was pushed. Sync again.",
219+ report.remote_branch,
220+ found.map_or_else(|| "nothing".to_owned(), |oid| oid.to_hex())
221+ );
222+ if report.after != report.before {
223+ eprintln!("{branch} is at the merge {}.", short(report.after));
224+ }
225+ }
226+ SyncOutcome::Rejected { reason } => {
227+ eprintln!("braid: error: the remote refused the push: {reason}");
228+ if report.after != report.before {
229+ eprintln!("{branch} is at the merge {}.", short(report.after));
230+ }
231+ }
232+ other => println!("{}", other.code()),
233+ }
234+}
added crates/cli/tests/git_sync.rs +410 −0
@@ -0,0 +1,410 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! End-to-end tests of `braid git sync`, with local bare repositories playing
5+//! the remote. Git runs without the user's or the system's configuration,
6+//! with fixed identities and dates, in the tests and in braid alike.
7+
8+use std::cell::Cell;
9+use std::path::{Path, PathBuf};
10+use std::process::{Command, Output};
11+
12+use serde_json::Value;
13+use tempfile::TempDir;
14+
15+const EPOCH: i64 = 1_700_000_000;
16+
17+/// Environment variables for every command: git ignores the user's and
18+/// the system's configuration and never prompts.
19+const GIT_ENV: [(&str, &str); 7] = [
20+ ("GIT_CONFIG_GLOBAL", "/dev/null"),
21+ ("GIT_CONFIG_NOSYSTEM", "1"),
22+ ("GIT_AUTHOR_NAME", "Ada Lovelace"),
23+ ("GIT_AUTHOR_EMAIL", "ada@example.org"),
24+ ("GIT_COMMITTER_NAME", "Charles Babbage"),
25+ ("GIT_COMMITTER_EMAIL", "charles@example.org"),
26+ ("GIT_TERMINAL_PROMPT", "0"),
27+];
28+
29+fn git_at(dir: &Path, date: i64, args: &[&str]) -> String {
30+ let mut command = Command::new("git");
31+ for variable in [
32+ "GIT_DIR",
33+ "GIT_WORK_TREE",
34+ "GIT_INDEX_FILE",
35+ "GIT_OBJECT_DIRECTORY",
36+ ] {
37+ command.env_remove(variable);
38+ }
39+ let output = command
40+ .current_dir(dir)
41+ .envs(GIT_ENV)
42+ .env("GIT_AUTHOR_DATE", format!("{date} +0100"))
43+ .env("GIT_COMMITTER_DATE", format!("{date} +0100"))
44+ .args([
45+ "-c",
46+ "init.defaultBranch=main",
47+ "-c",
48+ "commit.gpgSign=false",
49+ ])
50+ .args(args)
51+ .output()
52+ .expect("git must be installed to run these tests");
53+ assert!(
54+ output.status.success(),
55+ "git {args:?}: {}",
56+ String::from_utf8_lossy(&output.stderr)
57+ );
58+ String::from_utf8(output.stdout).unwrap().trim().to_owned()
59+}
60+
61+fn git(dir: &Path, args: &[&str]) -> String {
62+ git_at(dir, EPOCH, args)
63+}
64+
65+/// A bare remote with a reflog, clones of it where people work, and a braid
66+/// repository.
67+struct World {
68+ _dir: TempDir,
69+ root: PathBuf,
70+ remote: PathBuf,
71+ braid: PathBuf,
72+ clock: Cell<i64>,
73+}
74+
75+impl World {
76+ fn new() -> World {
77+ let dir = tempfile::tempdir().unwrap();
78+ let root = dir.path().to_path_buf();
79+ git(&root, &["init", "--quiet", "--bare", "remote.git"]);
80+ let remote = root.join("remote.git");
81+ git(&remote, &["config", "core.logAllRefUpdates", "true"]);
82+ let braid = root.join("braid");
83+ let world = World {
84+ _dir: dir,
85+ root,
86+ remote,
87+ braid,
88+ clock: Cell::new(EPOCH),
89+ };
90+ let init = world
91+ .braid_command(&["init"])
92+ .arg(&world.braid)
93+ .output()
94+ .unwrap();
95+ assert!(init.status.success());
96+ world
97+ }
98+
99+ /// A clone of the remote named `name`, made once, on the remote's main.
100+ fn clone(&self, name: &str) -> PathBuf {
101+ let path = self.root.join(name);
102+ if !path.exists() {
103+ git(&self.root, &["init", "--quiet", name]);
104+ git(
105+ &path,
106+ &["remote", "add", "origin", self.remote.to_str().unwrap()],
107+ );
108+ }
109+ if !git(&self.remote, &["for-each-ref", "refs/heads/main"]).is_empty() {
110+ git(&path, &["fetch", "--quiet", "origin", "main"]);
111+ git(&path, &["checkout", "--quiet", "-B", "main", "FETCH_HEAD"]);
112+ }
113+ path
114+ }
115+
116+ /// Commits `files` in the clone `name`, on top of the remote's main.
117+ fn commit(&self, name: &str, files: &[(&str, &str)], message: &str) -> (PathBuf, String) {
118+ let path = self.clone(name);
119+ for (file, content) in files {
120+ std::fs::write(path.join(file), content).unwrap();
121+ git(&path, &["add", file]);
122+ }
123+ self.clock.set(self.clock.get() + 60);
124+ git_at(
125+ &path,
126+ self.clock.get(),
127+ &["commit", "--quiet", "-m", message],
128+ );
129+ let commit = git(&path, &["rev-parse", "HEAD"]);
130+ (path, commit)
131+ }
132+
133+ /// Commits `files` in a clone and pushes them to the remote's main.
134+ fn push(&self, files: &[(&str, &str)], message: &str) -> String {
135+ let (path, commit) = self.commit("work", files, message);
136+ git(&path, &["push", "--quiet", "origin", "main"]);
137+ commit
138+ }
139+
140+ fn braid_command(&self, args: &[&str]) -> Command {
141+ let mut command = Command::new(env!("CARGO_BIN_EXE_braid"));
142+ command
143+ .envs(GIT_ENV)
144+ .env("BRAID_AGENT", "tester")
145+ .args(args);
146+ command
147+ }
148+
149+ /// Runs braid in the repository.
150+ fn braid(&self, args: &[&str]) -> Output {
151+ self.braid_command(args)
152+ .arg("--repo")
153+ .arg(&self.braid)
154+ .output()
155+ .unwrap()
156+ }
157+
158+ /// Runs braid with `--json` and returns its exit status and output.
159+ fn braid_json(&self, args: &[&str]) -> (Option<i32>, Value) {
160+ let output = self
161+ .braid_command(args)
162+ .arg("--repo")
163+ .arg(&self.braid)
164+ .arg("--json")
165+ .output()
166+ .unwrap();
167+ let value = serde_json::from_slice(&output.stdout).unwrap_or_else(|err| {
168+ panic!(
169+ "{err}: {}{}",
170+ String::from_utf8_lossy(&output.stdout),
171+ String::from_utf8_lossy(&output.stderr)
172+ )
173+ });
174+ (output.status.code(), value)
175+ }
176+
177+ fn sync(&self) -> (Option<i32>, Value) {
178+ self.braid_json(&["git", "sync", self.remote.to_str().unwrap()])
179+ }
180+
181+ fn refs(&self) -> Value {
182+ self.braid_json(&["refs"]).1["refs"].clone()
183+ }
184+
185+ fn operations(&self) -> usize {
186+ self.braid_json(&["op", "log", "-n", "1000"])
187+ .1
188+ .as_array()
189+ .unwrap()
190+ .len()
191+ }
192+
193+ fn remote_head(&self) -> String {
194+ git(&self.remote, &["rev-parse", "refs/heads/main"])
195+ }
196+
197+ /// The remote's main only ever moved forward.
198+ fn assert_forward_only(&self) {
199+ let log = std::fs::read_to_string(self.remote.join("logs/refs/heads/main")).unwrap();
200+ let zero = "0".repeat(40);
201+ let mut last = zero.clone();
202+ for line in log.lines() {
203+ let mut words = line.split(' ');
204+ let (old, new) = (words.next().unwrap(), words.next().unwrap());
205+ assert_eq!(old, last, "the reflog is continuous");
206+ if old != zero {
207+ git(&self.remote, &["merge-base", "--is-ancestor", old, new]);
208+ }
209+ last = new.to_owned();
210+ }
211+ assert_eq!(last, self.remote_head());
212+ }
213+}
214+
215+#[test]
216+fn the_first_sync_creates_the_branch_and_the_next_does_nothing() {
217+ let world = World::new();
218+ world.push(&[("README", "hello\n")], "First");
219+ let second = world.push(&[("lib.rs", "pub fn f() {}\n")], "Second");
220+
221+ let (code, report) = world.sync();
222+ assert_eq!(code, Some(0), "{report}");
223+ assert_eq!(report["outcome"], "created");
224+ assert_eq!(report["imported"], 2);
225+ assert_eq!(report["dry_run"], false);
226+ assert_eq!(report["fetched"]["commit"], second.as_str());
227+ assert_eq!(report["after"], report["fetched"]["changeset"]);
228+ assert_eq!(report["operations"].as_array().unwrap().len(), 1);
229+ let refs = world.refs();
230+ assert_eq!(refs["main"], report["after"]);
231+ let remote_ref = report["remote_ref"].as_str().unwrap();
232+ assert!(remote_ref.starts_with("remote/remote-"), "{remote_ref}");
233+ assert_eq!(refs[remote_ref], report["after"]);
234+
235+ let (code, again) = world.sync();
236+ assert_eq!(code, Some(0));
237+ assert_eq!(again["outcome"], "up_to_date");
238+ assert_eq!(again["operations"], Value::Array(Vec::new()));
239+ assert_eq!(world.refs(), refs);
240+
241+ let log = world.braid_json(&["log", "main"]).1;
242+ assert_eq!(log.as_array().unwrap().len(), 2);
243+}
244+
245+#[test]
246+fn the_remote_ahead_fast_forwards() {
247+ let world = World::new();
248+ world.push(&[("a", "1\n")], "First");
249+ world.sync();
250+ let next = world.push(&[("a", "2\n")], "Next");
251+ let (code, report) = world.sync();
252+ assert_eq!(code, Some(0), "{report}");
253+ assert_eq!(report["outcome"], "fast_forwarded");
254+ assert_eq!(report["fetched"]["commit"], next.as_str());
255+ assert_eq!(world.refs()["main"], report["after"]);
256+ assert_eq!(report["pushed"], Value::Null);
257+}
258+
259+#[test]
260+fn a_concurrent_push_fails_the_lease_and_the_next_sync_converges() {
261+ let world = World::new();
262+ world.push(&[("a", "1\n"), ("b", "1\n")], "First");
263+ world.sync();
264+
265+ // Braid gets ahead: it imports a commit that is not on the remote yet.
266+ let (upstream, ahead) = world.commit("upstream", &[("a", "braid\n")], "Ahead");
267+ let import = world.braid(&["git", "import", upstream.to_str().unwrap()]);
268+ assert!(import.status.success());
269+
270+ // Someone else's commit waits on a side branch of the remote, and the
271+ // remote's update hook moves main to it while braid's push is under way:
272+ // between braid's fetch and its push, someone else landed first.
273+ let (side, theirs) = world.commit("side", &[("b", "theirs\n")], "Theirs");
274+ git(&side, &["push", "--quiet", "origin", "main:side"]);
275+ let hook = world.remote.join("hooks/update");
276+ std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
277+ std::fs::write(
278+ &hook,
279+ "#!/bin/sh\n\
280+ if [ \"$1\" = refs/heads/main ]; then\n\
281+ \x20 git update-ref refs/heads/main refs/heads/side\n\
282+ \x20 rm -f \"$0\"\n\
283+ fi\n",
284+ )
285+ .unwrap();
286+ make_executable(&hook);
287+
288+ let refs = world.refs();
289+ let operations = world.operations();
290+ let (code, report) = world.sync();
291+ assert_eq!(code, Some(1), "{report}");
292+ assert_eq!(report["outcome"], "remote_moved");
293+ assert_eq!(report["found"], theirs.as_str());
294+ assert_eq!(report["pushed"], Value::Null);
295+ // Nothing moved in braid, and the remote has the other push only.
296+ assert_eq!(world.refs(), refs);
297+ assert_eq!(world.operations(), operations);
298+ assert_eq!(world.remote_head(), theirs);
299+ assert!(!hook.exists());
300+
301+ // The next sync merges both lines and pushes the merge.
302+ let (code, report) = world.sync();
303+ assert_eq!(code, Some(0), "{report}");
304+ assert_eq!(report["outcome"], "merged");
305+ let pushed = report["pushed"].as_str().unwrap();
306+ assert_eq!(world.remote_head(), pushed);
307+ assert_eq!(
308+ git(&world.remote, &["rev-list", "--parents", "-n", "1", "main"]),
309+ format!("{pushed} {ahead} {theirs}")
310+ );
311+ assert_eq!(git(&world.remote, &["show", "main:a"]), "braid");
312+ assert_eq!(git(&world.remote, &["show", "main:b"]), "theirs");
313+ world.assert_forward_only();
314+
315+ let (code, again) = world.sync();
316+ assert_eq!(code, Some(0));
317+ assert_eq!(again["outcome"], "up_to_date");
318+ assert_eq!(again["operations"], Value::Array(Vec::new()));
319+}
320+
321+#[cfg(unix)]
322+fn make_executable(path: &Path) {
323+ use std::os::unix::fs::PermissionsExt;
324+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
325+}
326+
327+#[cfg(not(unix))]
328+fn make_executable(_path: &Path) {}
329+
330+#[test]
331+fn conflicts_exit_with_2_and_change_nothing() {
332+ let world = World::new();
333+ world.push(&[("f", "1\n2\n3\n")], "First");
334+ world.sync();
335+ let (upstream, _) = world.commit("upstream", &[("f", "1\nbraid\n3\n")], "Braid");
336+ assert!(
337+ world
338+ .braid(&["git", "import", upstream.to_str().unwrap()])
339+ .status
340+ .success()
341+ );
342+ let theirs = world.push(&[("f", "1\ngit\n3\n")], "Git");
343+ let refs = world.refs();
344+ let operations = world.operations();
345+
346+ let (code, report) = world.sync();
347+ assert_eq!(code, Some(2), "{report}");
348+ assert_eq!(report["outcome"], "conflicts");
349+ let conflict = &report["conflicts"][0];
350+ assert_eq!(conflict["path"], "f");
351+ assert_eq!(conflict["kind"], "CONTENT");
352+ assert_eq!(conflict["ours"]["kind"], "file");
353+ assert_eq!(conflict["hunks"][0]["ours"]["text"], "braid\n");
354+ assert_eq!(conflict["hunks"][0]["theirs"]["text"], "git\n");
355+ assert_eq!(conflict["hunks"][0]["base"]["start"], 1);
356+ assert_eq!(world.refs(), refs);
357+ assert_eq!(world.operations(), operations);
358+ assert_eq!(world.remote_head(), theirs);
359+
360+ // The text form says the same, with the same exit status.
361+ let output = world.braid(&["git", "sync", world.remote.to_str().unwrap()]);
362+ assert_eq!(output.status.code(), Some(2));
363+ let text = String::from_utf8(output.stdout).unwrap();
364+ assert!(text.contains("nothing moved"), "{text}");
365+ assert!(text.contains("CONTENT f"), "{text}");
366+ world.assert_forward_only();
367+}
368+
369+#[test]
370+fn a_dry_run_reports_and_writes_nothing() {
371+ let world = World::new();
372+ world.push(&[("a", "1\n")], "First");
373+ world.sync();
374+ world.push(&[("a", "2\n")], "Next");
375+ let refs = world.refs();
376+ let operations = world.operations();
377+ let (code, report) =
378+ world.braid_json(&["git", "sync", world.remote.to_str().unwrap(), "--dry-run"]);
379+ assert_eq!(code, Some(0), "{report}");
380+ assert_eq!(report["dry_run"], true);
381+ assert_eq!(report["outcome"], "fast_forwarded");
382+ assert_eq!(report["imported"], 1);
383+ assert_eq!(world.refs(), refs);
384+ assert_eq!(world.operations(), operations);
385+
386+ let output = world.braid(&["git", "sync", world.remote.to_str().unwrap(), "--dry-run"]);
387+ let text = String::from_utf8(output.stdout).unwrap();
388+ assert!(text.starts_with("Would fast-forward main"), "{text}");
389+}
390+
391+#[test]
392+fn a_remote_branch_by_another_name() {
393+ let world = World::new();
394+ world.push(&[("a", "1\n")], "First");
395+ git(&world.remote, &["branch", "-m", "main", "trunk"]);
396+ let (code, report) = world.braid_json(&[
397+ "git",
398+ "sync",
399+ world.remote.to_str().unwrap(),
400+ "--branch",
401+ "work",
402+ "--remote-branch",
403+ "trunk",
404+ ]);
405+ assert_eq!(code, Some(0), "{report}");
406+ assert_eq!(report["outcome"], "created");
407+ assert_eq!(report["branch"], "work");
408+ assert_eq!(report["remote_branch"], "trunk");
409+ assert_eq!(world.refs()["work"], report["after"]);
410+}
modified crates/engine/src/error.rs +27 −0
@@ -163,6 +163,33 @@
163163 /// that a walk over a tree met.
164164 path: Vec<u8>,
165165 },
166+
167+ /// Two changesets to merge have no common ancestor.
168+ #[error("changesets {} and {} have no common ancestor", .ours.short(), .theirs.short())]
169+ UnrelatedHistories {
170+ /// The changeset merged into.
171+ ours: ObjectId,
172+ /// The changeset merged.
173+ theirs: ObjectId,
174+ },
175+
176+ /// Two changesets to merge have several best common ancestors, as after
177+ /// criss-cross merges, with different trees: the merge would depend on
178+ /// which one it started from.
179+ #[error(
180+ "changesets {} and {} have {} best common ancestors with different trees",
181+ .ours.short(),
182+ .theirs.short(),
183+ .bases.len()
184+ )]
185+ SeveralMergeBases {
186+ /// The changeset merged into.
187+ ours: ObjectId,
188+ /// The changeset merged.
189+ theirs: ObjectId,
190+ /// The best common ancestors, sorted by id.
191+ bases: Vec<ObjectId>,
192+ },
166193 }
167194
168195 impl Error {
modified crates/engine/src/land.rs +10 −10
@@ -326,24 +326,24 @@
326326 /// The names of one directory, by folded name.
327327 type FoldedNames = HashMap<Vec<u8>, Vec<Vec<u8>>>;
328328
329-/// The state of one rebase.
330-struct Rebase<'o, O> {
329+/// The state of one rebase. [`merge`](crate::merge) runs one too.
330+pub(crate) struct Rebase<'o, O> {
331331 trees: Trees<'o, O>,
332332 /// Root trees of the base, the head and the change.
333333 base: ObjectId,
334334 ours: ObjectId,
335335 theirs: ObjectId,
336336 /// The change list against the head, in path order.
337- resolved: Vec<Change>,
337+ pub(crate) resolved: Vec<Change>,
338338 /// Paths merged from both sides.
339- merged: Vec<Vec<u8>>,
339+ pub(crate) merged: Vec<Vec<u8>>,
340340 /// Merged contents to store.
341- blobs: Vec<(ObjectId, Vec<u8>)>,
341+ pub(crate) blobs: Vec<(ObjectId, Vec<u8>)>,
342342 /// Paths the change adds that had no file in the base or on the head.
343343 added: Vec<Vec<u8>>,
344344 /// Paths the change deletes.
345345 deleted: Vec<Vec<u8>>,
346- conflicts: Vec<Conflict>,
346+ pub(crate) conflicts: Vec<Conflict>,
347347 /// For each directory of the head, its names by folded name.
348348 folded: HashMap<ObjectId, Rc<FoldedNames>>,
349349 /// Names the change adds that were checked for collisions already.
@@ -351,7 +351,7 @@
351351 }
352352
353353 impl<'o, O: Objects> Rebase<'o, O> {
354- fn new(objects: &'o O, base: ObjectId, ours: ObjectId, theirs: ObjectId) -> Self {
354+ pub(crate) fn new(objects: &'o O, base: ObjectId, ours: ObjectId, theirs: ObjectId) -> Self {
355355 Rebase {
356356 trees: Trees::new(objects),
357357 base,
@@ -384,7 +384,7 @@
384384 }
385385
386386 /// Resolves one path of the change list.
387- fn path(&mut self, change: &Change) -> Result<(), Error> {
387+ pub(crate) fn path(&mut self, change: &Change) -> Result<(), Error> {
388388 let path = change.path.as_slice();
389389 if matches!(change.op, ChangeOp::Delete) {
390390 self.deleted.push(path.to_vec());
@@ -505,7 +505,7 @@
505505 /// Checks the structure around the resolved changes, applies them to the
506506 /// head without storing anything, and turns structural problems into
507507 /// conflicts.
508- fn structure(&mut self) -> Result<Applied, Error> {
508+ pub(crate) fn structure(&mut self) -> Result<Applied, Error> {
509509 self.removed_under_added()?;
510510 self.added_under_removed()?;
511511 let sets: Vec<Vec<u8>> = self
@@ -650,7 +650,7 @@
650650 }
651651
652652 /// The conflicts, sorted by path and kind, without repeats.
653- fn into_conflicts(self) -> Vec<Conflict> {
653+ pub(crate) fn into_conflicts(self) -> Vec<Conflict> {
654654 let mut conflicts = self.conflicts;
655655 conflicts.sort_by(|a, b| {
656656 a.path
modified crates/engine/src/lib.rs +9 −4
@@ -17,6 +17,8 @@
1717 //! ancestry.
1818 //! - [`merge3`]: three-way merges of file contents.
1919 //! - [`land`]: landing a change on a branch, with conflicts reported as data.
20+//! - [`merge`]: merging two changesets into a merge changeset, with the same
21+//! rules and conflicts as landing.
2022 //!
2123 //! # Files and directories
2224 //!
@@ -35,10 +37,11 @@
3537 //!
3638 //! # Costs
3739 //!
38-//! [`apply`], [`diff`], [`admit`] and [`land`] read only the directories on the
39-//! changed paths, so their cost follows the size of the change times the depth
40-//! of the tree, plus the size of each directory they touch. Ancestry queries
41-//! walk history and are proportional to the distance they cover.
40+//! [`apply`], [`diff`], [`admit`], [`land`] and [`merge`] read only the
41+//! directories on the changed paths, so their cost follows the size of the
42+//! change times the depth of the tree, plus the size of each directory they
43+//! touch. Ancestry queries walk history and are proportional to the distance
44+//! they cover.
4245 //!
4346 //! [`Objects`]: braid_format::Objects
4447
@@ -53,6 +56,7 @@
5356 mod land;
5457 mod merge;
5558 mod path;
59+mod tree_merge;
5660
5761 #[cfg(test)]
5862 mod testing;
@@ -69,3 +73,4 @@
6973 pub use land::{Conflict, ConflictKind, LandOutcome, REBASED_FROM, land};
7074 pub use merge::{BINARY_SNIFF_BYTES, ConflictHunk, HunkSide, MergeResult, is_binary, merge3};
7175 pub use path::MAX_PATH_DEPTH;
76+pub use tree_merge::{MergeOutcome, merge};
added crates/engine/src/tree_merge.rs +473 −0
@@ -0,0 +1,473 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Merging two changesets: a merge changeset whose tree is the three-way
5+//! merge of both trees against their merge base.
6+//!
7+//! The merge runs landing's rebase: the files that changed from the merge base
8+//! to `theirs` are applied to `ours` path by path, so every rule and every
9+//! kind of conflict is the one [`land`](crate::land) uses. Paths that only
10+//! `ours` changed keep their value without being looked at.
11+
12+use braid_format::{ChangesetParts, Kind, ObjectId, Objects, Signature};
13+
14+use crate::access::{EMPTY_TREE, empty_tree_node, read_changeset};
15+use crate::ancestry::merge_bases;
16+use crate::apply::write_nodes;
17+use crate::commit::store_assembled;
18+use crate::diff::diff;
19+use crate::error::{Error, store_error};
20+use crate::land::{Conflict, Rebase};
21+
22+/// What merging one changeset into another gives.
23+#[derive(Clone, Debug, PartialEq, Eq)]
24+pub enum MergeOutcome {
25+ /// `theirs` is `ours` or one of its ancestors: there is nothing to
26+ /// merge. Nothing was stored.
27+ UpToDate,
28+ /// `ours` is an ancestor of `theirs`, which has everything already: move
29+ /// to it, without a merge changeset. Nothing was stored.
30+ FastForward(ObjectId),
31+ /// The merge changeset, stored.
32+ Merged {
33+ /// The new changeset, whose parents are `[ours, theirs]`.
34+ changeset: ObjectId,
35+ /// The paths both sides changed, merged line by line or by kind.
36+ merged_paths: Vec<Vec<u8>>,
37+ },
38+ /// The sides conflict. Nothing was stored.
39+ Conflicts(Vec<Conflict>),
40+}
41+
42+/// Merges the changeset `theirs` into the changeset `ours`.
43+///
44+/// When one contains the other, the outcome says so and nothing is stored.
45+/// Otherwise the merge starts from their best common ancestor (see
46+/// [`merge_bases`](crate::merge_bases)). The merge changeset has the parents
47+/// `[ours, theirs]`; as root, the three-way merge of the three trees; the
48+/// change list against `ours`; `committer` as author and committer;
49+/// `message`; and no extra fields. It is made even when `ours` already has
50+/// every change of `theirs`, with an empty change list, so that its history
51+/// records the merge. Blobs, directories and the changeset are stored only
52+/// when the outcome is [`Merged`](MergeOutcome::Merged).
53+///
54+/// The conflicts are the ones [`land`](crate::land) reports for the same
55+/// trees, with `ours` as the head and `theirs` as the change. Changesets
56+/// without a common ancestor are not merged
57+/// ([`Error::UnrelatedHistories`]), and neither are changesets with several
58+/// best common ancestors whose trees differ ([`Error::SeveralMergeBases`]),
59+/// since the result would depend on which one the merge started from.
60+///
61+/// The cost follows the changes from the merge base to `theirs`, plus the
62+/// walks of history that find the merge base.
63+pub fn merge<O: Objects>(
64+ objects: &O,
65+ ours: ObjectId,
66+ theirs: ObjectId,
67+ committer: Signature,
68+ message: Vec<u8>,
69+) -> Result<MergeOutcome, Error> {
70+ let bases = merge_bases(objects, ours, theirs)?;
71+ let base_root = match bases.as_slice() {
72+ [] => return Err(Error::UnrelatedHistories { ours, theirs }),
73+ [base] if *base == theirs => return Ok(MergeOutcome::UpToDate),
74+ [base] if *base == ours => return Ok(MergeOutcome::FastForward(theirs)),
75+ [base] => read_changeset(objects, *base)?.root,
76+ several => shared_root(objects, ours, theirs, several)?,
77+ };
78+ let ours_root = read_changeset(objects, ours)?.root;
79+ let theirs_root = read_changeset(objects, theirs)?.root;
80+
81+ // Their side as a change built on the base, rebased onto ours.
82+ let changes = diff(objects, base_root, theirs_root)?;
83+ let mut rebase = Rebase::new(objects, base_root, ours_root, theirs_root);
84+ for change in &changes {
85+ rebase.path(change)?;
86+ }
87+ let applied = rebase.structure()?;
88+ if !rebase.conflicts.is_empty() {
89+ return Ok(MergeOutcome::Conflicts(rebase.into_conflicts()));
90+ }
91+
92+ for (_, bytes) in &rebase.blobs {
93+ objects.put(Kind::Blob, bytes).map_err(store_error)?;
94+ }
95+ write_nodes(objects, &applied.nodes)?;
96+ if applied.root == EMPTY_TREE {
97+ objects
98+ .put(Kind::Tree, &empty_tree_node())
99+ .map_err(store_error)?;
100+ }
101+ let assembled = ChangesetParts {
102+ parents: vec![ours, theirs],
103+ root: applied.root,
104+ changes: rebase.resolved,
105+ author: committer.clone(),
106+ committer,
107+ message,
108+ extras: Vec::new(),
109+ git_origin: None,
110+ }
111+ .assemble()
112+ .map_err(Error::Assemble)?;
113+ store_assembled(objects, &assembled)?;
114+ Ok(MergeOutcome::Merged {
115+ changeset: assembled.id,
116+ merged_paths: rebase.merged,
117+ })
118+}
119+
120+/// The root tree of several merge bases, when they all have the same one:
121+/// then the merge does not depend on which of them it starts from.
122+fn shared_root<O: Objects>(
123+ objects: &O,
124+ ours: ObjectId,
125+ theirs: ObjectId,
126+ bases: &[ObjectId],
127+) -> Result<ObjectId, Error> {
128+ let mut roots = Vec::with_capacity(bases.len());
129+ for base in bases {
130+ roots.push(read_changeset(objects, *base)?.root);
131+ }
132+ match roots.split_first() {
133+ Some((first, rest)) if rest.iter().all(|root| root == first) => Ok(*first),
134+ _ => Err(Error::SeveralMergeBases {
135+ ours,
136+ theirs,
137+ bases: bases.to_vec(),
138+ }),
139+ }
140+}
141+
142+#[cfg(test)]
143+mod tests {
144+ use super::*;
145+ use crate::access::read_changes;
146+ use crate::commit::{admit, commit};
147+ use crate::land::{ConflictKind, LandOutcome, land};
148+ use crate::testing::{Repo, delete, signature, text_map};
149+ use braid_format::{Change, Changes};
150+
151+ /// A base with `files`, and two changesets on it: ours applies `ours`
152+ /// and theirs applies `theirs`.
153+ struct Fork {
154+ repo: Repo,
155+ ours: ObjectId,
156+ theirs: ObjectId,
157+ }
158+
159+ fn fork(
160+ files: &[(&str, &str)],
161+ ours: impl FnOnce(&Repo) -> Vec<Change>,
162+ theirs: impl FnOnce(&Repo) -> Vec<Change>,
163+ ) -> Fork {
164+ let repo = Repo::new();
165+ let start: Vec<Change> = files.iter().map(|(p, c)| repo.set(p, c)).collect();
166+ let base = repo.commit(&[], start);
167+ let ours = repo.commit(&[base], ours(&repo));
168+ let theirs = commit(
169+ &repo.objects,
170+ vec![base],
171+ theirs(&repo),
172+ signature("other"),
173+ signature("other"),
174+ b"theirs\n".to_vec(),
175+ Vec::new(),
176+ )
177+ .unwrap();
178+ Fork { repo, ours, theirs }
179+ }
180+
181+ fn merge_it(fork: &Fork) -> MergeOutcome {
182+ merge(
183+ &fork.repo.objects,
184+ fork.ours,
185+ fork.theirs,
186+ signature("merger"),
187+ b"Merge\n".to_vec(),
188+ )
189+ .unwrap()
190+ }
191+
192+ /// Merges a fork that must merge cleanly, and checks the result: it is
193+ /// admissible, and its change list is the diff from ours.
194+ fn merged(fork: &Fork) -> (ObjectId, Vec<Vec<u8>>) {
195+ let outcome = merge_it(fork);
196+ let MergeOutcome::Merged {
197+ changeset,
198+ merged_paths,
199+ } = outcome
200+ else {
201+ panic!("expected a merge, got {outcome:?}");
202+ };
203+ let objects = &fork.repo.objects;
204+ admit(objects, changeset, |id| {
205+ [fork.ours, fork.theirs].contains(id)
206+ })
207+ .unwrap();
208+ let new = read_changeset(objects, changeset).unwrap();
209+ assert_eq!(new.parents, [fork.ours, fork.theirs]);
210+ let list = read_changes(objects, changeset, &new).unwrap().into_owned();
211+ assert_eq!(
212+ list,
213+ diff(objects, fork.repo.root(fork.ours), new.root).unwrap()
214+ );
215+ (changeset, merged_paths)
216+ }
217+
218+ #[test]
219+ fn one_side_containing_the_other() {
220+ let repo = Repo::new();
221+ let base = repo.commit(&[], vec![repo.set("a", "1")]);
222+ let next = repo.commit(&[base], vec![repo.set("a", "2")]);
223+ let later = repo.commit(&[next], vec![repo.set("b", "1")]);
224+ let objects = &repo.objects;
225+ let stored = objects.len();
226+ let run = |ours, theirs| merge(objects, ours, theirs, signature("m"), Vec::new()).unwrap();
227+ assert_eq!(run(base, later), MergeOutcome::FastForward(later));
228+ assert_eq!(run(later, base), MergeOutcome::UpToDate);
229+ assert_eq!(run(later, next), MergeOutcome::UpToDate);
230+ assert_eq!(run(later, later), MergeOutcome::UpToDate);
231+ assert_eq!(objects.len(), stored, "nothing is stored");
232+ }
233+
234+ #[test]
235+ fn disjoint_changes_merge() {
236+ let f = fork(
237+ &[("a", "1"), ("d/b", "2"), ("gone", "x"), ("old/x", "1")],
238+ |r| vec![r.set("a", "ours"), r.set("d/new", "o"), delete("gone")],
239+ |r| vec![r.set("d/b", "theirs"), r.set("e/f", "t"), delete("old/x")],
240+ );
241+ let (id, merged_paths) = merged(&f);
242+ assert!(merged_paths.is_empty());
243+ assert_eq!(
244+ f.repo.files(f.repo.root(id)),
245+ text_map(&[
246+ ("a", "ours"),
247+ ("d/b", "theirs"),
248+ ("d/new", "o"),
249+ ("e/f", "t")
250+ ])
251+ );
252+ let new = read_changeset(&f.repo.objects, id).unwrap();
253+ assert_eq!(new.author, signature("merger"));
254+ assert_eq!(new.committer, signature("merger"));
255+ assert_eq!(new.message, b"Merge\n");
256+ assert!(new.extras.is_empty());
257+ assert_eq!(new.git_origin, None);
258+
259+ // Merging the other way gives the same tree.
260+ let back = merge(
261+ &f.repo.objects,
262+ f.theirs,
263+ f.ours,
264+ signature("merger"),
265+ Vec::new(),
266+ )
267+ .unwrap();
268+ let MergeOutcome::Merged { changeset, .. } = back else {
269+ panic!("expected a merge, got {back:?}");
270+ };
271+ assert_eq!(f.repo.root(changeset), new.root);
272+ }
273+
274+ #[test]
275+ fn one_file_changed_on_both_sides_merges_line_by_line() {
276+ let f = fork(
277+ &[("f", "1\n2\n3\n4\n5\n")],
278+ |r| vec![r.set("f", "ONE\n2\n3\n4\n5\n")],
279+ |r| vec![r.exec("f", "1\n2\n3\n4\nFIVE\n")],
280+ );
281+ let (id, merged_paths) = merged(&f);
282+ assert_eq!(merged_paths, [b"f".to_vec()]);
283+ assert_eq!(
284+ f.repo.files(f.repo.root(id)),
285+ text_map(&[("f", "exec:ONE\n2\n3\n4\nFIVE\n")])
286+ );
287+ }
288+
289+ #[test]
290+ fn a_merge_that_changes_no_file_is_still_made() {
291+ let f = fork(
292+ &[("a", "1")],
293+ |r| vec![r.set("a", "2"), r.set("b", "1")],
294+ |r| vec![r.set("a", "2")],
295+ );
296+ let (id, _) = merged(&f);
297+ let new = read_changeset(&f.repo.objects, id).unwrap();
298+ assert_eq!(new.root, f.repo.root(f.ours));
299+ assert_eq!(new.changes, Changes::Inline(Vec::new()));
300+ }
301+
302+ #[test]
303+ fn deleting_everything() {
304+ let f = fork(
305+ &[("a", "1"), ("b", "1")],
306+ |_| vec![delete("a")],
307+ |_| vec![delete("b")],
308+ );
309+ let (id, _) = merged(&f);
310+ assert_eq!(f.repo.root(id), EMPTY_TREE);
311+ assert!(f.repo.objects.contains(&EMPTY_TREE).unwrap());
312+ }
313+
314+ #[test]
315+ fn conflicts_are_the_ones_landing_finds() {
316+ let cases: Vec<Fork> = vec![
317+ fork(
318+ &[("f", "1\n2\n3\n")],
319+ |r| vec![r.set("f", "1\nours\n3\n")],
320+ |r| vec![r.set("f", "1\ntheirs\n3\n")],
321+ ),
322+ fork(
323+ &[("f", "1"), ("g", "1")],
324+ |r| vec![r.set("f", "2"), delete("g")],
325+ |r| vec![delete("f"), r.set("g", "2")],
326+ ),
327+ fork(
328+ &[("a", "1")],
329+ |r| vec![r.set("x/y", "o")],
330+ |r| vec![r.set("x", "t")],
331+ ),
332+ fork(
333+ &[("d/a", "1"), ("k", "1")],
334+ |_| vec![delete("d/a")],
335+ |r| vec![r.set("d/b", "2")],
336+ ),
337+ fork(
338+ &[("x", "1")],
339+ |r| vec![r.set("README", "o")],
340+ |r| vec![r.set("readme", "t")],
341+ ),
342+ fork(
343+ &[("f", "1")],
344+ |r| vec![r.symlink("f", "target")],
345+ |r| vec![r.exec("f", "1")],
346+ ),
347+ ];
348+ let mut kinds = Vec::new();
349+ for f in &cases {
350+ let stored = f.repo.objects.len();
351+ let MergeOutcome::Conflicts(found) = merge_it(f) else {
352+ panic!("expected conflicts");
353+ };
354+ assert_eq!(f.repo.objects.len(), stored, "nothing is stored");
355+ let landed = land(&f.repo.objects, Some(f.ours), f.theirs, signature("x")).unwrap();
356+ assert_eq!(landed, LandOutcome::Conflicts(found.clone()));
357+ kinds.extend(found.iter().map(|c| c.kind.code()));
358+ }
359+ assert_eq!(
360+ kinds,
361+ [
362+ "CONTENT",
363+ "MODIFY_DELETE",
364+ "MODIFY_DELETE",
365+ "DF",
366+ "DIR_REMOVED",
367+ "CASE",
368+ "MODE"
369+ ]
370+ );
371+ let MergeOutcome::Conflicts(found) = merge_it(&cases[3]) else {
372+ panic!("expected conflicts");
373+ };
374+ assert_eq!(
375+ found[0].kind,
376+ ConflictKind::DirectoryRemoved {
377+ directory: b"d".to_vec()
378+ }
379+ );
380+ }
381+
382+ #[test]
383+ fn merging_again_after_a_merge() {
384+ // The history `git sync` makes: ours and theirs diverge, are merged,
385+ // and both sides go on.
386+ let f = fork(
387+ &[("a", "1"), ("b", "1")],
388+ |r| vec![r.set("a", "ours")],
389+ |r| vec![r.set("b", "theirs")],
390+ );
391+ let (first, _) = merged(&f);
392+ let repo = &f.repo;
393+ let run = |ours, theirs| merge(&repo.objects, ours, theirs, signature("m"), Vec::new());
394+ assert_eq!(run(first, f.theirs).unwrap(), MergeOutcome::UpToDate);
395+ assert_eq!(
396+ run(f.theirs, first).unwrap(),
397+ MergeOutcome::FastForward(first)
398+ );
399+
400+ let ours = repo.commit(&[first], vec![repo.set("c", "ours")]);
401+ let theirs = repo.commit(&[f.theirs], vec![repo.set("b", "again")]);
402+ let MergeOutcome::Merged { changeset, .. } = run(ours, theirs).unwrap() else {
403+ panic!("expected a merge");
404+ };
405+ assert_eq!(
406+ repo.files(repo.root(changeset)),
407+ text_map(&[("a", "ours"), ("b", "again"), ("c", "ours")])
408+ );
409+ }
410+
411+ #[test]
412+ fn unrelated_histories_are_not_merged() {
413+ let repo = Repo::new();
414+ let one = repo.commit(&[], vec![repo.set("a", "1")]);
415+ let two = repo.commit(&[], vec![repo.set("b", "1")]);
416+ let result = merge(&repo.objects, one, two, signature("m"), Vec::new());
417+ assert!(
418+ matches!(result, Err(Error::UnrelatedHistories { ours, theirs }) if ours == one && theirs == two),
419+ "{result:?}"
420+ );
421+ }
422+
423+ /// A changeset on `parents` with `changes`, told apart by `message`.
424+ fn node(repo: &Repo, parents: &[ObjectId], changes: Vec<Change>, message: &str) -> ObjectId {
425+ commit(
426+ &repo.objects,
427+ parents.to_vec(),
428+ changes,
429+ signature("author"),
430+ signature("author"),
431+ message.as_bytes().to_vec(),
432+ Vec::new(),
433+ )
434+ .unwrap()
435+ }
436+
437+ #[test]
438+ fn criss_cross_histories() {
439+ // Two sides merge each other: `x` and `y` are both best common
440+ // ancestors of what comes after.
441+ let repo = Repo::new();
442+ let root = node(&repo, &[], vec![repo.set("r", "1")], "root");
443+ let x = node(&repo, &[root], vec![repo.set("a", "x")], "x");
444+ let y = node(&repo, &[root], vec![repo.set("b", "y")], "y");
445+ let m1 = node(&repo, &[x, y], vec![repo.set("b", "y")], "m1");
446+ let m2 = node(&repo, &[y, x], vec![repo.set("a", "x")], "m2");
447+ let ours = node(&repo, &[m1], vec![repo.set("c", "1")], "ours");
448+ let theirs = node(&repo, &[m2], vec![repo.set("d", "1")], "theirs");
449+ let result = merge(&repo.objects, ours, theirs, signature("m"), Vec::new());
450+ assert!(
451+ matches!(&result, Err(Error::SeveralMergeBases { bases, .. }) if bases.len() == 2),
452+ "{result:?}"
453+ );
454+
455+ // When the best common ancestors have the same tree, the merge does
456+ // not depend on which one it starts from.
457+ let x = node(&repo, &[root], vec![repo.set("a", "1")], "x again");
458+ let y = node(&repo, &[root], vec![repo.set("a", "1")], "y again");
459+ let m1 = node(&repo, &[x, y], Vec::new(), "m1 again");
460+ let m2 = node(&repo, &[y, x], Vec::new(), "m2 again");
461+ let ours = node(&repo, &[m1], vec![repo.set("c", "1")], "ours again");
462+ let theirs = node(&repo, &[m2], vec![repo.set("d", "1")], "theirs again");
463+ let MergeOutcome::Merged { changeset, .. } =
464+ merge(&repo.objects, ours, theirs, signature("m"), Vec::new()).unwrap()
465+ else {
466+ panic!("expected a merge");
467+ };
468+ assert_eq!(
469+ repo.files(repo.root(changeset)),
470+ text_map(&[("a", "1"), ("c", "1"), ("d", "1"), ("r", "1")])
471+ );
472+ }
473+}
modified crates/engine/tests/properties.rs +77 −4
@@ -3,8 +3,9 @@
33
44 //! Property tests on random small repositories: `diff` is canonical and
55 //! `apply` inverts it, admission accepts what `commit` makes and rejects
6-//! tampering, and changes to unrelated paths land the same in either order.
7-//! Plus properties of the three-way merge.
6+//! tampering, changes to unrelated paths land the same in either order, and
7+//! merging two changesets agrees with landing one on the other. Plus
8+//! properties of the three-way merge.
89 //!
910 //! Trees are built here from scratch with `build_directory`, independently of
1011 //! the engine, and serve as the oracle.
@@ -12,8 +13,8 @@
1213 use std::collections::{BTreeMap, BTreeSet};
1314
1415 use braid_engine::{
15- ApplyProblem, Error, LandOutcome, MergeResult, admit, apply, commit, diff, land, merge3,
16- read_changes, read_changeset,
16+ ApplyProblem, Error, LandOutcome, MergeOutcome, MergeResult, admit, apply, commit, diff, land,
17+ merge, merge3, read_changes, read_changeset,
1718 };
1819 use braid_format::{
1920 Change, ChangeOp, Changes, Changeset, ChangesetError, ChangesetParts, Entry, EntryKind, GitId,
@@ -407,6 +408,69 @@
407408 Ok(())
408409 }
409410
411+/// Two changesets built on one start, related or not: merging the second
412+/// into the first gives what landing the second on the first gives, the same
413+/// conflicts or the same tree, and a merge that is admissible, whose change
414+/// list is the diff from the first.
415+fn check_merge_agrees_with_land(
416+ start: &Files,
417+ x_files: &Files,
418+ y_files: &Files,
419+) -> Result<(), TestCaseError> {
420+ let objects = MemoryObjects::new();
421+ store_all(&objects, start);
422+ store_all(&objects, x_files);
423+ store_all(&objects, y_files);
424+ let root = commit_list(&objects, Vec::new(), changes(&Files::new(), start))?;
425+ let x = commit_list(&objects, vec![root], changes(start, x_files))?;
426+ let y = commit(
427+ &objects,
428+ vec![root],
429+ changes(start, y_files),
430+ signature(),
431+ signature(),
432+ b"other change\n".to_vec(),
433+ Vec::new(),
434+ )?;
435+ let landed = land(&objects, Some(x), y, signature())?;
436+ let merged = merge(&objects, x, y, signature(), b"merge\n".to_vec())?;
437+ match (landed, merged) {
438+ (LandOutcome::Conflicts(by_land), MergeOutcome::Conflicts(by_merge)) => {
439+ prop_assert_eq!(by_land, by_merge);
440+ }
441+ (
442+ landed @ (LandOutcome::Rebased { .. } | LandOutcome::AlreadyApplied),
443+ MergeOutcome::Merged {
444+ changeset,
445+ merged_paths,
446+ },
447+ ) => {
448+ let new = read_changeset(&objects, changeset)?;
449+ prop_assert_eq!(&new.parents, &vec![x, y]);
450+ admit(&objects, changeset, |id| *id == x || *id == y)?;
451+ let x_root = read_changeset(&objects, x)?.root;
452+ let list = read_changes(&objects, changeset, &new)?.into_owned();
453+ prop_assert_eq!(list, diff(&objects, x_root, new.root)?);
454+ match landed {
455+ LandOutcome::Rebased {
456+ changeset: rebased,
457+ merged_paths: rebased_paths,
458+ } => {
459+ prop_assert_eq!(new.root, read_changeset(&objects, rebased)?.root);
460+ prop_assert_eq!(merged_paths, rebased_paths);
461+ }
462+ _ => prop_assert_eq!(new.root, x_root),
463+ }
464+ }
465+ (landed, merged) => {
466+ return Err(TestCaseError::fail(format!(
467+ "landing gave {landed:?}, merging gave {merged:?}"
468+ )));
469+ }
470+ }
471+ Ok(())
472+}
473+
410474 /// A directory of about a thousand files, on either side of the split
411475 /// limit, and a few other files.
412476 fn wide() -> impl Strategy<Value = Files> {
@@ -553,6 +617,15 @@
553617 ) {
554618 check_commutation(&start, &edit(&start, &x_edits), &edit(&start, &y_edits))?;
555619 }
620+
621+ #[test]
622+ fn merging_agrees_with_landing(
623+ start in files(),
624+ x_edits in edits(),
625+ y_edits in edits(),
626+ ) {
627+ check_merge_agrees_with_land(&start, &edit(&start, &x_edits), &edit(&start, &y_edits))?;
628+ }
556629 }
557630
558631 // Directories of about a thousand entries are slow to build and check in a
modified crates/git/src/export.rs +75 −10
@@ -11,7 +11,7 @@
1111
1212 use crate::error::Error;
1313 use crate::fetch;
14-use crate::map::GitMap;
14+use crate::map::{GitMap, Pairings};
1515 use crate::oid::{GitKind, GitOid};
1616 use crate::raw::{self, EntryType, TreeItem};
1717 use crate::repo::GitRepo;
@@ -31,7 +31,8 @@
3131 /// An exporter caches the git ids it computes, so exporting many related
3232 /// objects through one exporter does each piece of work once. Nothing is
3333 /// recursive: deep histories and deep directories are walked with explicit
34-/// stacks.
34+/// stacks. What it computed that the map does not know yet is available from
35+/// [`pairings`](Self::pairings), to record in the map.
3536 pub struct Exporter<'a, O: Objects> {
3637 objects: &'a O,
3738 map: &'a GitMap,
@@ -39,8 +40,8 @@
3940 /// link to one, and back.
4041 trees: HashMap<ObjectId, GitOid>,
4142 tree_sources: HashMap<GitOid, ObjectId>,
42- /// Git blobs computed here, and back.
43- blobs: HashMap<ObjectId, GitOid>,
43+ /// Git blobs computed here, with their sizes, and back.
44+ blobs: HashMap<ObjectId, (GitOid, u64)>,
4445 blob_sources: HashMap<GitOid, ObjectId>,
4546 /// Commits exported here, and back.
4647 commits: HashMap<ObjectId, GitOid>,
@@ -73,6 +74,39 @@
7374 }
7475 }
7576
77+ /// Every pairing this exporter computed that its map does not hold: the
78+ /// commits of the changesets it exported, and the canonical trees and
79+ /// the blobs it generated. [`GitMap::record`] adds them to a map, so that
80+ /// importing these git objects later gives back the same braid objects.
81+ pub fn pairings(&self) -> Pairings {
82+ let mut commits: Vec<(GitOid, ObjectId)> = self
83+ .commits
84+ .iter()
85+ .filter(|(changeset, _)| self.map.commit(changeset).is_none())
86+ .map(|(changeset, oid)| (*oid, *changeset))
87+ .collect();
88+ let mut trees: Vec<(GitOid, ObjectId)> = self
89+ .trees
90+ .iter()
91+ .filter(|(tree, _)| self.map.git_tree(tree).is_none())
92+ .map(|(tree, oid)| (*oid, *tree))
93+ .collect();
94+ let mut blobs: Vec<(GitOid, ObjectId, u64)> = self
95+ .blobs
96+ .iter()
97+ .filter(|(blob, _)| self.map.git_blob(blob).is_none())
98+ .map(|(blob, (oid, size))| (*oid, *blob, *size))
99+ .collect();
100+ commits.sort_unstable();
101+ trees.sort_unstable();
102+ blobs.sort_unstable();
103+ Pairings {
104+ commits,
105+ trees,
106+ blobs,
107+ }
108+ }
109+
76110 /// The git commit of a changeset: its id and its bytes.
77111 pub fn commit(&mut self, changeset: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> {
78112 let decoded = fetch::changeset(self.objects, changeset)?;
@@ -318,7 +352,7 @@
318352 detail: format!("the map links it to git blob {known}, but its content is {oid}"),
319353 });
320354 }
321- self.blobs.insert(*blob, oid);
355+ self.blobs.insert(*blob, (oid, bytes.len() as u64));
322356 self.blob_sources.insert(oid, *blob);
323357 Ok((oid, bytes))
324358 }
@@ -328,7 +362,7 @@
328362 match self
329363 .map
330364 .git_blob(blob)
331- .or_else(|| self.blobs.get(blob).copied())
365+ .or_else(|| self.blobs.get(blob).map(|(oid, _)| *oid))
332366 {
333367 Some(oid) => Ok(oid),
334368 None => Ok(self.blob(blob)?.0),
@@ -469,19 +503,49 @@
469503 /// then points the refs at them in one transaction.
470504 ///
471505 /// Refs are overwritten, whatever they pointed to before: there is no lease
472-/// and no fast-forward check here. That is meant for local exports; updating
473-/// a shared repository with a lease, as a fast-forward, is the job of
474-/// `git sync`, which comes later.
506+/// and no fast-forward check here. That is meant for local exports and for a
507+/// mirror; updating a shared repository with a lease, as a fast-forward, is
508+/// the job of `braid git sync`, which pushes from such a mirror.
475509 ///
476510 /// Objects the repository already has are not written again, and neither is
477511 /// anything they reach. Objects are written after everything they reach, so an
478512 /// interrupted write never leaves an object whose closure is missing.
513+///
514+/// The map is not changed: [`write_to_repo_recording`] also records what the
515+/// export generated.
479516 pub fn write_to_repo<O: Objects>(
480517 git_repo: &Path,
481518 objects: &O,
482519 map: &GitMap,
483520 refs: &[RefUpdate],
484521 ) -> Result<WriteReport, Error> {
522+ write(git_repo, objects, map, refs).map(|(report, _)| report)
523+}
524+
525+/// [`write_to_repo`], then records in `map` every commit, canonical tree and
526+/// blob the export generated (see [`Exporter::pairings`]), so that importing
527+/// them again, from this repository or from any other that received them,
528+/// gives back the same braid objects instead of new ones.
529+///
530+/// Nothing is recorded when the write fails. The caller saves the map.
531+pub fn write_to_repo_recording<O: Objects>(
532+ git_repo: &Path,
533+ objects: &O,
534+ map: &mut GitMap,
535+ refs: &[RefUpdate],
536+) -> Result<WriteReport, Error> {
537+ let (report, pairings) = write(git_repo, objects, map, refs)?;
538+ map.record(&pairings);
539+ Ok(report)
540+}
541+
542+/// Writes the objects and the refs, and returns what the export generated.
543+fn write<O: Objects>(
544+ git_repo: &Path,
545+ objects: &O,
546+ map: &GitMap,
547+ refs: &[RefUpdate],
548+) -> Result<(WriteReport, Pairings), Error> {
485549 let mut repo = GitRepo::open(git_repo)?;
486550 let mut writer = Writer {
487551 exporter: Exporter::new(objects, map),
@@ -498,10 +562,11 @@
498562 writer.write_closure(oid)?;
499563 targets.push((update.name.clone(), oid));
500564 }
565+ let pairings = writer.exporter.pairings();
501566 let mut report = writer.report;
502567 repo.set_refs(&targets, "braid: export")?;
503568 report.refs = targets;
504- Ok(report)
569+ Ok((report, pairings))
505570 }
506571
507572 struct Writer<'r, 'a, O: Objects> {
modified crates/git/src/lib.rs +6 −3
@@ -12,7 +12,9 @@
1212 //! - The [`Exporter`] turns braid objects back into git objects: imported ones
1313 //! byte for byte, from the raw bytes they keep, and new ones
1414 //! deterministically. [`write_to_repo`] writes them into a git repository
15-//! and points refs at them.
15+//! and points refs at them; [`write_to_repo_recording`] also records in the
16+//! [`GitMap`] the objects it generated for changesets made in braid, so
17+//! that importing them back gives the same changesets.
1618 //! - [`verify_round_trip`] imports a repository, exports it into a fresh one,
1719 //! and checks that every id matches.
1820 //!
@@ -39,11 +41,12 @@
3941 pub use error::{BoxError, Error};
4042 pub use export::{
4143 Exporter, RefTarget, RefUpdate, WriteReport, export_blob, export_commit, export_object,
42- export_tree, write_to_repo,
44+ export_tree, write_to_repo, write_to_repo_recording,
4345 };
4446 pub use import::{ImportOptions, ImportReport, ImportedRef, import};
45-pub use map::{GitMap, MapCounts, TagEntry};
47+pub use map::{GitMap, MapCounts, Pairings, TagEntry};
4648 pub use oid::{GitKind, GitOid, ParseGitOidError};
49+pub use repo::is_branch_name;
4750 pub use roundtrip::{RoundTripReport, verify_round_trip, verify_round_trip_with};
4851
4952 /// The parsers of raw git objects, for the fuzz targets in `fuzz/`. Not part
modified crates/git/src/map.rs +218 −2
@@ -7,7 +7,10 @@
77 //! changeset, a tree a braid tree, a blob a braid blob, and an annotated tag
88 //! the blob holding its raw bytes. The map records both directions, plus the
99 //! raw bytes of the git trees that cannot be regenerated from their braid
10-//! tree. It is derived data: importing the same repository again rebuilds it.
10+//! tree. Objects made in braid enter the map when they are exported, so that
11+//! importing them back gives the same braid objects. It is derived data:
12+//! importing the same repository again, and exporting the same changesets
13+//! again, rebuilds it.
1114
1215 use std::collections::{BTreeMap, HashMap};
1316
@@ -27,7 +30,7 @@
2730 pub target_kind: GitKind,
2831 }
2932
30-/// How many objects of each kind a map holds.
33+/// How many objects of each kind a map holds, or an operation added to it.
3134 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3235 pub struct MapCounts {
3336 /// Commits.
@@ -44,6 +47,44 @@
4447 pub tag_names: usize,
4548 }
4649
50+/// Git objects an export generated and the braid objects they come from:
51+/// the commits of changesets, canonical trees, and blobs. Each list is
52+/// sorted by git id.
53+///
54+/// [`Exporter::pairings`](crate::Exporter::pairings) collects them and
55+/// [`GitMap::record`] adds them to a map. Exports are deterministic, so a
56+/// pairing stays true wherever the git object goes: a commit that comes back
57+/// from a remote is the export of its changeset, and importing it must give
58+/// that changeset rather than a second one.
59+#[derive(Clone, Debug, Default, PartialEq, Eq)]
60+pub struct Pairings {
61+ pub(crate) commits: Vec<(GitOid, ObjectId)>,
62+ pub(crate) trees: Vec<(GitOid, ObjectId)>,
63+ pub(crate) blobs: Vec<(GitOid, ObjectId, u64)>,
64+}
65+
66+impl Pairings {
67+ /// Each commit and the changeset it was exported from.
68+ pub fn commits(&self) -> &[(GitOid, ObjectId)] {
69+ &self.commits
70+ }
71+
72+ /// Each git tree and the braid tree it is the canonical export of.
73+ pub fn trees(&self) -> &[(GitOid, ObjectId)] {
74+ &self.trees
75+ }
76+
77+ /// Each git blob, its braid blob, and its size.
78+ pub fn blobs(&self) -> &[(GitOid, ObjectId, u64)] {
79+ &self.blobs
80+ }
81+
82+ /// Whether there are no pairings.
83+ pub fn is_empty(&self) -> bool {
84+ self.commits.is_empty() && self.trees.is_empty() && self.blobs.is_empty()
85+ }
86+}
87+
4788 /// The two-way mapping between imported git objects and braid objects.
4889 ///
4990 /// - **Commits** map one to one to changesets.
@@ -157,6 +198,102 @@
157198 }
158199 }
159200
201+ /// Adds the pairings an export computed, and returns how many of each
202+ /// kind were new.
203+ ///
204+ /// The map stays one to one: a pairing is left out when the map already
205+ /// maps either of its objects, and a tree when its braid tree already has
206+ /// a canonical git tree. What the map knows wins.
207+ pub fn record(&mut self, pairings: &Pairings) -> MapCounts {
208+ let mut added = MapCounts::default();
209+ for (commit, changeset) in &pairings.commits {
210+ if self.add_commit(*commit, *changeset) {
211+ added.commits += 1;
212+ }
213+ }
214+ for (tree, braid) in &pairings.trees {
215+ if self.add_tree(*tree, *braid, None) {
216+ added.trees += 1;
217+ }
218+ }
219+ for (blob, braid, size) in &pairings.blobs {
220+ if self.add_blob(*blob, *braid, *size) {
221+ added.blobs += 1;
222+ }
223+ }
224+ added
225+ }
226+
227+ /// Adds every entry of `other` that this map lacks, such as what another
228+ /// process recorded since this map was read, and returns how many of each
229+ /// kind were new. As in [`record`](Self::record), what this map knows
230+ /// wins wherever the two disagree, so the result is still one to one.
231+ pub fn absorb(&mut self, other: &GitMap) -> MapCounts {
232+ let mut added = MapCounts::default();
233+ for (commit, changeset) in &other.commits {
234+ if self.add_commit(*commit, *changeset) {
235+ added.commits += 1;
236+ }
237+ }
238+ for (tree, braid) in &other.trees {
239+ let raw = other.raw_trees.get(tree).copied();
240+ if self.add_tree(*tree, *braid, raw) {
241+ added.trees += 1;
242+ if raw.is_some() {
243+ added.raw_trees += 1;
244+ }
245+ }
246+ }
247+ for (blob, (braid, size)) in &other.blobs {
248+ if self.add_blob(*blob, *braid, *size) {
249+ added.blobs += 1;
250+ }
251+ }
252+ for (tag, entry) in &other.tags {
253+ if !self.tags.contains_key(tag) && !self.tag_blobs.contains_key(&entry.raw) {
254+ self.insert_tag(*tag, *entry);
255+ added.tags += 1;
256+ }
257+ }
258+ for (name, tag) in &other.tag_names {
259+ if !self.tag_names.contains_key(name) && self.tags.contains_key(tag) {
260+ self.set_tag_name(name.clone(), *tag);
261+ added.tag_names += 1;
262+ }
263+ }
264+ added
265+ }
266+
267+ /// Inserts a commit unless either side is mapped already.
268+ fn add_commit(&mut self, commit: GitOid, changeset: ObjectId) -> bool {
269+ if self.commits.contains_key(&commit) || self.changesets.contains_key(&changeset) {
270+ return false;
271+ }
272+ self.insert_commit(commit, changeset);
273+ true
274+ }
275+
276+ /// Inserts a tree unless it is mapped already, or it would be a second
277+ /// canonical tree for its braid tree.
278+ fn add_tree(&mut self, tree: GitOid, braid: ObjectId, raw: Option<ObjectId>) -> bool {
279+ if self.trees.contains_key(&tree)
280+ || (raw.is_none() && self.canonical_trees.contains_key(&braid))
281+ {
282+ return false;
283+ }
284+ self.insert_tree(tree, braid, raw);
285+ true
286+ }
287+
288+ /// Inserts a blob unless either side is mapped already.
289+ fn add_blob(&mut self, blob: GitOid, braid: ObjectId, size: u64) -> bool {
290+ if self.blobs.contains_key(&blob) || self.git_blobs.contains_key(&braid) {
291+ return false;
292+ }
293+ self.insert_blob(blob, braid, size);
294+ true
295+ }
296+
160297 pub(crate) fn insert_commit(&mut self, commit: GitOid, changeset: ObjectId) {
161298 self.commits.insert(commit, changeset);
162299 self.changesets.insert(changeset, commit);
@@ -471,4 +608,83 @@
471608 first.swap_with_slice(second);
472609 assert!(GitMap::from_bytes(&swapped).is_err());
473610 }
611+
612+ #[test]
613+ fn recording_keeps_the_map_one_to_one() {
614+ let mut map = sample();
615+ let pairings = Pairings {
616+ commits: vec![
617+ (oid(1), id("another changeset")),
618+ (oid(8), id("c1")),
619+ (oid(9), id("c9")),
620+ ],
621+ trees: vec![(oid(3), id("t9")), (oid(10), id("t1")), (oid(11), id("t3"))],
622+ blobs: vec![
623+ (oid(6), id("b9"), 1),
624+ (oid(12), id("b1"), 42),
625+ (oid(13), id("b2"), 7),
626+ ],
627+ };
628+ assert!(!pairings.is_empty());
629+ let added = map.record(&pairings);
630+ assert_eq!(
631+ added,
632+ MapCounts {
633+ commits: 1,
634+ trees: 1,
635+ blobs: 1,
636+ ..MapCounts::default()
637+ }
638+ );
639+ // What the map knew stays.
640+ assert_eq!(map.changeset(&oid(1)), Some(id("c1")));
641+ assert_eq!(map.changeset(&oid(8)), None);
642+ assert_eq!(map.git_tree(&id("t1")), Some(oid(3)));
643+ assert_eq!(map.tree(&oid(10)), None);
644+ assert_eq!(map.blob(&oid(12)), None);
645+ // The rest is added both ways.
646+ assert_eq!(map.changeset(&oid(9)), Some(id("c9")));
647+ assert_eq!(map.commit(&id("c9")), Some(oid(9)));
648+ assert_eq!(map.git_tree(&id("t3")), Some(oid(11)));
649+ assert_eq!(map.raw_tree(&oid(11)), None);
650+ assert_eq!(map.blob(&oid(13)), Some((id("b2"), 7)));
651+ assert_eq!(map.git_blob(&id("b2")), Some(oid(13)));
652+ // The result still encodes, and recording again adds nothing.
653+ assert_eq!(GitMap::from_bytes(&map.to_bytes()).unwrap(), map);
654+ assert_eq!(map.record(&pairings), MapCounts::default());
655+ assert!(Pairings::default().is_empty());
656+ }
657+
658+ #[test]
659+ fn absorbing_adds_what_is_missing() {
660+ let theirs = sample();
661+ let mut ours = GitMap::new();
662+ ours.insert_commit(oid(1), id("c1"));
663+ ours.insert_tree(oid(5), id("t2"), None);
664+ assert_eq!(
665+ ours.absorb(&theirs),
666+ MapCounts {
667+ commits: 1,
668+ trees: 2,
669+ raw_trees: 1,
670+ blobs: 1,
671+ tags: 1,
672+ tag_names: 1,
673+ }
674+ );
675+ assert_eq!(ours, theirs);
676+ assert_eq!(ours.absorb(&theirs), MapCounts::default());
677+
678+ // Where the two disagree, this map wins and stays one to one.
679+ let mut mine = GitMap::new();
680+ mine.insert_commit(oid(2), id("mine"));
681+ mine.insert_tree(oid(20), id("t1"), None);
682+ mine.absorb(&theirs);
683+ assert_eq!(mine.changeset(&oid(2)), Some(id("mine")));
684+ assert_eq!(mine.commit(&id("c2")), None);
685+ assert_eq!(mine.git_tree(&id("t1")), Some(oid(20)));
686+ assert_eq!(mine.tree(&oid(3)), None);
687+ assert_eq!(mine.raw_tree(&oid(4)), Some(id("raw t1")));
688+ assert_eq!(GitMap::from_bytes(&mine.to_bytes()).unwrap(), mine);
689+ }
474690 }
modified crates/git/src/repo.rs +27 −0
@@ -20,6 +20,15 @@
2020 /// Memory for the cache of decoded pack deltas, per open repository.
2121 const PACK_CACHE_BYTES: usize = 64 * 1024 * 1024;
2222
23+/// Whether `name` can be the name of a git branch: `refs/heads/<name>`
24+/// follows git's rules for ref names (no `..`, no `:`, `?`, `*`, `[`, `\`,
25+/// `^`, `~`, space or control character, no component that starts with `.`
26+/// or ends with `.lock`, and so on), and is not `refs/heads/HEAD`.
27+pub fn is_branch_name(name: &str) -> bool {
28+ let full = format!("refs/heads/{name}");
29+ gix::validate::reference::branch_name(full.as_bytes().as_bstr()).is_ok()
30+}
31+
2332 /// The id of the empty tree.
2433 const EMPTY_TREE: GitOid = GitOid::from_bytes([
2534 0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60, 0xe5, 0x4b, 0xf8, 0xd6, 0x92, 0x88,
@@ -235,3 +244,21 @@
235244 Ok(())
236245 }
237246 }
247+
248+#[cfg(test)]
249+mod tests {
250+ use super::*;
251+
252+ #[test]
253+ fn branch_names() {
254+ for good in ["main", "feature/x", "v1.0", "a-b_c", "caf\u{e9}"] {
255+ assert!(is_branch_name(good), "{good}");
256+ }
257+ for bad in [
258+ "", "a b", "a:b", "a..b", "a*", "a?", "a[b", "a\\b", "a^", "a~1", "/a", "a/", "a//b",
259+ ".a", "a/.b", "a.lock", "a.", "a@{1}", "HEAD", "a\nb", "a\0b",
260+ ] {
261+ assert!(!is_branch_name(bad), "{bad:?}");
262+ }
263+ }
264+}
modified crates/git/tests/fixtures.rs +167 −0
@@ -16,6 +16,7 @@
1616 use braid_git::{
1717 Error, GitKind, GitMap, GitOid, ImportOptions, RefTarget, RefUpdate, RoundTripReport,
1818 export_commit, export_object, import, verify_round_trip, write_to_repo,
19+ write_to_repo_recording,
1920 };
2021 use common::{Repo, exec, file, link, raw_tree, submodule};
2122
@@ -1143,6 +1144,172 @@
11431144 changeset(objects, map, &commit.to_hex())
11441145 }
11451146
1147+/// Stores the directories holding exactly `files`, regular files given by
1148+/// path and content, and returns the root.
1149+fn store_files(objects: &MemoryObjects, files: &[(&str, &str)]) -> ObjectId {
1150+ fn store_dir(objects: &MemoryObjects, dir: &Dir) -> ObjectId {
1151+ let entries = dir
1152+ .iter()
1153+ .map(|(name, node)| Entry {
1154+ name: name.clone(),
1155+ kind: match node {
1156+ Node::Leaf(kind) => kind.clone(),
1157+ Node::Dir(below) => EntryKind::Tree {
1158+ tree: store_dir(objects, below),
1159+ },
1160+ },
1161+ })
1162+ .collect();
1163+ store_tree(objects, entries)
1164+ }
1165+ let mut dir = Dir::new();
1166+ let changes: Vec<Change> = files
1167+ .iter()
1168+ .map(|(path, content)| file_change(objects, path, content))
1169+ .collect();
1170+ apply(&mut dir, &changes);
1171+ store_dir(objects, &dir)
1172+}
1173+
1174+fn file_change(objects: &MemoryObjects, path: &str, content: &str) -> Change {
1175+ let (blob, size) = store_blob(objects, content.as_bytes());
1176+ Change {
1177+ path: path.as_bytes().to_vec(),
1178+ op: ChangeOp::File { blob, size },
1179+ }
1180+}
1181+
1182+/// A changeset made in braid on `parent`, whose tree holds exactly `files`
1183+/// and whose change list is `changes`.
1184+fn braid_changeset(
1185+ objects: &MemoryObjects,
1186+ parent: ObjectId,
1187+ files: &[(&str, &str)],
1188+ changes: Vec<Change>,
1189+ message: &str,
1190+) -> ObjectId {
1191+ let grace = Signature {
1192+ name: b"Grace Hopper".to_vec(),
1193+ email: b"grace@example.org".to_vec(),
1194+ seconds: 1_700_000_500,
1195+ offset_minutes: -300,
1196+ };
1197+ let assembled = ChangesetParts {
1198+ parents: vec![parent],
1199+ root: store_files(objects, files),
1200+ changes,
1201+ author: grace.clone(),
1202+ committer: grace,
1203+ message: message.as_bytes().to_vec(),
1204+ extras: Vec::new(),
1205+ git_origin: None,
1206+ }
1207+ .assemble()
1208+ .unwrap();
1209+ objects.put(Kind::Changeset, &assembled.encoded).unwrap()
1210+}
1211+
1212+#[test]
1213+fn exported_commits_import_as_the_changesets_they_came_from() {
1214+ let mut repo = Repo::new();
1215+ let imported = repo.snapshot(
1216+ "main",
1217+ &[file("README", "hi\n"), file("src/a.rs", "a\n")],
1218+ "imported",
1219+ );
1220+ let objects = MemoryObjects::new();
1221+ let mut map = GitMap::new();
1222+ import_all(&repo, &objects, &mut map);
1223+
1224+ // Two changesets made in braid, one on top of the other.
1225+ let base = map.changeset(&oid(&imported)).unwrap();
1226+ let first_files = [("README", "hello from braid\n"), ("src/a.rs", "a\n")];
1227+ let first = braid_changeset(
1228+ &objects,
1229+ base,
1230+ &first_files,
1231+ vec![file_change(&objects, "README", "hello from braid\n")],
1232+ "one\n",
1233+ );
1234+ let second_files = [
1235+ ("README", "hello from braid\n"),
1236+ ("docs/b.md", "# B\n"),
1237+ ("src/a.rs", "a\n"),
1238+ ];
1239+ let second = braid_changeset(
1240+ &objects,
1241+ first,
1242+ &second_files,
1243+ vec![file_change(&objects, "docs/b.md", "# B\n")],
1244+ "two\n",
1245+ );
1246+
1247+ // Exporting them records their commits, trees and blobs in the map.
1248+ let before = map.counts();
1249+ let report = write_to_repo_recording(
1250+ repo.path(),
1251+ &objects,
1252+ &mut map,
1253+ &[RefUpdate {
1254+ name: b"refs/heads/main".to_vec(),
1255+ target: RefTarget::Changeset(second),
1256+ }],
1257+ )
1258+ .unwrap();
1259+ assert_eq!((report.commits, report.trees, report.blobs), (2, 3, 2));
1260+ let tip = report.refs[0].1;
1261+ assert_eq!(map.changeset(&tip), Some(second));
1262+ assert_eq!(map.commit(&second), Some(tip));
1263+ let first_commit = map.commit(&first).unwrap();
1264+ assert_eq!(repo.git(&["rev-parse", "main~1"]), first_commit.to_hex());
1265+ let after = map.counts();
1266+ assert_eq!(after.commits, before.commits + 2);
1267+ assert_eq!(after.trees, before.trees + 3);
1268+ assert_eq!(after.blobs, before.blobs + 2);
1269+ // The plain export of the same changesets records nothing, and agrees.
1270+ let plain = write_to_repo(
1271+ repo.path(),
1272+ &objects,
1273+ &map,
1274+ &[RefUpdate {
1275+ name: b"refs/heads/again".to_vec(),
1276+ target: RefTarget::Changeset(second),
1277+ }],
1278+ )
1279+ .unwrap();
1280+ assert_eq!(plain.refs[0].1, tip);
1281+ assert_eq!((plain.commits, plain.trees, plain.blobs), (0, 0, 0));
1282+
1283+ // Importing the exported commits finds every object in the map: nothing
1284+ // new, and the branch is the changeset made in braid.
1285+ let again = import_all(&repo, &objects, &mut map);
1286+ assert_eq!(
1287+ (again.commits, again.trees, again.blobs, again.raw_trees),
1288+ (0, 0, 0, 0)
1289+ );
1290+ let main = again
1291+ .refs
1292+ .iter()
1293+ .find(|r| r.name == b"refs/heads/main")
1294+ .unwrap();
1295+ assert_eq!(main.braid, second);
1296+
1297+ // A commit made in git on top of them builds on the braid changeset.
1298+ let mut next_files: Vec<_> = second_files.iter().map(|(p, c)| file(p, c)).collect();
1299+ next_files.push(file("c", "from git\n"));
1300+ let next = repo.snapshot("main", &next_files, "made in git");
1301+ let later = import_all(&repo, &objects, &mut map);
1302+ assert_eq!(later.commits, 1);
1303+ let next_changeset = changeset(&objects, &map, &next);
1304+ assert_eq!(next_changeset.parents, [second]);
1305+ assert_eq!(changes(&objects, &map, &next), pairs(&[("c", "file")]));
1306+
1307+ // The map still encodes, and everything round-trips.
1308+ assert_eq!(GitMap::from_bytes(&map.to_bytes()).unwrap(), map);
1309+ assert_admissible(&objects, &map);
1310+ round_trip(&repo);
1311+}
1312+
11461313 #[test]
11471314 fn a_changeset_that_disagrees_with_its_origin_is_not_exported() {
11481315 let mut repo = Repo::new();
modified crates/repo/Cargo.toml +2 −0
@@ -16,6 +16,8 @@
1616 braid-format.workspace = true
1717 braid-store.workspace = true
1818 braid-git.workspace = true
19+braid-engine.workspace = true
20+blake3.workspace = true
1921 thiserror = "2"
2022
2123 [dev-dependencies]
added crates/repo/src/config.rs +108 −0
@@ -0,0 +1,108 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The repository's own settings: the optional file `.braid/config`.
5+//!
6+//! The file holds `key = value` lines (`key: value` works too). Blank lines,
7+//! lines that start with `#` or `;`, and section headers in square brackets
8+//! are skipped, and so are keys braid does not know. A value may be quoted
9+//! with `"`. The keys are:
10+//!
11+//! - `name` (or `user.name`): the name braid gives the changesets it makes;
12+//! - `email` (or `user.email`): their email address.
13+//!
14+//! Nothing requires the file. Without an email, the changesets braid makes
15+//! itself, such as the merges of `git sync`, get an `example.org` address.
16+
17+use std::fs;
18+use std::io;
19+
20+use crate::{DIR, Error, Repo};
21+
22+/// Name of the configuration file inside [`DIR`].
23+pub const CONFIG_FILE: &str = "config";
24+
25+/// What `.braid/config` sets.
26+#[derive(Clone, Debug, Default, PartialEq, Eq)]
27+#[non_exhaustive]
28+pub struct Config {
29+ /// The name for changesets braid makes.
30+ pub name: Option<String>,
31+ /// The email address for changesets braid makes.
32+ pub email: Option<String>,
33+}
34+
35+impl Config {
36+ /// Reads the text of a configuration file. Lines it does not understand
37+ /// are skipped, and an empty value counts as no value.
38+ pub fn parse(text: &str) -> Config {
39+ let mut config = Config::default();
40+ for line in text.lines() {
41+ let line = line.trim();
42+ if line.is_empty() || line.starts_with(['#', ';', '[']) {
43+ continue;
44+ }
45+ let Some((key, value)) = line.split_once(['=', ':']) else {
46+ continue;
47+ };
48+ let value = value.trim();
49+ let value = value
50+ .strip_prefix('"')
51+ .and_then(|inner| inner.strip_suffix('"'))
52+ .unwrap_or(value);
53+ let value = (!value.is_empty()).then(|| value.to_owned());
54+ match key.trim() {
55+ "name" | "user.name" => config.name = value,
56+ "email" | "user.email" => config.email = value,
57+ _ => {}
58+ }
59+ }
60+ config
61+ }
62+}
63+
64+impl Repo {
65+ /// The settings in `.braid/config`; all unset when there is no such file.
66+ pub fn config(&self) -> Result<Config, Error> {
67+ match fs::read_to_string(self.root.join(DIR).join(CONFIG_FILE)) {
68+ Ok(text) => Ok(Config::parse(&text)),
69+ Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Config::default()),
70+ Err(err) => Err(err.into()),
71+ }
72+ }
73+}
74+
75+#[cfg(test)]
76+mod tests {
77+ use super::*;
78+
79+ #[test]
80+ fn parsing() {
81+ let config = Config::parse(
82+ "# who braid is\n[user]\nname = Ada Lovelace\n email: \"ada@example.org\"\n\
83+ colour = blue\nnot a setting\n",
84+ );
85+ assert_eq!(config.name.as_deref(), Some("Ada Lovelace"));
86+ assert_eq!(config.email.as_deref(), Some("ada@example.org"));
87+ let config = Config::parse("user.name=Grace\nuser.email =\n; done\n");
88+ assert_eq!(config.name.as_deref(), Some("Grace"));
89+ assert_eq!(config.email, None);
90+ assert_eq!(Config::parse(""), Config::default());
91+ }
92+
93+ #[test]
94+ fn the_file_is_optional() {
95+ let dir = tempfile::tempdir().unwrap();
96+ let repo = Repo::init(dir.path()).unwrap();
97+ assert_eq!(repo.config().unwrap(), Config::default());
98+ fs::write(
99+ dir.path().join(DIR).join(CONFIG_FILE),
100+ "email = bot@example.org\n",
101+ )
102+ .unwrap();
103+ assert_eq!(
104+ repo.config().unwrap().email.as_deref(),
105+ Some("bot@example.org")
106+ );
107+ }
108+}
modified crates/repo/src/git.rs +206 −14
@@ -6,12 +6,19 @@
66 //! The map between git and braid ids is a derived object in the store, and the
77 //! ref [`MAP_REF`] points at its current version. An import moves that ref in
88 //! the same operation as the refs it brings in, so `braid undo` reverts both.
9+//! An export records in the map the commits, trees and blobs it generated for
10+//! changesets made in braid, so that importing them back gives the same
11+//! changesets.
12+//!
13+//! Braid's own refs live in namespaces no git branch maps to: `braid/` for
14+//! braid's bookkeeping, `remote/` for where the branches of git remotes were
15+//! last seen (see `git sync`), `tags/` for tags and `git/` for other git refs.
916
1017 use std::convert::Infallible;
1118 use std::path::Path;
1219
1320 use braid_format::{Kind, ObjectId, Objects};
14-use braid_git::{GitMap, ImportOptions, ImportReport, RefTarget, WriteReport};
21+use braid_git::{GitMap, ImportOptions, ImportReport, MapCounts, RefTarget, WriteReport};
1522 use braid_store::{Operation, RefUpdate, TransactError};
1623
1724 use crate::{Error, Repo};
@@ -19,11 +26,32 @@
1926 /// The ref that points at the current git map.
2027 pub const MAP_REF: &str = "braid/git-map";
2128
29+/// The prefix of the braid refs that record where the branches of git
30+/// remotes were last seen: `remote/<label>/<branch>`. They are never
31+/// exported.
32+pub const REMOTE_PREFIX: &str = "remote/";
33+
34+/// The agent label of the operations [`Repo::git_export`] records.
35+pub const GIT_EXPORT_AGENT: &str = "git-export";
36+
37+/// Braid's own namespaces. A git branch whose name starts with one of them
38+/// keeps its full name, under `git/`, so that it never lands in them.
39+pub(crate) const RESERVED: [&str; 4] = ["braid/", "git/", REMOTE_PREFIX, "tags/"];
40+
41+/// How many times saving the git map merges with a map another process saved
42+/// meanwhile before giving up.
43+const MAP_ATTEMPTS: usize = 16;
44+
2245 /// The braid ref for a git ref: branches keep their short name, tags go under
23-/// `tags/`, and any other ref keeps its full name under `git/`.
46+/// `tags/`, and any other ref, or a branch whose short name starts like one
47+/// of braid's own namespaces (`braid/`, `git/`, `remote/`, `tags/`), keeps
48+/// its full name under `git/`.
2449 pub fn braid_ref_for_git(name: &[u8]) -> Option<String> {
2550 let name = std::str::from_utf8(name).ok()?;
26- Some(if let Some(branch) = name.strip_prefix("refs/heads/") {
51+ let branch = name
52+ .strip_prefix("refs/heads/")
53+ .filter(|branch| !RESERVED.iter().any(|prefix| branch.starts_with(prefix)));
54+ Some(if let Some(branch) = branch {
2755 branch.to_owned()
2856 } else if let Some(tag) = name.strip_prefix("refs/tags/") {
2957 format!("tags/{tag}")
@@ -32,9 +60,10 @@
3260 })
3361 }
3462
35-/// The git ref for a braid ref, or `None` for braid's own refs.
63+/// The git ref for a braid ref, or `None` for braid's own refs and for the
64+/// refs that record the branches of remotes.
3665 pub fn git_ref_for_braid(name: &str) -> Option<String> {
37- if name.starts_with("braid/") {
66+ if name.starts_with("braid/") || name.starts_with(REMOTE_PREFIX) {
3867 None
3968 } else if let Some(tag) = name.strip_prefix("tags/") {
4069 Some(format!("refs/tags/{tag}"))
@@ -45,6 +74,12 @@
4574 }
4675 }
4776
77+/// The braid ref that records where `branch` of the remote labelled `label`
78+/// was last seen: `remote/<label>/<branch>`.
79+pub fn remote_ref(label: &str, branch: &str) -> String {
80+ format!("{REMOTE_PREFIX}{label}/{branch}")
81+}
82+
4883 /// What `git_import` did.
4984 #[derive(Debug)]
5085 pub struct GitImport {
@@ -61,10 +96,55 @@
6196 }
6297 }
6398
99+/// A git map being added to, and the stored map it started from.
100+#[derive(Debug)]
101+pub(crate) struct WorkingMap {
102+ /// The map.
103+ pub(crate) map: GitMap,
104+ /// What [`MAP_REF`] pointed at when the map was read.
105+ base: Option<ObjectId>,
106+ /// What that map held.
107+ counts: MapCounts,
108+}
109+
110+impl WorkingMap {
111+ /// Whether the map holds more than the stored map it started from.
112+ pub(crate) fn changed(&self) -> bool {
113+ self.map.counts() != self.counts
114+ }
115+}
116+
117+/// What an operation that saves the git map expects of a ref.
118+#[derive(Clone, Debug)]
119+pub(crate) struct Move {
120+ /// The ref.
121+ pub(crate) name: String,
122+ /// The value it must hold, `None` for a ref that must not exist; or, when
123+ /// this is `None` itself, whatever it holds.
124+ pub(crate) expect: Option<Option<ObjectId>>,
125+ /// Its new value.
126+ pub(crate) new: ObjectId,
127+}
128+
129+/// Why an operation that saves the git map recorded nothing.
130+enum Abort {
131+ /// [`MAP_REF`] moved since the map was read.
132+ MapMoved(Option<ObjectId>),
133+ /// A ref did not hold the value the operation expected.
134+ Moved(String),
135+ /// Nothing would change.
136+ Nothing,
137+}
138+
64139 impl Repo {
65140 /// The current git map, empty if nothing was imported yet.
66141 pub fn git_map(&self) -> Result<GitMap, Error> {
67- let Some(id) = self.store.refs()?.get(MAP_REF) else {
142+ self.git_map_at(self.store.refs()?.get(MAP_REF))
143+ }
144+
145+ /// The git map stored as `id`, or the empty map.
146+ fn git_map_at(&self, id: Option<ObjectId>) -> Result<GitMap, Error> {
147+ let Some(id) = id else {
68148 return Ok(GitMap::new());
69149 };
70150 let Some((_, bytes)) = self.store.get(&id)? else {
@@ -73,6 +153,90 @@
73153 GitMap::from_bytes(&bytes).map_err(Error::GitMap)
74154 }
75155
156+ /// The git map stored as `base`, the value of [`MAP_REF`], to add to.
157+ pub(crate) fn working_map(&self, base: Option<ObjectId>) -> Result<WorkingMap, Error> {
158+ let map = self.git_map_at(base)?;
159+ let counts = map.counts();
160+ Ok(WorkingMap { map, base, counts })
161+ }
162+
163+ /// Records one operation by `agent` that makes the `moves` and, if the
164+ /// map grew, points [`MAP_REF`] at it. Returns `None` when nothing would
165+ /// change.
166+ ///
167+ /// If another operation saved a map meanwhile, the two are merged (see
168+ /// [`GitMap::absorb`]) and the operation is tried again, so that no
169+ /// pairing is lost. If a ref of `moves` does not hold what it should,
170+ /// nothing is recorded and the error is [`Error::BranchMoved`].
171+ pub(crate) fn save_with_map(
172+ &self,
173+ agent: &str,
174+ description: &str,
175+ map: &mut WorkingMap,
176+ moves: &[Move],
177+ ) -> Result<Option<Operation>, Error> {
178+ for _ in 0..MAP_ATTEMPTS {
179+ let map_id = if map.changed() {
180+ let id = self.store.put(Kind::Derived, &map.map.to_bytes())?;
181+ self.store.sync()?;
182+ Some(id)
183+ } else {
184+ None
185+ };
186+ let base = map.base;
187+ let result = self.store.transact(agent, description, |refs| {
188+ let mut updates = Vec::new();
189+ for wanted in moves {
190+ let found = refs.get(&wanted.name);
191+ if wanted.expect.is_some_and(|expected| expected != found) {
192+ return Err(Abort::Moved(wanted.name.clone()));
193+ }
194+ if found != Some(wanted.new) {
195+ updates.push(RefUpdate::new(wanted.name.clone(), found, Some(wanted.new)));
196+ }
197+ }
198+ if let Some(id) = map_id {
199+ let found = refs.get(MAP_REF);
200+ if found != base {
201+ return Err(Abort::MapMoved(found));
202+ }
203+ updates.push(RefUpdate::new(MAP_REF, found, Some(id)));
204+ }
205+ if updates.is_empty() {
206+ return Err(Abort::Nothing);
207+ }
208+ Ok(updates)
209+ });
210+ match result {
211+ Ok(operation) => {
212+ if let Some(id) = map_id {
213+ map.base = Some(id);
214+ map.counts = map.map.counts();
215+ }
216+ return Ok(Some(operation));
217+ }
218+ Err(TransactError::Aborted(Abort::Nothing)) => return Ok(None),
219+ Err(TransactError::Aborted(Abort::MapMoved(found))) => {
220+ let mut current = self.git_map_at(found)?;
221+ let counts = current.counts();
222+ current.absorb(&map.map);
223+ *map = WorkingMap {
224+ map: current,
225+ base: found,
226+ counts,
227+ };
228+ }
229+ Err(TransactError::Aborted(Abort::Moved(name))) => {
230+ return Err(Error::BranchMoved { branch: name });
231+ }
232+ Err(TransactError::Store(err)) => return Err(Error::Store(err)),
233+ }
234+ }
235+ Err(Error::Busy {
236+ name: MAP_REF.to_owned(),
237+ })
238+ }
239+
76240 /// Imports every branch and tag of the git repository at `git_repo`,
77241 /// incrementally, and points the matching braid refs at them.
78242 pub fn git_import(&self, git_repo: &Path, agent: &str) -> Result<GitImport, Error> {
@@ -118,9 +282,25 @@
118282 /// Writes the given braid refs (all of them when `names` is empty) into
119283 /// the git repository at `git_repo`, which must exist. Existing git refs
120284 /// of the same names are overwritten.
285+ ///
286+ /// The commits, trees and blobs the export generated for changesets made
287+ /// in braid are recorded in the git map, as an operation by
288+ /// [`GIT_EXPORT_AGENT`]; [`git_export_as`](Self::git_export_as) names
289+ /// the agent.
121290 pub fn git_export(&self, git_repo: &Path, names: &[String]) -> Result<WriteReport, Error> {
122- let map = self.git_map()?;
291+ self.git_export_as(git_repo, names, GIT_EXPORT_AGENT)
292+ }
293+
294+ /// [`git_export`](Self::git_export), recording the git map as an
295+ /// operation by `agent`.
296+ pub fn git_export_as(
297+ &self,
298+ git_repo: &Path,
299+ names: &[String],
300+ agent: &str,
301+ ) -> Result<WriteReport, Error> {
123302 let refs = self.store.refs()?;
303+ let mut map = self.working_map(refs.get(MAP_REF))?;
124304 let mut updates = Vec::new();
125305 for (name, id) in refs.iter() {
126306 if !names.is_empty() && !names.iter().any(|n| n == name) {
@@ -131,7 +311,7 @@
131311 };
132312 let target = match self.store.stat(&id)? {
133313 Some((Kind::Changeset, _)) => RefTarget::Changeset(id),
134- Some((Kind::Blob, _)) => match map.git_tag(&id) {
314+ Some((Kind::Blob, _)) => match map.map.git_tag(&id) {
135315 Some(tag) => RefTarget::Git(tag),
136316 None => {
137317 return Err(Error::NotExportable {
@@ -155,12 +335,13 @@
155335 return Err(Error::UnknownRevision(name.clone()));
156336 }
157337 }
158- Ok(braid_git::write_to_repo(
159- git_repo,
160- &self.store,
161- &map,
162- &updates,
163- )?)
338+ let report =
339+ braid_git::write_to_repo_recording(git_repo, &self.store, &mut map.map, &updates)?;
340+ if map.changed() {
341+ let description = format!("git export of {} refs", updates.len());
342+ self.save_with_map(agent, &description, &mut map, &[])?;
343+ }
344+ Ok(report)
164345 }
165346 }
166347
@@ -175,11 +356,22 @@
175356 ("refs/heads/feature/x", "feature/x"),
176357 ("refs/tags/v1.0", "tags/v1.0"),
177358 ("refs/notes/commits", "git/refs/notes/commits"),
359+ // Branches named like braid's own namespaces keep their full
360+ // names, so that none of them lands there.
361+ ("refs/heads/tags/v1", "git/refs/heads/tags/v1"),
362+ ("refs/heads/git/x", "git/refs/heads/git/x"),
363+ ("refs/heads/remote/a/main", "git/refs/heads/remote/a/main"),
364+ ("refs/heads/braid/git-map", "git/refs/heads/braid/git-map"),
365+ ("refs/heads/remotes", "remotes"),
366+ ("refs/heads/tags", "tags"),
178367 ] {
179368 assert_eq!(braid_ref_for_git(git.as_bytes()).as_deref(), Some(braid));
180369 assert_eq!(git_ref_for_braid(braid).as_deref(), Some(git));
181370 }
182371 assert_eq!(git_ref_for_braid(MAP_REF), None);
183372 assert_eq!(braid_ref_for_git(b"refs/heads/\xff"), None);
373+ let remote = remote_ref("origin-0123456789ab", "main");
374+ assert_eq!(remote, "remote/origin-0123456789ab/main");
375+ assert_eq!(git_ref_for_braid(&remote), None);
184376 }
185377 }
modified crates/repo/src/lib.rs +85 −4
@@ -1,12 +1,14 @@
11 // SPDX-License-Identifier: Apache-2.0
22 // Copyright (c) 2026 UtopiaIA
33
4-//! A braid repository on disk: where it is, how to open it, and how names
5-//! resolve to objects.
4+//! A braid repository on disk: where it is, how to open it, how names
5+//! resolve to objects, and how it trades history with git repositories.
66 //!
77 //! A repository is a directory holding a `.braid` directory. Inside it,
88 //! `store/` is the object store and op log shared by every process and every
9-//! workspace of the repository.
9+//! workspace of the repository, `git/` holds the mirrors of the git remotes
10+//! that [`Repo::git_sync`] keeps in step with, and the optional `config` file
11+//! holds settings (see [`Config`]).
1012 //!
1113 //! A workspace is any directory holding a `.braid` *file* instead: a
1214 //! [`WorkspaceLink`] naming the repository and the workspace. [`locate`] and
@@ -14,8 +16,11 @@
1416
1517 #![forbid(unsafe_code)]
1618
19+mod config;
1720 mod git;
1821 mod link;
22+mod remote;
23+mod sync;
1924 pub mod text;
2025
2126 use std::fs;
@@ -25,8 +30,15 @@
2530 use braid_format::{ObjectId, Objects};
2631 use braid_store::{Options, Store};
2732
28-pub use git::{GitImport, MAP_REF, braid_ref_for_git, git_ref_for_braid};
33+pub use braid_engine::{Conflict, ConflictHunk, ConflictKind, HunkSide};
34+pub use config::{CONFIG_FILE, Config};
35+pub use git::{
36+ GIT_EXPORT_AGENT, GitImport, MAP_REF, REMOTE_PREFIX, braid_ref_for_git, git_ref_for_braid,
37+ remote_ref,
38+};
2939 pub use link::{Location, WORKSPACES_DIR, WorkspaceLink, locate};
40+pub use remote::Remote;
41+pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport};
3042
3143 /// Name of the directory that holds a repository's data.
3244 pub const DIR: &str = ".braid";
@@ -74,6 +86,75 @@
7486 /// The file system failed.
7587 #[error(transparent)]
7688 Io(#[from] io::Error),
89+ /// A merge, or a walk of history, failed.
90+ #[error(transparent)]
91+ Engine(#[from] braid_engine::Error),
92+ /// A git remote braid does not hand to git.
93+ #[error("invalid remote {remote:?}: {reason}")]
94+ InvalidRemote {
95+ /// The remote as given.
96+ remote: String,
97+ /// Why it is refused.
98+ reason: &'static str,
99+ },
100+ /// A branch name sync cannot use.
101+ #[error("invalid branch name {name:?}: {reason}")]
102+ InvalidBranch {
103+ /// The name.
104+ name: String,
105+ /// Why it is refused.
106+ reason: &'static str,
107+ },
108+ /// An agent label that cannot name the committer of a git commit.
109+ #[error("the agent label {agent:?} cannot name a git committer: {reason}")]
110+ InvalidAgent {
111+ /// The label.
112+ agent: String,
113+ /// Why it cannot.
114+ reason: &'static str,
115+ },
116+ /// A setting of the repository's configuration that cannot be used.
117+ #[error("the setting {key:?} in .braid/config cannot be used: {reason}")]
118+ InvalidConfig {
119+ /// The setting.
120+ key: &'static str,
121+ /// Why.
122+ reason: &'static str,
123+ },
124+ /// A branch that should point at a changeset, or a remote branch that
125+ /// should point at a commit, does not.
126+ #[error("{what} does not point at a changeset")]
127+ NotAChangeset {
128+ /// Which branch.
129+ what: String,
130+ },
131+ /// Neither braid nor the remote has the branch to sync.
132+ #[error("neither braid nor the remote has the branch {branch:?}")]
133+ NothingToSync {
134+ /// The braid branch.
135+ branch: String,
136+ },
137+ /// Another operation moved a branch while sync was working on it.
138+ /// Nothing was pushed; syncing again starts from where it is now.
139+ #[error("branch {branch:?} moved during the sync; nothing was pushed, sync again")]
140+ BranchMoved {
141+ /// The branch.
142+ branch: String,
143+ },
144+ /// A ref kept moving, so an operation could not be recorded.
145+ #[error("ref {name:?} keeps moving; try again")]
146+ Busy {
147+ /// The ref.
148+ name: String,
149+ },
150+ /// A git command failed.
151+ #[error("git {command} failed: {detail}")]
152+ GitCommand {
153+ /// The git command.
154+ command: &'static str,
155+ /// What git said, or why it could not run.
156+ detail: String,
157+ },
77158 }
78159
79160 /// An open repository.
added crates/repo/src/remote.rs +518 −0
@@ -0,0 +1,518 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Git remotes for `git sync`: their addresses, the labels braid knows them
5+//! by, and the git commands that fetch from them and push to them.
6+//!
7+//! Fetching and pushing run the `git` binary as a subprocess, since gitoxide
8+//! does not push yet. Each command runs in braid's mirror of the remote, with
9+//! the caller's environment (so credentials, SSH settings and proxies work as
10+//! for any git command) except for the variables that would point git at
11+//! another repository, and with these settings on top of the user's: no
12+//! hooks, no automatic garbage collection or maintenance in the mirror, and
13+//! no `ext::` transport.
14+
15+use std::ffi::OsString;
16+use std::path::{Path, PathBuf};
17+use std::process::{Command, Output, Stdio};
18+
19+use braid_git::GitOid;
20+
21+use crate::Error;
22+
23+/// The longest name a label keeps from its remote, before the hash.
24+const MAX_LABEL_NAME: usize = 40;
25+
26+/// Hex digits of the hash at the end of a label.
27+const LABEL_HASH_DIGITS: usize = 12;
28+
29+/// A git remote: where it is, and the label braid knows it by.
30+#[derive(Clone, Debug, PartialEq, Eq)]
31+pub struct Remote {
32+ address: String,
33+ label: String,
34+}
35+
36+impl Remote {
37+ /// Reads a remote as given to `git sync`: a URL (`https://`, `ssh://`,
38+ /// `file://` and so on), an scp-like address such as `host:path`, or a
39+ /// path.
40+ ///
41+ /// A path is made absolute, against the current directory, and resolved
42+ /// when it exists, since the git commands run in the mirror. An address
43+ /// that is empty, starts with `-`, or holds a control character is
44+ /// refused.
45+ ///
46+ /// The label is the last name of the address's path, without `.git` and
47+ /// with every byte other than ASCII letters, digits, `.`, `_` and `-`
48+ /// turned into `-` (at most 40 of them, `remote` if none is left), then a
49+ /// `-` and the first 12 hex digits of the BLAKE3 hash of the address
50+ /// without any user name or password and without a trailing `/` or
51+ /// `.git`. So `https://example.org/team/project.git` is `project-` and 12
52+ /// hex digits, with or without `.git`, a trailing `/` or credentials, and
53+ /// credentials never reach a label.
54+ pub fn new(remote: &str) -> Result<Remote, Error> {
55+ let invalid = |reason| Error::InvalidRemote {
56+ remote: remote.to_owned(),
57+ reason,
58+ };
59+ if remote.is_empty() {
60+ return Err(invalid("it is empty"));
61+ }
62+ if remote.starts_with('-') {
63+ return Err(invalid("it starts with '-'"));
64+ }
65+ if remote.chars().any(char::is_control) {
66+ return Err(invalid("it holds a control character"));
67+ }
68+ let address = if remote.contains("://") || is_scp_like(remote) {
69+ remote.to_owned()
70+ } else {
71+ local_path(remote)?
72+ };
73+ let label = label_of(&address);
74+ Ok(Remote { address, label })
75+ }
76+
77+ /// The address git is given: the remote as written, or for a path, the
78+ /// absolute path.
79+ pub fn address(&self) -> &str {
80+ &self.address
81+ }
82+
83+ /// The label: a short name for the remote, made only of ASCII letters,
84+ /// digits, `.`, `_` and `-`. See [`Remote::new`].
85+ pub fn label(&self) -> &str {
86+ &self.label
87+ }
88+}
89+
90+/// Whether git reads an address as `[user@]host:path`, which goes over SSH:
91+/// a colon with no slash before it.
92+fn is_scp_like(address: &str) -> bool {
93+ match address.find(':') {
94+ Some(colon) => colon > 0 && !address[..colon].contains('/'),
95+ None => false,
96+ }
97+}
98+
99+/// A local path, absolute, and resolved when it exists.
100+fn local_path(path: &str) -> Result<String, Error> {
101+ let absolute = std::path::absolute(path)?;
102+ let resolved = absolute.canonicalize().unwrap_or_else(|_| absolute.clone());
103+ Ok(match resolved.to_str() {
104+ Some(text) => text.to_owned(),
105+ None => absolute.to_string_lossy().into_owned(),
106+ })
107+}
108+
109+/// The address without user name, password, trailing `/` or `.git`.
110+fn normalized(address: &str) -> String {
111+ let mut text = if let Some(scheme) = address.find("://") {
112+ let start = scheme + 3;
113+ let end = address[start..]
114+ .find('/')
115+ .map_or(address.len(), |slash| start + slash);
116+ match address[start..end].rfind('@') {
117+ Some(at) => format!("{}{}", &address[..start], &address[start + at + 1..]),
118+ None => address.to_owned(),
119+ }
120+ } else if is_scp_like(address) {
121+ let colon = address.find(':').unwrap_or(0);
122+ match address[..colon].rfind('@') {
123+ Some(at) => address[at + 1..].to_owned(),
124+ None => address.to_owned(),
125+ }
126+ } else {
127+ address.to_owned()
128+ };
129+ while text.ends_with('/') {
130+ text.pop();
131+ }
132+ if let Some(stripped) = text.strip_suffix(".git") {
133+ text.truncate(stripped.len());
134+ }
135+ while text.ends_with('/') {
136+ text.pop();
137+ }
138+ text
139+}
140+
141+fn label_of(address: &str) -> String {
142+ let normalized = normalized(address);
143+ let last = normalized.rsplit(['/', ':']).next().unwrap_or("");
144+ let mut name = String::new();
145+ for c in last.chars() {
146+ let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
147+ c
148+ } else {
149+ '-'
150+ };
151+ if !(c == '-' && name.ends_with('-')) {
152+ name.push(c);
153+ }
154+ }
155+ let mut name = name.trim_matches(['-', '.']).to_owned();
156+ if name.len() > MAX_LABEL_NAME {
157+ name.truncate(MAX_LABEL_NAME);
158+ name = name.trim_end_matches(['-', '.']).to_owned();
159+ }
160+ if name.is_empty() {
161+ name.push_str("remote");
162+ }
163+ let hash = blake3::hash(normalized.as_bytes()).to_hex();
164+ format!("{name}-{}", &hash[..LABEL_HASH_DIGITS])
165+}
166+
167+/// Environment variables that would point git at another repository, or
168+/// change which objects it sees. The commands sync runs never inherit them.
169+const REPOSITORY_VARIABLES: [&str; 13] = [
170+ "GIT_DIR",
171+ "GIT_WORK_TREE",
172+ "GIT_INDEX_FILE",
173+ "GIT_OBJECT_DIRECTORY",
174+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
175+ "GIT_COMMON_DIR",
176+ "GIT_NAMESPACE",
177+ "GIT_CEILING_DIRECTORIES",
178+ "GIT_REPLACE_REF_BASE",
179+ "GIT_NO_REPLACE_OBJECTS",
180+ "GIT_GRAFT_FILE",
181+ "GIT_SHALLOW_FILE",
182+ "GIT_QUARANTINE_PATH",
183+];
184+
185+/// Settings every command sync runs gets on top of the user's.
186+const SETTINGS: [&str; 4] = [
187+ "core.hooksPath=/dev/null",
188+ "gc.auto=0",
189+ "maintenance.auto=false",
190+ "protocol.ext.allow=never",
191+];
192+
193+/// Whether a fetch found the branch.
194+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195+pub(crate) enum Fetched {
196+ /// The branch was fetched into the ref asked for.
197+ Branch,
198+ /// The remote has no such branch.
199+ Absent,
200+}
201+
202+/// What a push did.
203+#[derive(Clone, Debug, PartialEq, Eq)]
204+pub(crate) enum Pushed {
205+ /// The remote branch points at the commit now.
206+ Done,
207+ /// The remote branch did not move; this is git's reason.
208+ Refused(String),
209+}
210+
211+/// The `git` binary, run with extra environment variables.
212+#[derive(Clone, Copy, Debug)]
213+pub(crate) struct Git<'a> {
214+ env: &'a [(OsString, OsString)],
215+}
216+
217+impl<'a> Git<'a> {
218+ pub(crate) fn new(env: &'a [(OsString, OsString)]) -> Self {
219+ Git { env }
220+ }
221+
222+ /// A git command that runs in the repository `git_dir`, if given.
223+ fn command(&self, git_dir: Option<&Path>) -> Command {
224+ let mut command = Command::new("git");
225+ command.envs(self.env.iter().map(|(key, value)| (key, value)));
226+ for variable in REPOSITORY_VARIABLES {
227+ command.env_remove(variable);
228+ }
229+ for setting in SETTINGS {
230+ command.arg("-c").arg(setting);
231+ }
232+ if let Some(dir) = git_dir {
233+ command.arg("--git-dir").arg(dir).current_dir(dir);
234+ }
235+ command
236+ .stdin(Stdio::null())
237+ .stdout(Stdio::piped())
238+ .stderr(Stdio::piped());
239+ command
240+ }
241+
242+ /// Runs a command and returns its output, whatever its exit status.
243+ fn output(&self, what: &'static str, mut command: Command) -> Result<Output, Error> {
244+ command.output().map_err(|err| Error::GitCommand {
245+ command: what,
246+ detail: format!("cannot run git: {err}"),
247+ })
248+ }
249+
250+ /// Runs a command that must succeed.
251+ fn run(&self, what: &'static str, command: Command) -> Result<Output, Error> {
252+ let output = self.output(what, command)?;
253+ if output.status.success() {
254+ Ok(output)
255+ } else {
256+ Err(failure(what, &output))
257+ }
258+ }
259+
260+ /// Creates an empty bare repository, without hooks or other templates.
261+ pub(crate) fn init_bare(&self, path: &Path) -> Result<(), Error> {
262+ let mut command = self.command(None);
263+ if let Some(parent) = path.parent() {
264+ command.current_dir(parent);
265+ }
266+ command
267+ .args(["init", "--quiet", "--bare", "--template="])
268+ .arg(path);
269+ self.run("init", command).map(drop)
270+ }
271+
272+ /// Fetches the branch `branch` (a full ref name) of `remote` into the ref
273+ /// `into` of the repository `git_dir`, which is deleted first so that
274+ /// the fetch never needs to force it. No tags, no submodules.
275+ pub(crate) fn fetch(
276+ &self,
277+ git_dir: &Path,
278+ remote: &str,
279+ branch: &str,
280+ into: &str,
281+ ) -> Result<Fetched, Error> {
282+ let mut delete = self.command(Some(git_dir));
283+ delete.args(["update-ref", "-d", into]);
284+ self.run("update-ref", delete)?;
285+
286+ let mut fetch = self.command(Some(git_dir));
287+ fetch
288+ .args([
289+ "fetch",
290+ "--quiet",
291+ "--no-tags",
292+ "--no-recurse-submodules",
293+ "--",
294+ remote,
295+ ])
296+ .arg(format!("{branch}:{into}"));
297+ let output = self.output("fetch", fetch)?;
298+ if output.status.success() {
299+ return Ok(Fetched::Branch);
300+ }
301+ // A missing branch is not an error; anything else is.
302+ match self.ls_remote(git_dir, remote, branch) {
303+ Ok(None) => Ok(Fetched::Absent),
304+ _ => Err(failure("fetch", &output)),
305+ }
306+ }
307+
308+ /// The commit the ref `name` (a full ref name) points to on `remote`.
309+ pub(crate) fn ls_remote(
310+ &self,
311+ git_dir: &Path,
312+ remote: &str,
313+ name: &str,
314+ ) -> Result<Option<GitOid>, Error> {
315+ let mut command = self.command(Some(git_dir));
316+ command.args(["ls-remote", "--", remote, name]);
317+ let output = self.run("ls-remote", command)?;
318+ let text = String::from_utf8_lossy(&output.stdout);
319+ for line in text.lines() {
320+ if let Some((oid, found)) = line.split_once('\t')
321+ && found == name
322+ {
323+ return oid.parse().map(Some).map_err(|_| Error::GitCommand {
324+ command: "ls-remote",
325+ detail: format!("unexpected output {line:?}"),
326+ });
327+ }
328+ }
329+ Ok(None)
330+ }
331+
332+ /// Pushes `commit` from the repository `git_dir` to the branch `branch`
333+ /// (a full ref name) of `remote`, only if that branch still points to
334+ /// `expected` (`None`: only if it does not exist): an atomic push with a
335+ /// lease, never a forced one.
336+ pub(crate) fn push(
337+ &self,
338+ git_dir: &Path,
339+ remote: &str,
340+ branch: &str,
341+ commit: GitOid,
342+ expected: Option<GitOid>,
343+ ) -> Result<Pushed, Error> {
344+ let lease = match expected {
345+ Some(oid) => format!("--force-with-lease={branch}:{oid}"),
346+ None => format!("--force-with-lease={branch}:"),
347+ };
348+ let refspec = format!("{commit}:{branch}");
349+ let mut command = self.command(Some(git_dir));
350+ command
351+ .args(["push", "--atomic", "--porcelain"])
352+ .arg(lease)
353+ .args(["--", remote])
354+ .arg(&refspec);
355+ let output = self.output("push", command)?;
356+ // Porcelain lines are `<flag> TAB <from>:<to> TAB <summary>`.
357+ let text = String::from_utf8_lossy(&output.stdout);
358+ for line in text.lines() {
359+ let mut fields = line.splitn(3, '\t');
360+ let (Some(flag), Some(spec)) = (fields.next(), fields.next()) else {
361+ continue;
362+ };
363+ if spec != refspec {
364+ continue;
365+ }
366+ let summary = fields.next().unwrap_or("").trim();
367+ return Ok(match flag {
368+ // A fast-forward, a new branch, or already there.
369+ " " | "*" | "=" => Pushed::Done,
370+ _ => Pushed::Refused(summary.to_owned()),
371+ });
372+ }
373+ Err(failure("push", &output))
374+ }
375+}
376+
377+/// The error for a git command that failed: its exit status and what it
378+/// said.
379+fn failure(what: &'static str, output: &Output) -> Error {
380+ let stderr = String::from_utf8_lossy(&output.stderr);
381+ let said: Vec<&str> = stderr
382+ .lines()
383+ .map(str::trim)
384+ .filter(|line| !line.is_empty())
385+ .collect();
386+ let status = match output.status.code() {
387+ Some(code) => format!("exit status {code}"),
388+ None => "killed".to_owned(),
389+ };
390+ Error::GitCommand {
391+ command: what,
392+ detail: if said.is_empty() {
393+ status
394+ } else {
395+ format!("{status}: {}", said.join("; "))
396+ },
397+ }
398+}
399+
400+/// A temporary bare repository, removed when dropped: where a dry run
401+/// fetches, borrowing the objects of the mirror when there is one.
402+#[derive(Debug)]
403+pub(crate) struct Scratch {
404+ path: PathBuf,
405+}
406+
407+impl Scratch {
408+ pub(crate) fn create(git: &Git<'_>, borrow: Option<&Path>) -> Result<Scratch, Error> {
409+ let base = std::path::absolute(std::env::temp_dir())?;
410+ let nanos = std::time::SystemTime::now()
411+ .duration_since(std::time::UNIX_EPOCH)
412+ .map_or(0, |elapsed| elapsed.subsec_nanos());
413+ let mut attempt = 0u32;
414+ let scratch = loop {
415+ let path = base.join(format!(
416+ "braid-sync-{}-{nanos}-{attempt}.git",
417+ std::process::id()
418+ ));
419+ match std::fs::create_dir(&path) {
420+ Ok(()) => break Scratch { path },
421+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt < 64 => {
422+ attempt += 1;
423+ }
424+ Err(err) => return Err(err.into()),
425+ }
426+ };
427+ git.init_bare(&scratch.path)?;
428+ if let Some(mirror) = borrow {
429+ let info = scratch.path.join("objects").join("info");
430+ std::fs::create_dir_all(&info)?;
431+ let objects = std::path::absolute(mirror.join("objects"))?;
432+ let mut line = objects.into_os_string();
433+ line.push("\n");
434+ std::fs::write(info.join("alternates"), line.as_encoded_bytes())?;
435+ }
436+ Ok(scratch)
437+ }
438+
439+ pub(crate) fn path(&self) -> &Path {
440+ &self.path
441+ }
442+}
443+
444+impl Drop for Scratch {
445+ fn drop(&mut self) {
446+ let _ = std::fs::remove_dir_all(&self.path);
447+ }
448+}
449+
450+#[cfg(test)]
451+mod tests {
452+ use super::*;
453+
454+ fn label(remote: &str) -> String {
455+ Remote::new(remote).unwrap().label().to_owned()
456+ }
457+
458+ #[test]
459+ fn labels() {
460+ let https = label("https://example.org/team/project.git");
461+ assert!(https.starts_with("project-"), "{https}");
462+ assert_eq!(https.len(), "project-".len() + LABEL_HASH_DIGITS);
463+ assert!(
464+ https[8..]
465+ .bytes()
466+ .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
467+ );
468+ // The same remote written differently, or with credentials.
469+ for same in [
470+ "https://example.org/team/project",
471+ "https://example.org/team/project/",
472+ "https://user:secret@example.org/team/project.git",
473+ "https://token@example.org/team/project.git/",
474+ ] {
475+ assert_eq!(label(same), https, "{same}");
476+ }
477+ assert_ne!(label("https://example.org/other/project.git"), https);
478+ // scp-like addresses, with or without a user.
479+ let scp = label("git@example.org:team/project.git");
480+ assert_eq!(label("example.org:team/project"), scp);
481+ assert!(scp.starts_with("project-"));
482+ assert_ne!(scp, https);
483+ // Odd names are cleaned, and nothing of the user part is kept.
484+ assert!(label("https://example.org/a/My Repo!!.git").starts_with("My-Repo-"));
485+ assert!(label("https://example.org/").starts_with("example.org-"));
486+ assert!(label("file:///").starts_with("remote-"));
487+ let long = format!("https://example.org/{}", "x".repeat(100));
488+ assert_eq!(label(&long).len(), MAX_LABEL_NAME + 1 + LABEL_HASH_DIGITS);
489+ assert!(!label("https://secret@example.org/r.git").contains("secret"));
490+ }
491+
492+ #[test]
493+ fn local_paths_become_absolute() {
494+ let dir = tempfile::tempdir().unwrap();
495+ let path = dir.path().join("remote.git");
496+ std::fs::create_dir(&path).unwrap();
497+ let remote = Remote::new(path.to_str().unwrap()).unwrap();
498+ assert!(Path::new(remote.address()).is_absolute());
499+ assert!(remote.label().starts_with("remote-"));
500+ let relative = Remote::new("some/relative/dir.git").unwrap();
501+ assert!(Path::new(relative.address()).is_absolute());
502+ assert!(relative.address().ends_with("some/relative/dir.git"));
503+ assert!(relative.label().starts_with("dir-"));
504+ // An scp-like address and a path with a colon after a slash.
505+ assert_eq!(Remote::new("host:dir").unwrap().address(), "host:dir");
506+ assert!(Path::new(Remote::new("./a:b").unwrap().address()).is_absolute());
507+ }
508+
509+ #[test]
510+ fn refused_remotes() {
511+ for bad in ["", "-upload-pack=touch", "a\nb", "a\0b", "a\tb"] {
512+ assert!(
513+ matches!(Remote::new(bad), Err(Error::InvalidRemote { .. })),
514+ "{bad:?}"
515+ );
516+ }
517+ }
518+}
added crates/repo/src/sync.rs +798 −0
@@ -0,0 +1,798 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! `git sync`: keeping a braid branch and a branch of a git remote in step,
5+//! so that a git host stays the public face of a repository while agents
6+//! land their changes in braid. See [`Repo::git_sync`].
7+
8+use std::ffi::OsString;
9+use std::fs::{self, File, OpenOptions};
10+use std::path::{Path, PathBuf};
11+use std::time::{SystemTime, UNIX_EPOCH};
12+
13+use braid_engine::{Conflict, MergeOutcome, is_ancestor, merge};
14+use braid_format::{Kind, MemoryObjects, ObjectId, Objects, Signature};
15+use braid_git::{Exporter, GitKind, GitOid, ImportOptions, RefTarget};
16+use braid_store::{Operation, Store};
17+
18+use crate::git::{MAP_REF, Move, RESERVED, WorkingMap, remote_ref};
19+use crate::remote::{Fetched, Git, Pushed, Remote, Scratch};
20+use crate::{DIR, Error, Repo};
21+
22+/// The directory inside [`DIR`] that holds the mirrors of git remotes.
23+pub const MIRRORS_DIR: &str = "git";
24+
25+/// What [`Repo::git_sync`] does besides its defaults.
26+#[derive(Clone, Debug, Default, PartialEq, Eq)]
27+pub struct SyncOptions {
28+ /// The branch of the remote, when its name differs from the braid
29+ /// branch's.
30+ pub remote_branch: Option<String>,
31+ /// Find out what the sync would do, and write nothing: no braid object,
32+ /// ref or operation, no mirror, no push. The remote branch is fetched
33+ /// into a temporary repository, removed afterwards.
34+ pub dry_run: bool,
35+ /// Environment variables to set for the git commands, on top of the
36+ /// process's own.
37+ pub git_env: Vec<(OsString, OsString)>,
38+}
39+
40+/// What a sync did, or would do.
41+#[derive(Clone, Debug, PartialEq, Eq)]
42+#[non_exhaustive]
43+pub enum SyncOutcome {
44+ /// The braid branch and the remote branch were at the same changeset.
45+ UpToDate,
46+ /// The braid branch did not exist; it was created at the remote's head.
47+ Created,
48+ /// The remote was ahead: the braid branch fast-forwarded to it.
49+ FastForwarded,
50+ /// Braid was ahead, or the remote had no such branch: the remote
51+ /// fast-forwarded to the braid branch, or the branch was created there.
52+ Pushed,
53+ /// Both had moved: braid merged them, moved its branch to the merge, and
54+ /// the remote fast-forwarded to it.
55+ Merged {
56+ /// The merge changeset.
57+ merge: ObjectId,
58+ /// The paths both sides changed, merged line by line or by kind.
59+ merged_paths: Vec<Vec<u8>>,
60+ },
61+ /// Both had moved, and the changes conflict. Nothing moved, and nothing
62+ /// was pushed.
63+ Conflicts(Vec<Conflict>),
64+ /// The push was refused because the remote branch moved after the fetch.
65+ /// Braid changed nothing, except that its branch is at the merge when
66+ /// one was made; the next sync takes the new commits in.
67+ RemoteMoved {
68+ /// Where the remote branch was found after the push failed.
69+ found: Option<GitOid>,
70+ },
71+ /// The remote refused the push for another reason, such as a protected
72+ /// branch. Braid changed nothing, except that its branch is at the merge
73+ /// when one was made.
74+ Rejected {
75+ /// Git's reason.
76+ reason: String,
77+ },
78+}
79+
80+impl SyncOutcome {
81+ /// A short, stable name for the outcome, for reports and JSON:
82+ /// `up_to_date`, `created`, `fast_forwarded`, `pushed`, `merged`,
83+ /// `conflicts`, `remote_moved` or `rejected`.
84+ pub fn code(&self) -> &'static str {
85+ match self {
86+ SyncOutcome::UpToDate => "up_to_date",
87+ SyncOutcome::Created => "created",
88+ SyncOutcome::FastForwarded => "fast_forwarded",
89+ SyncOutcome::Pushed => "pushed",
90+ SyncOutcome::Merged { .. } => "merged",
91+ SyncOutcome::Conflicts(_) => "conflicts",
92+ SyncOutcome::RemoteMoved { .. } => "remote_moved",
93+ SyncOutcome::Rejected { .. } => "rejected",
94+ }
95+ }
96+
97+ /// Whether the two branches are in step at the end: every outcome but
98+ /// conflicts and refused pushes.
99+ pub fn is_success(&self) -> bool {
100+ !matches!(
101+ self,
102+ SyncOutcome::Conflicts(_)
103+ | SyncOutcome::RemoteMoved { .. }
104+ | SyncOutcome::Rejected { .. }
105+ )
106+ }
107+}
108+
109+/// What [`Repo::git_sync`] did, or with a dry run, would do.
110+#[derive(Clone, Debug, PartialEq, Eq)]
111+pub struct SyncReport {
112+ /// The remote's label, which names its mirror and its braid ref.
113+ pub label: String,
114+ /// The braid branch.
115+ pub branch: String,
116+ /// The branch of the remote.
117+ pub remote_branch: String,
118+ /// The braid ref that records where the remote branch was last seen.
119+ pub remote_ref: String,
120+ /// What happened.
121+ pub outcome: SyncOutcome,
122+ /// The braid branch before the sync.
123+ pub before: Option<ObjectId>,
124+ /// The braid branch after it.
125+ pub after: Option<ObjectId>,
126+ /// The remote branch as fetched, its commit and its changeset, or `None`
127+ /// when the remote has no such branch.
128+ pub fetched: Option<(GitOid, ObjectId)>,
129+ /// The commit pushed to the remote branch, or with a dry run, the commit
130+ /// that would be.
131+ pub pushed: Option<GitOid>,
132+ /// How many commits were imported from the remote.
133+ pub imported: usize,
134+ /// Whether this was a dry run, which writes nothing.
135+ pub dry_run: bool,
136+ /// The operations recorded in the op log, oldest first.
137+ pub operations: Vec<Operation>,
138+}
139+
140+/// What the branches call for, once the remote branch is imported.
141+enum Decision {
142+ UpToDate,
143+ Create(ObjectId),
144+ FastForward(ObjectId),
145+ Push(ObjectId),
146+ Merge {
147+ changeset: ObjectId,
148+ merged_paths: Vec<Vec<u8>>,
149+ },
150+ Conflicts(Vec<Conflict>),
151+}
152+
153+/// The state after fetching and importing.
154+struct Prepared {
155+ map: WorkingMap,
156+ head: Option<ObjectId>,
157+ fetched: Option<(GitOid, ObjectId)>,
158+ imported: usize,
159+}
160+
161+/// A push that did not go through.
162+enum Refused {
163+ RemoteMoved(Option<GitOid>),
164+ Rejected(String),
165+}
166+
167+impl Refused {
168+ fn outcome(self) -> SyncOutcome {
169+ match self {
170+ Refused::RemoteMoved(found) => SyncOutcome::RemoteMoved { found },
171+ Refused::Rejected(reason) => SyncOutcome::Rejected { reason },
172+ }
173+ }
174+}
175+
176+impl Repo {
177+ /// Keeps the braid branch `branch` and a branch of the git remote
178+ /// `remote` in step: fetches and imports the remote branch, then
179+ /// fast-forwards the braid branch, or pushes it (merging first when both
180+ /// moved) as a fast-forward with a lease. Braid never force-pushes.
181+ /// Operations are recorded by `agent`, who is also the committer of a
182+ /// merge, with the `email` of the repository's [`Config`](crate::Config)
183+ /// or `<agent>@example.org`.
184+ ///
185+ /// # The mirror
186+ ///
187+ /// Braid keeps a bare git repository per remote, its mirror, at
188+ /// `.braid/git/<label>.git`, where `<label>` is the remote's label (see
189+ /// [`Remote::new`](crate::Remote::new)). In it,
190+ /// `refs/remotes/origin/<branch>` is the remote branch as last fetched,
191+ /// and `refs/heads/<branch>` the braid branch as last exported.
192+ /// `.braid/git/<label>.lock` is held while a sync with that remote runs,
193+ /// so syncs with one remote take turns.
194+ ///
195+ /// # Steps
196+ ///
197+ /// 1. The commits of the changesets on the braid branch are computed
198+ /// (exports are deterministic) and recorded in the git map, so that
199+ /// their copies on the remote import as the same changesets.
200+ /// 2. The remote branch is fetched into the mirror, with an explicit
201+ /// refspec and no tags, and imported. Its changeset G is recorded in
202+ /// the braid ref `remote/<label>/<branch>` (see [`remote_ref`]).
203+ /// 3. With B the head of the braid branch:
204+ /// - B is G: nothing to do;
205+ /// - there is no B: the braid branch is created at G;
206+ /// - B is an ancestor of G: the braid branch fast-forwards to G;
207+ /// - G is an ancestor of B, or the remote has no such branch: B is
208+ /// exported into the mirror and pushed;
209+ /// - otherwise the two are merged (see [`braid_engine::merge`]). A
210+ /// clean merge M moves the braid branch from B to M, and M is
211+ /// exported and pushed. Conflicts change nothing and are reported.
212+ ///
213+ /// The braid branch only ever moves with a compare and swap, in one
214+ /// operation with the git map and `remote/<label>/<branch>`.
215+ /// 4. A push is atomic and leased: `git push --atomic --porcelain
216+ /// --force-with-lease=refs/heads/<branch>:<fetched> <remote>
217+ /// <commit>:refs/heads/<branch>`, where `<fetched>` is G's commit as
218+ /// this same sync fetched it, or nothing when the remote had no such
219+ /// branch. What is pushed descends from G, so the remote only ever
220+ /// fast-forwards. If the remote moved meanwhile, the lease fails and
221+ /// nothing changes in braid (beyond the merge already made, if any);
222+ /// the next sync takes the new commits in.
223+ ///
224+ /// # Crashes
225+ ///
226+ /// A crash after a push and before braid records it loses nothing: the
227+ /// next sync computes the same commits again in step 1, so the commits it
228+ /// fetches are known as the changesets they came from, and nothing is
229+ /// imported twice. A crash between moving the braid branch to a merge and
230+ /// pushing it leaves the braid branch ahead, and the next sync pushes it.
231+ ///
232+ /// Conflicts and refused pushes are outcomes, not errors: see
233+ /// [`SyncOutcome`]. With [`SyncOptions::dry_run`], nothing is written.
234+ pub fn git_sync(
235+ &self,
236+ remote: &str,
237+ branch: &str,
238+ agent: &str,
239+ options: &SyncOptions,
240+ ) -> Result<SyncReport, Error> {
241+ let sync = Sync::new(self, remote, branch, agent, options)?;
242+ if options.dry_run {
243+ sync.dry_run()
244+ } else {
245+ sync.run()
246+ }
247+ }
248+
249+ /// The committer of the changesets sync makes: the agent label, and the
250+ /// email of the configuration or `<agent>@example.org`.
251+ fn sync_committer(&self, agent: &str) -> Result<Signature, Error> {
252+ if let Some(reason) = unfit_for_git(agent) {
253+ return Err(Error::InvalidAgent {
254+ agent: agent.to_owned(),
255+ reason,
256+ });
257+ }
258+ let email = match self.config()?.email {
259+ Some(email) => {
260+ if let Some(reason) = unfit_for_git(&email) {
261+ return Err(Error::InvalidConfig {
262+ key: "email",
263+ reason,
264+ });
265+ }
266+ email
267+ }
268+ None => format!("{}@example.org", email_name(agent)),
269+ };
270+ let seconds = SystemTime::now()
271+ .duration_since(UNIX_EPOCH)
272+ .map_or(0, |elapsed| i64::try_from(elapsed.as_secs()).unwrap_or(0));
273+ Ok(Signature {
274+ name: agent.as_bytes().to_vec(),
275+ email: email.into_bytes(),
276+ seconds,
277+ offset_minutes: 0,
278+ })
279+ }
280+}
281+
282+/// Why a name or an address cannot be written in a git signature, if it
283+/// cannot.
284+fn unfit_for_git(text: &str) -> Option<&'static str> {
285+ if text.trim().is_empty() {
286+ Some("it is empty")
287+ } else if text.contains(['<', '>', '\n', '\0']) {
288+ Some("it holds '<', '>', a newline or NUL")
289+ } else {
290+ None
291+ }
292+}
293+
294+/// The agent label as the local part of an email address.
295+fn email_name(agent: &str) -> String {
296+ let mut name = String::new();
297+ for c in agent.chars() {
298+ let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
299+ c
300+ } else {
301+ '-'
302+ };
303+ if !(c == '-' && name.ends_with('-')) {
304+ name.push(c);
305+ }
306+ }
307+ let name = name.trim_matches(['-', '.']);
308+ if name.is_empty() {
309+ "braid".to_owned()
310+ } else {
311+ name.to_owned()
312+ }
313+}
314+
315+/// Checks the names: a braid branch outside braid's own namespaces, and a
316+/// remote branch git accepts.
317+fn check_branches(branch: &str, remote_branch: &str) -> Result<(), Error> {
318+ let invalid = |name: &str, reason| Error::InvalidBranch {
319+ name: name.to_owned(),
320+ reason,
321+ };
322+ if branch.is_empty() || branch.contains('\0') {
323+ return Err(invalid(branch, "it is empty or holds NUL"));
324+ }
325+ if RESERVED.iter().any(|prefix| branch.starts_with(prefix)) {
326+ return Err(invalid(branch, "it is in one of braid's own namespaces"));
327+ }
328+ if !braid_git::is_branch_name(remote_branch) {
329+ return Err(invalid(remote_branch, "git does not accept it as a branch"));
330+ }
331+ Ok(())
332+}
333+
334+/// One sync with one remote.
335+struct Sync<'r> {
336+ repo: &'r Repo,
337+ git: Git<'r>,
338+ remote: Remote,
339+ agent: &'r str,
340+ committer: Signature,
341+ /// The braid branch.
342+ branch: String,
343+ /// The branch of the remote.
344+ remote_branch: String,
345+ /// Its full name, `refs/heads/<remote branch>`: on the remote, and in
346+ /// the mirror for the braid branch as last exported.
347+ branch_ref: String,
348+ /// The braid ref recording the remote branch.
349+ remote_ref: String,
350+ /// The mirror's ref for the remote branch as fetched.
351+ tracking_ref: String,
352+ /// The directory of the mirrors, absolute.
353+ mirrors: PathBuf,
354+}
355+
356+impl<'r> Sync<'r> {
357+ fn new(
358+ repo: &'r Repo,
359+ remote: &str,
360+ branch: &str,
361+ agent: &'r str,
362+ options: &'r SyncOptions,
363+ ) -> Result<Self, Error> {
364+ let remote = Remote::new(remote)?;
365+ let remote_branch = options
366+ .remote_branch
367+ .clone()
368+ .unwrap_or_else(|| branch.to_owned());
369+ check_branches(branch, &remote_branch)?;
370+ Ok(Sync {
371+ repo,
372+ git: Git::new(&options.git_env),
373+ remote_ref: remote_ref(remote.label(), &remote_branch),
374+ branch_ref: format!("refs/heads/{remote_branch}"),
375+ tracking_ref: format!("refs/remotes/origin/{remote_branch}"),
376+ committer: repo.sync_committer(agent)?,
377+ mirrors: std::path::absolute(repo.root.join(DIR).join(MIRRORS_DIR))?,
378+ branch: branch.to_owned(),
379+ remote_branch,
380+ remote,
381+ agent,
382+ })
383+ }
384+
385+ /// The remote's mirror.
386+ fn mirror(&self) -> PathBuf {
387+ self.mirrors.join(format!("{}.git", self.remote.label()))
388+ }
389+
390+ fn run(&self) -> Result<SyncReport, Error> {
391+ let (_lock, mirror) = self.open_mirror()?;
392+ let store = self.repo.store();
393+ let prepared = self.prepare(store, &mirror)?;
394+ let decision = self.decide(store, &prepared)?;
395+ self.execute(&mirror, prepared, decision)
396+ }
397+
398+ /// Takes the remote's lock, held until the returned file is dropped, and
399+ /// creates its mirror if there is none: an empty bare repository, made
400+ /// under a temporary name and renamed into place.
401+ fn open_mirror(&self) -> Result<(File, PathBuf), Error> {
402+ fs::create_dir_all(&self.mirrors)?;
403+ let label = self.remote.label();
404+ let lock = OpenOptions::new()
405+ .create(true)
406+ .truncate(false)
407+ .write(true)
408+ .open(self.mirrors.join(format!("{label}.lock")))?;
409+ lock.lock()?;
410+ let mirror = self.mirror();
411+ if !mirror.join("HEAD").is_file() {
412+ let partial = self.mirrors.join(format!("{label}.git.tmp"));
413+ if partial.exists() {
414+ fs::remove_dir_all(&partial)?;
415+ }
416+ self.git.init_bare(&partial)?;
417+ fs::rename(&partial, &mirror)?;
418+ }
419+ Ok((lock, mirror))
420+ }
421+
422+ /// Records the commits of the braid branch, fetches the remote branch
423+ /// into `fetch_repo` and imports it.
424+ fn prepare<O: Objects<Error = braid_store::Error>>(
425+ &self,
426+ objects: &O,
427+ fetch_repo: &Path,
428+ ) -> Result<Prepared, Error> {
429+ let refs = self.repo.store().refs()?;
430+ let head = refs.get(&self.branch);
431+ let mut map = self.repo.working_map(refs.get(MAP_REF))?;
432+ if let Some(head) = head {
433+ if !matches!(objects.stat(&head)?, Some((Kind::Changeset, _))) {
434+ return Err(Error::NotAChangeset {
435+ what: format!("branch {:?}", self.branch),
436+ });
437+ }
438+ // Exports are deterministic: the commits of braid's changesets
439+ // are what a remote holds of them, whether or not an earlier sync
440+ // got to record them. A head that cannot be exported fails later,
441+ // where it would be pushed.
442+ let pairings = {
443+ let mut exporter = Exporter::new(objects, &map.map);
444+ exporter.commit_id(&head).map(|_| exporter.pairings())
445+ };
446+ if let Ok(pairings) = pairings {
447+ map.map.record(&pairings);
448+ }
449+ }
450+
451+ let mut imported = 0;
452+ let fetched = match self.git.fetch(
453+ fetch_repo,
454+ self.remote.address(),
455+ &self.branch_ref,
456+ &self.tracking_ref,
457+ )? {
458+ Fetched::Absent => None,
459+ Fetched::Branch => {
460+ let options = ImportOptions {
461+ refs: vec![self.tracking_ref.clone().into_bytes()],
462+ };
463+ let report = braid_git::import(fetch_repo, objects, &mut map.map, &options)?;
464+ imported = report.commits;
465+ let fetched = report.refs.into_iter().next().ok_or(Error::NotAChangeset {
466+ what: "the remote branch".to_owned(),
467+ })?;
468+ if fetched.kind != GitKind::Commit {
469+ return Err(Error::NotAChangeset {
470+ what: "the remote branch".to_owned(),
471+ });
472+ }
473+ Some((fetched.oid, fetched.braid))
474+ }
475+ };
476+ Ok(Prepared {
477+ map,
478+ head,
479+ fetched,
480+ imported,
481+ })
482+ }
483+
484+ /// What the two heads call for. A merge is made, and stored in
485+ /// `objects`, when both moved.
486+ fn decide<O: Objects<Error = braid_store::Error>>(
487+ &self,
488+ objects: &O,
489+ prepared: &Prepared,
490+ ) -> Result<Decision, Error> {
491+ let remote = prepared.fetched.map(|(_, changeset)| changeset);
492+ Ok(match (prepared.head, remote) {
493+ (None, None) => {
494+ return Err(Error::NothingToSync {
495+ branch: self.branch.clone(),
496+ });
497+ }
498+ (None, Some(remote)) => Decision::Create(remote),
499+ (Some(head), None) => Decision::Push(head),
500+ (Some(head), Some(remote)) if head == remote => Decision::UpToDate,
501+ (Some(head), Some(remote)) if is_ancestor(objects, remote, head)? => {
502+ Decision::Push(head)
503+ }
504+ (Some(head), Some(remote)) => {
505+ let message = format!("Merge {} into {}\n", self.remote_ref, self.branch);
506+ match merge(
507+ objects,
508+ head,
509+ remote,
510+ self.committer.clone(),
511+ message.into_bytes(),
512+ )? {
513+ MergeOutcome::UpToDate => Decision::Push(head),
514+ MergeOutcome::FastForward(to) => Decision::FastForward(to),
515+ MergeOutcome::Merged {
516+ changeset,
517+ merged_paths,
518+ } => Decision::Merge {
519+ changeset,
520+ merged_paths,
521+ },
522+ MergeOutcome::Conflicts(conflicts) => Decision::Conflicts(conflicts),
523+ }
524+ }
525+ })
526+ }
527+
528+ fn report(&self, prepared: &Prepared, dry_run: bool) -> SyncReport {
529+ SyncReport {
530+ label: self.remote.label().to_owned(),
531+ branch: self.branch.clone(),
532+ remote_branch: self.remote_branch.clone(),
533+ remote_ref: self.remote_ref.clone(),
534+ outcome: SyncOutcome::UpToDate,
535+ before: prepared.head,
536+ after: prepared.head,
537+ fetched: prepared.fetched,
538+ pushed: None,
539+ imported: prepared.imported,
540+ dry_run,
541+ operations: Vec::new(),
542+ }
543+ }
544+
545+ /// Carries a decision out.
546+ fn execute(
547+ &self,
548+ mirror: &Path,
549+ mut prepared: Prepared,
550+ decision: Decision,
551+ ) -> Result<SyncReport, Error> {
552+ let mut report = self.report(&prepared, false);
553+ let head = prepared.head;
554+ let fetched = prepared.fetched.map(|(commit, _)| commit);
555+ let remote = prepared.fetched.map(|(_, changeset)| changeset);
556+ let map = &mut prepared.map;
557+ report.outcome = match decision {
558+ Decision::UpToDate => {
559+ // What step 1 and the import added to the map, and where the
560+ // remote branch is.
561+ report
562+ .operations
563+ .extend(self.save("up to date", map, None, remote)?);
564+ SyncOutcome::UpToDate
565+ }
566+ Decision::Create(to) => {
567+ report.operations.extend(self.save(
568+ &format!("created {}", self.branch),
569+ map,
570+ Some((None, to)),
571+ Some(to),
572+ )?);
573+ report.after = Some(to);
574+ SyncOutcome::Created
575+ }
576+ Decision::FastForward(to) => {
577+ report.operations.extend(self.save(
578+ "fast-forward",
579+ map,
580+ Some((head, to)),
581+ Some(to),
582+ )?);
583+ report.after = Some(to);
584+ SyncOutcome::FastForwarded
585+ }
586+ Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
587+ Decision::Push(target) => {
588+ let commit = self.export(mirror, map, target)?;
589+ match self.push(mirror, commit, fetched)? {
590+ Ok(()) => {
591+ report.operations.extend(self.save(
592+ &format!("pushed {commit}"),
593+ map,
594+ None,
595+ Some(target),
596+ )?);
597+ report.pushed = Some(commit);
598+ SyncOutcome::Pushed
599+ }
600+ Err(refused) => refused.outcome(),
601+ }
602+ }
603+ Decision::Merge {
604+ changeset,
605+ merged_paths,
606+ } => {
607+ let commit = self.export(mirror, map, changeset)?;
608+ report.operations.extend(self.save(
609+ "merge",
610+ map,
611+ Some((head, changeset)),
612+ remote,
613+ )?);
614+ report.after = Some(changeset);
615+ match self.push(mirror, commit, fetched)? {
616+ Ok(()) => {
617+ report.operations.extend(self.save(
618+ &format!("pushed {commit}"),
619+ map,
620+ None,
621+ Some(changeset),
622+ )?);
623+ report.pushed = Some(commit);
624+ SyncOutcome::Merged {
625+ merge: changeset,
626+ merged_paths,
627+ }
628+ }
629+ Err(refused) => refused.outcome(),
630+ }
631+ }
632+ };
633+ Ok(report)
634+ }
635+
636+ /// Records an operation: the braid branch moved from one value to
637+ /// another, the remote ref to its value, and the map when it grew.
638+ fn save(
639+ &self,
640+ what: &str,
641+ map: &mut WorkingMap,
642+ branch: Option<(Option<ObjectId>, ObjectId)>,
643+ remote: Option<ObjectId>,
644+ ) -> Result<Option<Operation>, Error> {
645+ let mut moves = Vec::new();
646+ if let Some((from, to)) = branch {
647+ moves.push(Move {
648+ name: self.branch.clone(),
649+ expect: Some(from),
650+ new: to,
651+ });
652+ }
653+ if let Some(remote) = remote {
654+ moves.push(Move {
655+ name: self.remote_ref.clone(),
656+ expect: None,
657+ new: remote,
658+ });
659+ }
660+ let description = format!("git sync {} with {}: {what}", self.branch, self.remote_ref);
661+ self.repo
662+ .save_with_map(self.agent, &description, map, &moves)
663+ }
664+
665+ /// Exports a changeset into the mirror, as the mirror's branch, and
666+ /// records in the map what the export generated. Returns its commit.
667+ fn export(
668+ &self,
669+ mirror: &Path,
670+ map: &mut WorkingMap,
671+ changeset: ObjectId,
672+ ) -> Result<GitOid, Error> {
673+ let report = braid_git::write_to_repo_recording(
674+ mirror,
675+ self.repo.store(),
676+ &mut map.map,
677+ &[braid_git::RefUpdate {
678+ name: self.branch_ref.clone().into_bytes(),
679+ target: RefTarget::Changeset(changeset),
680+ }],
681+ )?;
682+ Ok(report.refs[0].1)
683+ }
684+
685+ /// Pushes a commit with a lease on what was fetched.
686+ fn push(
687+ &self,
688+ mirror: &Path,
689+ commit: GitOid,
690+ expected: Option<GitOid>,
691+ ) -> Result<Result<(), Refused>, Error> {
692+ let address = self.remote.address();
693+ let reason = match self
694+ .git
695+ .push(mirror, address, &self.branch_ref, commit, expected)?
696+ {
697+ Pushed::Done => return Ok(Ok(())),
698+ Pushed::Refused(reason) => reason,
699+ };
700+ // Whether the remote moved, or refused for another reason.
701+ Ok(
702+ match self.git.ls_remote(mirror, address, &self.branch_ref) {
703+ Ok(found) if found == Some(commit) => Ok(()),
704+ Ok(found) if found != expected => Err(Refused::RemoteMoved(found)),
705+ _ => Err(Refused::Rejected(reason)),
706+ },
707+ )
708+ }
709+
710+ /// Everything [`run`](Self::run) would do up to the push, on a copy:
711+ /// the remote branch is fetched into a temporary repository that borrows
712+ /// the mirror's objects, and braid objects go to memory.
713+ fn dry_run(&self) -> Result<SyncReport, Error> {
714+ let mirror = self.mirror();
715+ let borrow = mirror.join("HEAD").is_file().then_some(mirror.as_path());
716+ let scratch = Scratch::create(&self.git, borrow)?;
717+ let overlay = Overlay {
718+ store: self.repo.store(),
719+ added: MemoryObjects::new(),
720+ };
721+ let prepared = self.prepare(&overlay, scratch.path())?;
722+ let decision = self.decide(&overlay, &prepared)?;
723+ let mut report = self.report(&prepared, true);
724+ let commit_of = |changeset: ObjectId| -> Result<GitOid, Error> {
725+ Ok(Exporter::new(&overlay, &prepared.map.map).commit_id(&changeset)?)
726+ };
727+ report.outcome = match decision {
728+ Decision::UpToDate => SyncOutcome::UpToDate,
729+ Decision::Create(to) => {
730+ report.after = Some(to);
731+ SyncOutcome::Created
732+ }
733+ Decision::FastForward(to) => {
734+ report.after = Some(to);
735+ SyncOutcome::FastForwarded
736+ }
737+ Decision::Push(target) => {
738+ report.pushed = Some(commit_of(target)?);
739+ SyncOutcome::Pushed
740+ }
741+ Decision::Merge {
742+ changeset,
743+ merged_paths,
744+ } => {
745+ report.pushed = Some(commit_of(changeset)?);
746+ report.after = Some(changeset);
747+ SyncOutcome::Merged {
748+ merge: changeset,
749+ merged_paths,
750+ }
751+ }
752+ Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
753+ };
754+ Ok(report)
755+ }
756+}
757+
758+/// The store, with what is written kept in memory: what a dry run works on.
759+struct Overlay<'s> {
760+ store: &'s Store,
761+ added: MemoryObjects,
762+}
763+
764+impl Objects for Overlay<'_> {
765+ type Error = braid_store::Error;
766+
767+ fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
768+ let Ok(found) = self.added.get(id);
769+ match found {
770+ Some(found) => Ok(Some(found)),
771+ None => self.store.get(id),
772+ }
773+ }
774+
775+ fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
776+ let Ok(id) = self.added.put(kind, payload);
777+ Ok(id)
778+ }
779+
780+ fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> {
781+ let Ok(found) = self.added.contains(id);
782+ if found {
783+ return Ok(true);
784+ }
785+ self.store.contains(id)
786+ }
787+
788+ fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> {
789+ let Ok(found) = self.added.stat(id);
790+ match found {
791+ Some(found) => Ok(Some(found)),
792+ None => self.store.stat(id),
793+ }
794+ }
795+}
796+
797+#[cfg(test)]
798+mod tests;
added crates/repo/src/sync/tests.rs +1021 −0
@@ -0,0 +1,1021 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Tests of `git sync`, against local bare repositories playing the remote.
5+//!
6+//! Every git command here, those of the tests and those sync runs, ignores
7+//! the user's and the system's configuration and has fixed identities and
8+//! dates. Remotes keep a reflog of their branch, and every test that pushes
9+//! checks that it only ever moved forward.
10+
11+use std::cell::Cell;
12+use std::collections::HashSet;
13+use std::ffi::OsString;
14+use std::path::{Path, PathBuf};
15+use std::process::Command;
16+
17+use braid_engine::{ConflictKind, commit, read_changeset};
18+use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
19+use braid_git::{GitOid, export_commit};
20+use braid_store::RefUpdate;
21+use tempfile::TempDir;
22+
23+use super::*;
24+use crate::Repo;
25+
26+/// The environment of every git command: no configuration but the
27+/// repository's, fixed identities, never a prompt.
28+fn git_env() -> Vec<(OsString, OsString)> {
29+ [
30+ ("GIT_CONFIG_GLOBAL", "/dev/null"),
31+ ("GIT_CONFIG_NOSYSTEM", "1"),
32+ ("GIT_AUTHOR_NAME", "Ada Lovelace"),
33+ ("GIT_AUTHOR_EMAIL", "ada@example.org"),
34+ ("GIT_COMMITTER_NAME", "Charles Babbage"),
35+ ("GIT_COMMITTER_EMAIL", "charles@example.org"),
36+ ("GIT_TERMINAL_PROMPT", "0"),
37+ ]
38+ .into_iter()
39+ .map(|(key, value)| (key.into(), value.into()))
40+ .collect()
41+}
42+
43+/// Runs git in `dir` and returns its output, trimmed. `date` is the author
44+/// and committer date of anything it commits.
45+fn git_at(dir: &Path, date: i64, args: &[&str]) -> String {
46+ let mut command = Command::new("git");
47+ for variable in [
48+ "GIT_DIR",
49+ "GIT_WORK_TREE",
50+ "GIT_INDEX_FILE",
51+ "GIT_OBJECT_DIRECTORY",
52+ ] {
53+ command.env_remove(variable);
54+ }
55+ let output = command
56+ .current_dir(dir)
57+ .envs(git_env())
58+ .env("GIT_AUTHOR_DATE", format!("{date} +0100"))
59+ .env("GIT_COMMITTER_DATE", format!("{date} +0100"))
60+ .args([
61+ "-c",
62+ "init.defaultBranch=main",
63+ "-c",
64+ "commit.gpgSign=false",
65+ ])
66+ .args(args)
67+ .output()
68+ .expect("git must be installed to run these tests");
69+ assert!(
70+ output.status.success(),
71+ "git {args:?} failed: {}",
72+ String::from_utf8_lossy(&output.stderr)
73+ );
74+ String::from_utf8(output.stdout).unwrap().trim().to_owned()
75+}
76+
77+fn git(dir: &Path, args: &[&str]) -> String {
78+ git_at(dir, EPOCH, args)
79+}
80+
81+/// The first commit time; each commit adds a minute.
82+const EPOCH: i64 = 1_700_000_000;
83+
84+/// A file to write, or `None` to delete it.
85+type Edit<'a> = (&'a str, Option<&'a str>);
86+
87+/// A remote, a clone of it where others work, and a braid repository.
88+struct World {
89+ _dir: TempDir,
90+ root: PathBuf,
91+ remote: PathBuf,
92+ work: PathBuf,
93+ braid: Repo,
94+ clock: Cell<i64>,
95+}
96+
97+impl World {
98+ fn new() -> World {
99+ let dir = tempfile::tempdir().unwrap();
100+ let root = dir.path().to_path_buf();
101+ git(&root, &["init", "--quiet", "--bare", "remote.git"]);
102+ let remote = root.join("remote.git");
103+ // Bare repositories keep no reflog unless asked to.
104+ git(&remote, &["config", "core.logAllRefUpdates", "true"]);
105+ let work = root.join("work");
106+ git(&root, &["init", "--quiet", "work"]);
107+ git(
108+ &work,
109+ &["remote", "add", "origin", remote.to_str().unwrap()],
110+ );
111+ let braid = Repo::init(&root.join("braid")).unwrap();
112+ World {
113+ _dir: dir,
114+ root,
115+ remote,
116+ work,
117+ braid,
118+ clock: Cell::new(EPOCH),
119+ }
120+ }
121+
122+ fn remote_address(&self) -> &str {
123+ self.remote.to_str().unwrap()
124+ }
125+
126+ fn options(&self) -> SyncOptions {
127+ SyncOptions {
128+ git_env: git_env(),
129+ ..SyncOptions::default()
130+ }
131+ }
132+
133+ fn sync_with(&self, options: &SyncOptions) -> Result<SyncReport, Error> {
134+ self.braid
135+ .git_sync(self.remote_address(), "main", "tester", options)
136+ }
137+
138+ fn sync(&self) -> SyncReport {
139+ self.sync_with(&self.options())
140+ .unwrap_or_else(|err| panic!("{err}"))
141+ }
142+
143+ /// The internal steps of one sync.
144+ fn steps<'a>(&'a self, options: &'a SyncOptions) -> Sync<'a> {
145+ Sync::new(
146+ &self.braid,
147+ self.remote_address(),
148+ "main",
149+ "tester",
150+ options,
151+ )
152+ .unwrap()
153+ }
154+
155+ /// Commits `edits` in the clone, on top of the remote's main; returns
156+ /// the commit.
157+ fn commit_elsewhere(&self, edits: &[Edit<'_>], message: &str) -> String {
158+ if self.remote_head().is_some() {
159+ git(&self.work, &["fetch", "--quiet", "origin", "main"]);
160+ git(
161+ &self.work,
162+ &["checkout", "--quiet", "-B", "main", "FETCH_HEAD"],
163+ );
164+ }
165+ for (path, content) in edits {
166+ let file = self.work.join(path);
167+ match content {
168+ Some(content) => {
169+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();
170+ std::fs::write(&file, content).unwrap();
171+ git(&self.work, &["add", path]);
172+ }
173+ None => {
174+ git(&self.work, &["rm", "--quiet", path]);
175+ }
176+ }
177+ }
178+ self.clock.set(self.clock.get() + 60);
179+ git_at(
180+ &self.work,
181+ self.clock.get(),
182+ &["commit", "--quiet", "-m", message],
183+ );
184+ git(&self.work, &["rev-parse", "HEAD"])
185+ }
186+
187+ /// Commits `edits` elsewhere and pushes them to the remote, as a
188+ /// fast-forward.
189+ fn push_elsewhere(&self, edits: &[Edit<'_>], message: &str) -> String {
190+ let commit = self.commit_elsewhere(edits, message);
191+ git(&self.work, &["push", "--quiet", "origin", "main"]);
192+ commit
193+ }
194+
195+ /// The remote's main, if it has one.
196+ fn remote_head(&self) -> Option<String> {
197+ let found = git(
198+ &self.remote,
199+ &["for-each-ref", "--format=%(objectname)", "refs/heads/main"],
200+ );
201+ (!found.is_empty()).then_some(found)
202+ }
203+
204+ fn head(&self) -> Option<ObjectId> {
205+ self.braid.store().refs().unwrap().get("main")
206+ }
207+
208+ /// Makes a changeset in braid on main with `edits`, and lands it.
209+ fn commit_in_braid(&self, edits: &[Edit<'_>], message: &str) -> ObjectId {
210+ let store = self.braid.store();
211+ let changes: Vec<Change> = edits
212+ .iter()
213+ .map(|(path, content)| Change {
214+ path: path.as_bytes().to_vec(),
215+ op: match content {
216+ Some(content) => ChangeOp::File {
217+ blob: store.put(Kind::Blob, content.as_bytes()).unwrap(),
218+ size: content.len() as u64,
219+ },
220+ None => ChangeOp::Delete,
221+ },
222+ })
223+ .collect();
224+ let head = self.head();
225+ let grace = Signature {
226+ name: b"Grace Hopper".to_vec(),
227+ email: b"grace@example.org".to_vec(),
228+ seconds: 1_700_000_000,
229+ offset_minutes: -300,
230+ };
231+ let id = commit(
232+ store,
233+ head.into_iter().collect(),
234+ changes,
235+ grace.clone(),
236+ grace,
237+ message.as_bytes().to_vec(),
238+ Vec::new(),
239+ )
240+ .unwrap();
241+ store.sync().unwrap();
242+ store
243+ .transact("agent", "land", |refs| {
244+ Ok::<_, std::convert::Infallible>(vec![RefUpdate::new(
245+ "main",
246+ refs.get("main"),
247+ Some(id),
248+ )])
249+ })
250+ .unwrap();
251+ id
252+ }
253+
254+ fn operations(&self) -> usize {
255+ self.braid.store().log(usize::MAX).unwrap().len()
256+ }
257+
258+ fn objects(&self) -> u64 {
259+ self.braid.store().fsck().unwrap().objects
260+ }
261+
262+ fn map(&self) -> braid_git::GitMap {
263+ self.braid.git_map().unwrap()
264+ }
265+
266+ /// The file at `path` in the remote's main.
267+ fn remote_file(&self, path: &str) -> String {
268+ git(&self.remote, &["show", &format!("main:{path}")])
269+ }
270+
271+ /// Every commit of the remote's main, and every changeset of braid's
272+ /// main, are the same history: one changeset per commit, through the
273+ /// map, and no other.
274+ fn assert_same_history(&self) {
275+ let commits: HashSet<String> = git(&self.remote, &["rev-list", "main"])
276+ .lines()
277+ .map(str::to_owned)
278+ .collect();
279+ let mut changesets = HashSet::new();
280+ let mut pending: Vec<ObjectId> = self.head().into_iter().collect();
281+ while let Some(id) = pending.pop() {
282+ if changesets.insert(id) {
283+ pending.extend(read_changeset(self.braid.store(), id).unwrap().parents);
284+ }
285+ }
286+ assert_eq!(commits.len(), changesets.len(), "one changeset per commit");
287+ let map = self.map();
288+ for commit in &commits {
289+ let changeset = map
290+ .changeset(&commit.parse().unwrap())
291+ .unwrap_or_else(|| panic!("commit {commit} is not in the map"));
292+ assert!(changesets.contains(&changeset), "commit {commit}");
293+ }
294+ }
295+
296+ /// The remote's main only ever moved forward: each update in its
297+ /// reflog starts where the one before ended and is a fast-forward.
298+ fn assert_forward_only(&self) {
299+ let log = std::fs::read_to_string(self.remote.join("logs/refs/heads/main")).unwrap();
300+ let zero = "0".repeat(40);
301+ let mut last = zero.clone();
302+ for line in log.lines() {
303+ let mut words = line.split(' ');
304+ let (old, new) = (words.next().unwrap(), words.next().unwrap());
305+ assert_eq!(old, last, "the reflog is continuous");
306+ if old != zero {
307+ git(&self.remote, &["merge-base", "--is-ancestor", old, new]);
308+ }
309+ last = new.to_owned();
310+ }
311+ assert_eq!(Some(last), self.remote_head());
312+ }
313+
314+ /// A second sync changes nothing: no operation, no object.
315+ fn assert_sync_is_a_no_op(&self) {
316+ let (operations, objects) = (self.operations(), self.objects());
317+ let head = self.remote_head();
318+ let report = self.sync();
319+ assert_eq!(report.outcome, SyncOutcome::UpToDate);
320+ assert!(report.operations.is_empty());
321+ assert_eq!(report.imported, 0);
322+ assert_eq!(self.operations(), operations);
323+ assert_eq!(self.objects(), objects);
324+ assert_eq!(self.remote_head(), head);
325+ }
326+}
327+
328+fn oid(text: &str) -> GitOid {
329+ text.parse().unwrap()
330+}
331+
332+#[test]
333+fn the_first_sync_creates_the_branch() {
334+ let world = World::new();
335+ world.push_elsewhere(&[("README", Some("hello\n"))], "first");
336+ let second = world.push_elsewhere(&[("src/lib.rs", Some("pub fn f() {}\n"))], "second");
337+
338+ let report = world.sync();
339+ assert_eq!(report.outcome, SyncOutcome::Created);
340+ assert!(report.outcome.is_success());
341+ assert_eq!(report.imported, 2);
342+ assert_eq!(report.before, None);
343+ let changeset = world.map().changeset(&oid(&second)).unwrap();
344+ assert_eq!(report.after, Some(changeset));
345+ assert_eq!(report.fetched, Some((oid(&second), changeset)));
346+ assert_eq!(report.pushed, None);
347+ assert_eq!(report.operations.len(), 1);
348+ assert_eq!(report.operations[0].agent, "tester");
349+ assert_eq!(world.head(), Some(changeset));
350+ let refs = world.braid.store().refs().unwrap();
351+ assert_eq!(refs.get(&report.remote_ref), Some(changeset));
352+ assert!(report.remote_ref.starts_with("remote/remote-"));
353+ assert!(report.remote_ref.ends_with("/main"));
354+
355+ // The mirror, its lock, and the branch as fetched.
356+ let mirror = world
357+ .root
358+ .join("braid/.braid/git")
359+ .join(format!("{}.git", report.label));
360+ assert!(mirror.join("HEAD").is_file());
361+ assert!(
362+ world
363+ .root
364+ .join("braid/.braid/git")
365+ .join(format!("{}.lock", report.label))
366+ .is_file()
367+ );
368+ assert_eq!(
369+ git(&mirror, &["rev-parse", "refs/remotes/origin/main"]),
370+ second
371+ );
372+
373+ world.assert_same_history();
374+ world.assert_sync_is_a_no_op();
375+}
376+
377+#[test]
378+fn braid_ahead_is_pushed() {
379+ let world = World::new();
380+ let first = world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
381+ world.sync();
382+ let one = world.commit_in_braid(&[("a", Some("2\n"))], "Made in braid\n");
383+ let two = world.commit_in_braid(&[("c/d", Some("new\n")), ("b", None)], "Again\n");
384+
385+ let report = world.sync();
386+ assert_eq!(report.outcome, SyncOutcome::Pushed);
387+ assert_eq!(report.before, Some(two));
388+ assert_eq!(report.after, Some(two));
389+ assert_eq!(report.imported, 0);
390+ assert_eq!(report.operations.len(), 1);
391+ let pushed = report.pushed.unwrap();
392+ assert_eq!(world.remote_head(), Some(pushed.to_hex()));
393+
394+ // The remote got exactly braid's commits, as the export makes them.
395+ let map = world.map();
396+ assert_eq!(map.commit(&two), Some(pushed));
397+ let store = world.braid.store();
398+ for changeset in [one, two] {
399+ let (commit, bytes) = export_commit(store, &map, &changeset).unwrap();
400+ let shown = Command::new("git")
401+ .current_dir(&world.remote)
402+ .envs(git_env())
403+ .args(["cat-file", "commit", &commit.to_hex()])
404+ .output()
405+ .unwrap();
406+ assert_eq!(shown.stdout, bytes);
407+ }
408+ assert_eq!(
409+ git(&world.remote, &["rev-list", "main"]),
410+ [pushed, map.commit(&one).unwrap(), oid(&first)]
411+ .map(|commit| commit.to_hex())
412+ .join("\n")
413+ );
414+ assert_eq!(world.remote_file("a"), "2");
415+ assert_eq!(world.remote_file("c/d"), "new");
416+ let refs = world.braid.store().refs().unwrap();
417+ assert_eq!(refs.get(&report.remote_ref), Some(two));
418+
419+ world.assert_same_history();
420+ world.assert_forward_only();
421+ world.assert_sync_is_a_no_op();
422+}
423+
424+#[test]
425+fn remote_ahead_fast_forwards() {
426+ let world = World::new();
427+ world.push_elsewhere(&[("a", Some("1\n"))], "first");
428+ world.sync();
429+ let before = world.head();
430+ world.push_elsewhere(&[("a", Some("2\n"))], "second");
431+ let third = world.push_elsewhere(&[("b", Some("1\n"))], "third");
432+
433+ let report = world.sync();
434+ assert_eq!(report.outcome, SyncOutcome::FastForwarded);
435+ assert_eq!(report.imported, 2);
436+ assert_eq!(report.before, before);
437+ let changeset = world.map().changeset(&oid(&third)).unwrap();
438+ assert_eq!(report.after, Some(changeset));
439+ assert_eq!(world.head(), Some(changeset));
440+ assert_eq!(report.pushed, None);
441+ assert_eq!(world.remote_head(), Some(third));
442+
443+ world.assert_same_history();
444+ world.assert_forward_only();
445+ world.assert_sync_is_a_no_op();
446+}
447+
448+#[test]
449+fn diverged_with_disjoint_edits_merges_and_pushes() {
450+ let world = World::new();
451+ world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
452+ world.sync();
453+ let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
454+ let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git");
455+
456+ let report = world.sync();
457+ let SyncOutcome::Merged {
458+ merge,
459+ merged_paths,
460+ } = report.outcome.clone()
461+ else {
462+ panic!("expected a merge, got {:?}", report.outcome);
463+ };
464+ assert!(merged_paths.is_empty());
465+ assert_eq!(report.imported, 1);
466+ assert_eq!(report.before, Some(ours));
467+ assert_eq!(report.after, Some(merge));
468+ assert_eq!(world.head(), Some(merge));
469+ let theirs_changeset = world.map().changeset(&oid(&theirs)).unwrap();
470+ let merged = read_changeset(world.braid.store(), merge).unwrap();
471+ assert_eq!(merged.parents, [ours, theirs_changeset]);
472+ assert_eq!(report.operations.len(), 2, "the merge, then the push");
473+
474+ // The remote has both lines and the merge commit, a fast-forward from
475+ // what it had.
476+ let pushed = report.pushed.unwrap();
477+ assert_eq!(world.remote_head(), Some(pushed.to_hex()));
478+ let parents = git(&world.remote, &["rev-list", "--parents", "-n", "1", "main"]);
479+ let ours_commit = world.map().commit(&ours).unwrap();
480+ assert_eq!(parents, format!("{pushed} {ours_commit} {theirs}"));
481+ assert_eq!(world.remote_file("a"), "braid");
482+ assert_eq!(world.remote_file("b"), "git");
483+ let text = git(&world.remote, &["cat-file", "commit", "main"]);
484+ assert!(
485+ text.contains("\ncommitter tester <tester@example.org> "),
486+ "{text}"
487+ );
488+ assert!(
489+ text.ends_with(&format!("Merge {} into main", report.remote_ref)),
490+ "{text}"
491+ );
492+
493+ world.assert_same_history();
494+ world.assert_forward_only();
495+ world.assert_sync_is_a_no_op();
496+}
497+
498+#[test]
499+fn diverged_with_conflicting_edits_changes_nothing() {
500+ let world = World::new();
501+ world.push_elsewhere(&[("f", Some("1\n2\n3\n"))], "first");
502+ world.sync();
503+ let tracked = world.braid.store().refs().unwrap();
504+ let ours = world.commit_in_braid(&[("f", Some("1\nbraid\n3\n"))], "In braid\n");
505+ let theirs = world.push_elsewhere(&[("f", Some("1\ngit\n3\n"))], "In git");
506+ let operations = world.operations();
507+
508+ let report = world.sync();
509+ let SyncOutcome::Conflicts(conflicts) = &report.outcome else {
510+ panic!("expected conflicts, got {:?}", report.outcome);
511+ };
512+ assert!(!report.outcome.is_success());
513+ assert_eq!(conflicts.len(), 1);
514+ assert_eq!(conflicts[0].path, b"f");
515+ assert!(matches!(conflicts[0].kind, ConflictKind::Content { .. }));
516+ assert!(report.operations.is_empty());
517+ assert_eq!(report.after, Some(ours));
518+ assert_eq!(report.pushed, None);
519+
520+ // Nothing moved in braid, nothing was pushed.
521+ assert_eq!(world.operations(), operations);
522+ assert_eq!(world.head(), Some(ours));
523+ let refs = world.braid.store().refs().unwrap();
524+ assert_eq!(
525+ refs.get(&report.remote_ref),
526+ tracked.get(&report.remote_ref)
527+ );
528+ assert_eq!(refs.get(MAP_REF), tracked.get(MAP_REF));
529+ assert_eq!(world.remote_head(), Some(theirs));
530+ world.assert_forward_only();
531+
532+ // Again: the same conflicts, still nothing moved.
533+ let again = world.sync();
534+ assert_eq!(again.outcome, report.outcome);
535+ assert_eq!(world.operations(), operations);
536+}
537+
538+#[test]
539+fn a_lease_that_fails_changes_nothing_and_the_next_sync_converges() {
540+ let world = World::new();
541+ world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
542+ world.sync();
543+ let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
544+ let refs_before = world.braid.store().refs().unwrap();
545+ let operations = world.operations();
546+
547+ // Sync fetches and decides to push; then someone else pushes first.
548+ let options = world.options();
549+ let sync = world.steps(&options);
550+ let (lock, mirror) = sync.open_mirror().unwrap();
551+ let store = world.braid.store();
552+ let prepared = sync.prepare(store, &mirror).unwrap();
553+ let decision = sync.decide(store, &prepared).unwrap();
554+ assert!(matches!(decision, Decision::Push(id) if id == ours));
555+ let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git first");
556+ let report = sync.execute(&mirror, prepared, decision).unwrap();
557+ drop(lock);
558+
559+ assert_eq!(
560+ report.outcome,
561+ SyncOutcome::RemoteMoved {
562+ found: Some(oid(&theirs))
563+ }
564+ );
565+ assert!(!report.outcome.is_success());
566+ assert_eq!(report.pushed, None);
567+ assert!(report.operations.is_empty());
568+ // Nothing moved in braid: no ref, no operation.
569+ assert_eq!(
570+ world.braid.store().refs().unwrap().as_map(),
571+ refs_before.as_map()
572+ );
573+ assert_eq!(world.operations(), operations);
574+ assert_eq!(world.remote_head(), Some(theirs.clone()));
575+
576+ // The next sync takes the new commit in, merges, and pushes.
577+ let report = world.sync();
578+ assert!(
579+ matches!(report.outcome, SyncOutcome::Merged { .. }),
580+ "{:?}",
581+ report.outcome
582+ );
583+ assert_eq!(world.remote_file("a"), "braid");
584+ assert_eq!(world.remote_file("b"), "git");
585+ world.assert_same_history();
586+ world.assert_forward_only();
587+ world.assert_sync_is_a_no_op();
588+}
589+
590+#[test]
591+fn a_crash_after_the_push_loses_nothing() {
592+ let world = World::new();
593+ world.push_elsewhere(&[("a", Some("1\n"))], "first");
594+ world.sync();
595+ world.commit_in_braid(&[("a", Some("2\n"))], "One\n");
596+ let two = world.commit_in_braid(&[("b", Some("1\n"))], "Two\n");
597+
598+ // The steps of a sync up to the push, with a map that is never saved:
599+ // the process dies right after the push.
600+ let pushed = {
601+ let options = world.options();
602+ let sync = world.steps(&options);
603+ let (_lock, mirror) = sync.open_mirror().unwrap();
604+ let store = world.braid.store();
605+ let mut prepared = sync.prepare(store, &mirror).unwrap();
606+ let Decision::Push(target) = sync.decide(store, &prepared).unwrap() else {
607+ panic!("expected a push");
608+ };
609+ let commit = sync.export(&mirror, &mut prepared.map, target).unwrap();
610+ let expected = prepared.fetched.map(|(commit, _)| commit);
611+ assert!(sync.push(&mirror, commit, expected).unwrap().is_ok());
612+ commit
613+ };
614+ assert_eq!(world.remote_head(), Some(pushed.to_hex()));
615+ assert_eq!(
616+ world.map().changeset(&pushed),
617+ None,
618+ "the map was not saved"
619+ );
620+ let (operations, objects) = (world.operations(), world.objects());
621+
622+ // The next sync knows the remote's new commits as braid's own: nothing
623+ // is imported, and only the map is saved.
624+ let report = world.sync();
625+ assert_eq!(report.outcome, SyncOutcome::UpToDate);
626+ assert_eq!(report.imported, 0);
627+ assert_eq!(report.fetched.map(|(commit, _)| commit), Some(pushed));
628+ assert_eq!(report.after, Some(two));
629+ assert_eq!(report.operations.len(), 1);
630+ assert_eq!(world.operations(), operations + 1);
631+ assert_eq!(
632+ world.objects(),
633+ objects + 1,
634+ "the new map, and nothing else"
635+ );
636+ assert_eq!(world.map().changeset(&pushed), Some(two));
637+ let refs = world.braid.store().refs().unwrap();
638+ assert_eq!(refs.get(&report.remote_ref), Some(two));
639+
640+ world.assert_same_history();
641+ world.assert_forward_only();
642+ world.assert_sync_is_a_no_op();
643+}
644+
645+#[test]
646+fn a_remote_without_the_branch_gets_it() {
647+ let world = World::new();
648+ let first = world.commit_in_braid(&[("a", Some("1\n"))], "Root made in braid\n");
649+ let second = world.commit_in_braid(&[("b", Some("2\n"))], "Second\n");
650+
651+ let report = world.sync();
652+ assert_eq!(report.outcome, SyncOutcome::Pushed);
653+ assert_eq!(report.fetched, None);
654+ let pushed = report.pushed.unwrap();
655+ assert_eq!(world.remote_head(), Some(pushed.to_hex()));
656+ assert_eq!(world.map().commit(&second), Some(pushed));
657+ assert!(world.map().commit(&first).is_some());
658+ assert_eq!(git(&world.remote, &["rev-list", "--count", "main"]), "2");
659+
660+ world.assert_same_history();
661+ world.assert_forward_only();
662+ world.assert_sync_is_a_no_op();
663+}
664+
665+#[test]
666+fn nothing_to_sync() {
667+ let world = World::new();
668+ let result = world.sync_with(&world.options());
669+ assert!(
670+ matches!(&result, Err(Error::NothingToSync { branch }) if branch == "main"),
671+ "{result:?}"
672+ );
673+}
674+
675+#[test]
676+fn a_dry_run_writes_nothing() {
677+ let world = World::new();
678+ let dry = SyncOptions {
679+ dry_run: true,
680+ ..world.options()
681+ };
682+ world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
683+
684+ // Before any sync: not even a mirror.
685+ let report = world.sync_with(&dry).unwrap();
686+ assert!(report.dry_run);
687+ assert_eq!(report.outcome, SyncOutcome::Created);
688+ assert_eq!(world.head(), None);
689+ assert_eq!(world.operations(), 0);
690+ assert_eq!(world.objects(), 0);
691+ assert!(!world.root.join("braid/.braid/git").exists());
692+
693+ world.sync();
694+ let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
695+ let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git");
696+ let mirror_refs = |world: &World| {
697+ let mirror = world.root.join("braid/.braid/git").join(format!(
698+ "{}.git",
699+ Remote::new(world.remote_address()).unwrap().label()
700+ ));
701+ git(&mirror, &["for-each-ref"])
702+ };
703+ let refs = world.braid.store().refs().unwrap();
704+ let (operations, objects, mirrored) =
705+ (world.operations(), world.objects(), mirror_refs(&world));
706+
707+ let report = world.sync_with(&dry).unwrap();
708+ let SyncOutcome::Merged { merge, .. } = report.outcome else {
709+ panic!("expected a merge, got {:?}", report.outcome);
710+ };
711+ assert_eq!(report.imported, 1);
712+ assert!(report.pushed.is_some());
713+ assert!(report.operations.is_empty());
714+ assert_eq!(world.braid.store().refs().unwrap().as_map(), refs.as_map());
715+ assert_eq!(world.operations(), operations);
716+ assert_eq!(world.objects(), objects);
717+ assert!(!world.braid.store().contains(&merge).unwrap());
718+ assert_eq!(mirror_refs(&world), mirrored);
719+ assert_eq!(world.remote_head(), Some(theirs));
720+ assert_eq!(world.head(), Some(ours));
721+
722+ // The real sync does what the dry run said.
723+ let real = world.sync();
724+ assert!(matches!(real.outcome, SyncOutcome::Merged { .. }));
725+ world.assert_forward_only();
726+}
727+
728+#[test]
729+fn a_remote_branch_with_another_name() {
730+ let world = World::new();
731+ world.push_elsewhere(&[("a", Some("1\n"))], "first");
732+ git(&world.remote, &["branch", "-m", "main", "trunk"]);
733+ let options = SyncOptions {
734+ remote_branch: Some("trunk".to_owned()),
735+ ..world.options()
736+ };
737+ let report = world.sync_with(&options).unwrap();
738+ assert_eq!(report.outcome, SyncOutcome::Created);
739+ assert_eq!(report.remote_branch, "trunk");
740+ assert!(report.remote_ref.ends_with("/trunk"));
741+ world.commit_in_braid(&[("a", Some("2\n"))], "In braid\n");
742+ let report = world.sync_with(&options).unwrap();
743+ assert_eq!(report.outcome, SyncOutcome::Pushed);
744+ assert_eq!(
745+ git(&world.remote, &["rev-parse", "trunk"]),
746+ report.pushed.unwrap().to_hex()
747+ );
748+}
749+
750+#[test]
751+fn the_merge_committer_comes_from_the_configuration() {
752+ let world = World::new();
753+ world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
754+ world.sync();
755+ std::fs::write(
756+ world.root.join("braid/.braid/config"),
757+ "name = Braid\nemail = braid-bot@example.org\n",
758+ )
759+ .unwrap();
760+ world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
761+ world.push_elsewhere(&[("b", Some("git\n"))], "In git");
762+ let report = world.sync();
763+ assert!(matches!(report.outcome, SyncOutcome::Merged { .. }));
764+ let text = git(&world.remote, &["cat-file", "commit", "main"]);
765+ assert!(
766+ text.contains("\ncommitter tester <braid-bot@example.org> "),
767+ "{text}"
768+ );
769+}
770+
771+#[test]
772+fn names_sync_refuses() {
773+ let world = World::new();
774+ let options = world.options();
775+ let sync = |remote: &str, branch: &str, agent: &str| {
776+ world.braid.git_sync(remote, branch, agent, &options)
777+ };
778+ let remote = world.remote_address();
779+ for branch in [
780+ "remote/x/main",
781+ "braid/git-map",
782+ "tags/v1",
783+ "git/refs/heads/x",
784+ "",
785+ ] {
786+ assert!(
787+ matches!(
788+ sync(remote, branch, "tester"),
789+ Err(Error::InvalidBranch { .. })
790+ ),
791+ "{branch:?}"
792+ );
793+ }
794+ for branch in ["a..b", "a:b", "a b", "HEAD"] {
795+ assert!(
796+ matches!(
797+ sync(remote, branch, "tester"),
798+ Err(Error::InvalidBranch { .. })
799+ ),
800+ "{branch:?}"
801+ );
802+ }
803+ assert!(matches!(
804+ sync("--upload-pack=touch", "main", "tester"),
805+ Err(Error::InvalidRemote { .. })
806+ ));
807+ assert!(matches!(
808+ sync(remote, "main", "<bot>"),
809+ Err(Error::InvalidAgent { .. })
810+ ));
811+}
812+
813+#[test]
814+fn git_export_records_the_map() {
815+ let world = World::new();
816+ let first = world.commit_in_braid(&[("a", Some("1\n"))], "One\n");
817+ let second = world.commit_in_braid(&[("b", Some("1\n"))], "Two\n");
818+ let operations = world.operations();
819+ world.braid.git_export(&world.remote, &[]).unwrap();
820+ let map = world.map();
821+ let commit = map.commit(&second).unwrap();
822+ assert!(map.commit(&first).is_some());
823+ assert_eq!(world.remote_head(), Some(commit.to_hex()));
824+ let log = world.braid.store().log(1).unwrap();
825+ assert_eq!(world.operations(), operations + 1);
826+ assert_eq!(log[0].agent, crate::GIT_EXPORT_AGENT);
827+
828+ // Importing what was exported brings nothing new.
829+ let import = world.braid.git_import(&world.remote, "tester").unwrap();
830+ assert_eq!(import.report.commits, 0);
831+ assert_eq!(import.report.refs[0].braid, second);
832+ // Exporting again records nothing.
833+ world.braid.git_export(&world.remote, &[]).unwrap();
834+ assert_eq!(
835+ world.operations(),
836+ operations + 1 + usize::from(import.operation.is_some())
837+ );
838+}
839+
840+#[test]
841+fn saving_the_map_merges_what_another_process_saved() {
842+ let world = World::new();
843+ world.push_elsewhere(&[("a", Some("1\n"))], "first");
844+ world.sync();
845+ let repo = &world.braid;
846+ let base = repo.store().refs().unwrap().get(MAP_REF);
847+ let mut ours = repo.working_map(base).unwrap();
848+ let mut theirs = repo.working_map(base).unwrap();
849+ let ours_commit = world.commit_in_braid(&[("x", Some("1\n"))], "Ours\n");
850+ let theirs_commit = world.commit_in_braid(&[("y", Some("1\n"))], "Theirs\n");
851+ for (map, changeset) in [(&mut ours, ours_commit), (&mut theirs, theirs_commit)] {
852+ let mut exporter = braid_git::Exporter::new(repo.store(), &map.map);
853+ exporter.commit_id(&changeset).unwrap();
854+ let pairings = exporter.pairings();
855+ map.map.record(&pairings);
856+ }
857+ repo.save_with_map("a", "theirs", &mut theirs, &[]).unwrap();
858+ repo.save_with_map("b", "ours", &mut ours, &[]).unwrap();
859+ let saved = world.map();
860+ assert!(saved.commit(&ours_commit).is_some());
861+ assert!(saved.commit(&theirs_commit).is_some());
862+ assert_eq!(saved, ours.map);
863+}
864+
865+#[test]
866+#[should_panic(expected = "\"merge-base\", \"--is-ancestor\"")]
867+fn the_forward_check_catches_a_forced_update() {
868+ let world = World::new();
869+ let first = world.push_elsewhere(&[("a", Some("1\n"))], "first");
870+ world.push_elsewhere(&[("a", Some("2\n"))], "second");
871+ git(&world.remote, &["update-ref", "refs/heads/main", &first]);
872+ world.assert_forward_only();
873+}
874+
875+#[test]
876+fn history_rewritten_on_the_remote_is_merged_not_overwritten() {
877+ let world = World::new();
878+ let first = world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
879+ let second = world.push_elsewhere(&[("a", Some("2\n"))], "second");
880+ world.sync();
881+ let synced = world.head().unwrap();
882+ // Someone drops `second` from the remote and pushes something else.
883+ git(&world.work, &["checkout", "--quiet", "-B", "main", &first]);
884+ world.clock.set(world.clock.get() + 60);
885+ std::fs::write(world.work.join("b"), "rewritten\n").unwrap();
886+ git(&world.work, &["add", "b"]);
887+ git_at(
888+ &world.work,
889+ world.clock.get(),
890+ &["commit", "--quiet", "-m", "rewritten"],
891+ );
892+ git(
893+ &world.work,
894+ &["push", "--quiet", "--force", "origin", "main"],
895+ );
896+ let rewritten = world.remote_head().unwrap();
897+
898+ // Braid keeps what it had and merges: the remote fast-forwards from the
899+ // rewritten history and gets `second` back.
900+ let report = world.sync();
901+ let SyncOutcome::Merged { merge, .. } = report.outcome else {
902+ panic!("expected a merge, got {:?}", report.outcome);
903+ };
904+ assert_eq!(
905+ read_changeset(world.braid.store(), merge).unwrap().parents[0],
906+ synced
907+ );
908+ let pushed = report.pushed.unwrap().to_hex();
909+ git(
910+ &world.remote,
911+ &["merge-base", "--is-ancestor", &rewritten, &pushed],
912+ );
913+ git(
914+ &world.remote,
915+ &["merge-base", "--is-ancestor", &second, &pushed],
916+ );
917+ assert_eq!(world.remote_file("a"), "2");
918+ assert_eq!(world.remote_file("b"), "rewritten");
919+ world.assert_same_history();
920+ world.assert_sync_is_a_no_op();
921+}
922+
923+#[test]
924+fn an_unreachable_remote_is_an_error() {
925+ let world = World::new();
926+ world.commit_in_braid(&[("a", Some("1\n"))], "One\n");
927+ let operations = world.operations();
928+ let missing = world.root.join("nowhere.git");
929+ let result = world.braid.git_sync(
930+ missing.to_str().unwrap(),
931+ "main",
932+ "tester",
933+ &world.options(),
934+ );
935+ assert!(
936+ matches!(
937+ &result,
938+ Err(Error::GitCommand {
939+ command: "fetch",
940+ ..
941+ })
942+ ),
943+ "{result:?}"
944+ );
945+ assert_eq!(world.operations(), operations);
946+}
947+
948+#[test]
949+fn a_crash_between_the_merge_and_its_push_loses_nothing() {
950+ let world = World::new();
951+ world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
952+ world.sync();
953+ let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
954+ let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git");
955+
956+ // The braid branch moves to the merge, and the process dies before the
957+ // push.
958+ let merge = {
959+ let options = world.options();
960+ let sync = world.steps(&options);
961+ let (_lock, mirror) = sync.open_mirror().unwrap();
962+ let store = world.braid.store();
963+ let mut prepared = sync.prepare(store, &mirror).unwrap();
964+ let Decision::Merge { changeset, .. } = sync.decide(store, &prepared).unwrap() else {
965+ panic!("expected a merge");
966+ };
967+ sync.export(&mirror, &mut prepared.map, changeset).unwrap();
968+ let remote = prepared.fetched.map(|(_, changeset)| changeset);
969+ sync.save(
970+ "merge",
971+ &mut prepared.map,
972+ Some((Some(ours), changeset)),
973+ remote,
974+ )
975+ .unwrap();
976+ changeset
977+ };
978+ assert_eq!(world.head(), Some(merge));
979+ assert_eq!(world.remote_head(), Some(theirs));
980+
981+ // The next sync finds braid ahead, and pushes the merge.
982+ let report = world.sync();
983+ assert_eq!(report.outcome, SyncOutcome::Pushed);
984+ assert_eq!(report.imported, 0);
985+ assert_eq!(report.after, Some(merge));
986+ assert_eq!(world.map().commit(&merge), report.pushed);
987+ world.assert_same_history();
988+ world.assert_forward_only();
989+ world.assert_sync_is_a_no_op();
990+}
991+
992+#[test]
993+fn syncs_with_one_remote_take_turns() {
994+ let world = World::new();
995+ world.push_elsewhere(&[("a", Some("1\n"))], "first");
996+ world.sync();
997+ world.commit_in_braid(&[("a", Some("2\n"))], "In braid\n");
998+ let (repo, remote, options) = (&world.braid, world.remote_address(), world.options());
999+ let outcomes: Vec<SyncOutcome> = std::thread::scope(|scope| {
1000+ let runs: Vec<_> = (0..4)
1001+ .map(|_| scope.spawn(|| repo.git_sync(remote, "main", "tester", &options)))
1002+ .collect();
1003+ runs.into_iter()
1004+ .map(|run| run.join().unwrap().unwrap().outcome)
1005+ .collect()
1006+ });
1007+ let pushed = outcomes
1008+ .iter()
1009+ .filter(|outcome| **outcome == SyncOutcome::Pushed)
1010+ .count();
1011+ assert_eq!(pushed, 1, "{outcomes:?}");
1012+ assert!(
1013+ outcomes
1014+ .iter()
1015+ .all(|outcome| matches!(outcome, SyncOutcome::Pushed | SyncOutcome::UpToDate)),
1016+ "{outcomes:?}"
1017+ );
1018+ world.assert_same_history();
1019+ world.assert_forward_only();
1020+ world.assert_sync_is_a_no_op();
1021+}
modified docs/design.md +58 −0
@@ -154,10 +154,68 @@
154154 no code from git itself, which is GPLv2.
155155 - Import keeps the raw bytes of commits, tags and non-canonical trees, and
156156 verifies each commit by exporting it again and comparing ids.
157+- Export is deterministic. What it generates for changesets made in braid
158+ (their commits, trees and blobs) enters the git map, so importing those
159+ commits back, from wherever they went, gives the same changesets.
160+- Braid's refs keep to their own namespaces: `braid/` for its bookkeeping
161+ (the git map is `braid/git-map`), `tags/`, `git/` for other git refs, and
162+ `remote/<label>/<branch>` for where the branches of git remotes were last
163+ seen. A git branch named like one of them is imported under its full name,
164+ below `git/`.
157165 - Sync fetches and imports first, then pushes with a lease, as a fast-forward.
158166 Braid never force-pushes. The push itself runs the `git` binary as a
159167 subprocess, since gitoxide does not push yet.
160168
169+### Sync
170+
171+`braid git sync <remote> [--branch main] [--remote-branch <name>]` keeps a
172+braid branch and a branch of a git remote (GitHub, Gitea, a path) in step,
173+so that the git host stays the public face of a repository while agents land
174+in braid.
175+
176+- **Mirror.** Each remote has a bare mirror at `.braid/git/<label>.git`. The
177+ label is the last name of the remote's path without `.git`, with every
178+ character other than ASCII letters, digits, `.`, `_` and `-` turned into
179+ `-`, then a `-` and the first 12 hex digits of the BLAKE3 hash of the
180+ address without user name, password, trailing `/` or `.git`. So
181+ `https://example.org/team/project.git` is `project-` and a hash, and no
182+ credential ever reaches a file or ref name. In the mirror,
183+ `refs/remotes/origin/<branch>` is the remote branch as fetched and
184+ `refs/heads/<branch>` the braid branch as exported. `.braid/git/<label>.lock`
185+ makes syncs with one remote take turns.
186+- **Fetch and import.** The remote branch is fetched with an explicit refspec
187+ and no tags, then imported. The braid ref `remote/<label>/<branch>` records
188+ it.
189+- **Reconcile.** With B the braid branch and G the remote branch: if they are
190+ equal, there is nothing to do; without B, the braid branch is created at G;
191+ if B is an ancestor of G, braid fast-forwards; if G is an ancestor of B, or
192+ there is no G, B is pushed. Otherwise braid merges them with the engine's
193+ `merge`, which follows landing's rules and conflicts: a clean merge moves
194+ the braid branch to the merge, which is then pushed; conflicts move nothing
195+ and exit with status 2. The braid branch moves only with a compare and swap,
196+ in one operation with the git map and the remote's ref.
197+- **Push.** `git push --atomic --porcelain
198+ --force-with-lease=refs/heads/<branch>:<fetched> <remote>
199+ <commit>:refs/heads/<branch>`, where `<fetched>` is what the same sync
200+ fetched. What is pushed descends from it, so the remote only fast-forwards.
201+ If someone else pushed in between, the lease fails and braid records
202+ nothing more (after a merge, its branch is already at the merge); the next
203+ sync merges the new commits.
204+- **Crashes.** Each sync first records in the git map the commits of the
205+ braid branch's changesets, which exports make deterministically. After a
206+ crash between a push and its record, the commits that come back from the
207+ remote are recognised as the changesets they came from, and nothing is
208+ imported twice.
209+- **Git commands** run with the user's environment, so credentials and SSH
210+ settings work, minus the variables that would point git at another
211+ repository, and with hooks, automatic garbage collection and the `ext::`
212+ transport turned off.
213+- **Identity.** A merge made by sync is committed by the `--agent` label, with
214+ the `email` that `.braid/config` sets (`email = ...`), or else
215+ `<agent>@example.org`. Git's own configuration is never read for identity.
216+- **Dry run.** `--dry-run` fetches into a temporary repository that borrows
217+ the mirror's objects, keeps braid objects in memory, and writes nothing.
218+
161219 ## Server and caches
162220
163221 - HTTP, with immutable objects served by id so that a daemon, a regional cache,
modified docs/spec/format-v1.md +9 −0
@@ -286,6 +286,15 @@
286286 beyond ±99 hours, or an extra that cannot be a header has no git form and is
287287 refused.
288288
289+An export records what it generated in the map, in the same tables as an
290+import: the commit of each changeset, each canonical tree and each blob. An
291+import that meets one of those commits again, from wherever it went, takes the
292+changeset it was exported from instead of making a new one with a git origin.
293+The map stays one to one: a pairing whose commit or changeset (tree, blob) is
294+already mapped is not recorded, and a braid tree keeps the canonical git tree
295+it has. Since exports are deterministic, the pairings of any changeset can be
296+recomputed at any time and recorded again.
297+
289298 **Map record.** The mapping is one derived record, versioned on its own:
290299
291300 ```