Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 35.1 KiBRawPermalink
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
11use std::cell::Cell;
12use std::collections::HashSet;
13use std::ffi::OsString;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16
17use braid_engine::{ConflictKind, commit, read_changeset};
18use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
19use braid_git::{GitOid, export_commit};
20use braid_store::RefUpdate;
21use tempfile::TempDir;
22
23use super::*;
24use crate::Repo;
25
26/// The environment of every git command: no configuration but the
27/// repository's, fixed identities, never a prompt.
28fn 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.
45fn 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
77fn git(dir: &Path, args: &[&str]) -> String {
78 git_at(dir, EPOCH, args)
79}
80
81/// The first commit time; each commit adds a minute.
82const EPOCH: i64 = 1_700_000_000;
83
84/// A file to write, or `None` to delete it.
85type Edit<'a> = (&'a str, Option<&'a str>);
86
87/// A remote, a clone of it where others work, and a braid repository.
88struct World {
89 _dir: TempDir,
90 root: PathBuf,
91 remote: PathBuf,
92 work: PathBuf,
93 braid: Repo,
94 clock: Cell<i64>,
95}
96
97impl 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
328fn oid(text: &str) -> GitOid {
329 text.parse().unwrap()
330}
331
332#[test]
333fn 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]
378fn 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]
425fn 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]
449fn 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 // The merge names the agent that made it.
473 assert_eq!(
474 merged.extras,
475 [(braid_engine::AGENT.to_vec(), b"tester".to_vec())]
476 );
477 assert_eq!(report.operations.len(), 2, "the merge, then the push");
478
479 // The remote has both lines and the merge commit, a fast-forward from
480 // what it had.
481 let pushed = report.pushed.unwrap();
482 assert_eq!(world.remote_head(), Some(pushed.to_hex()));
483 let parents = git(&world.remote, &["rev-list", "--parents", "-n", "1", "main"]);
484 let ours_commit = world.map().commit(&ours).unwrap();
485 assert_eq!(parents, format!("{pushed} {ours_commit} {theirs}"));
486 assert_eq!(world.remote_file("a"), "braid");
487 assert_eq!(world.remote_file("b"), "git");
488 let text = git(&world.remote, &["cat-file", "commit", "main"]);
489 assert!(
490 text.contains("\ncommitter tester <tester@example.org> "),
491 "{text}"
492 );
493 assert!(text.contains("\nagent tester\n"), "{text}");
494 assert!(
495 text.ends_with(&format!("Merge {} into main", report.remote_ref)),
496 "{text}"
497 );
498
499 world.assert_same_history();
500 world.assert_forward_only();
501 world.assert_sync_is_a_no_op();
502}
503
504#[test]
505fn diverged_with_conflicting_edits_changes_nothing() {
506 let world = World::new();
507 world.push_elsewhere(&[("f", Some("1\n2\n3\n"))], "first");
508 world.sync();
509 let tracked = world.braid.store().refs().unwrap();
510 let ours = world.commit_in_braid(&[("f", Some("1\nbraid\n3\n"))], "In braid\n");
511 let theirs = world.push_elsewhere(&[("f", Some("1\ngit\n3\n"))], "In git");
512 let operations = world.operations();
513
514 let report = world.sync();
515 let SyncOutcome::Conflicts(conflicts) = &report.outcome else {
516 panic!("expected conflicts, got {:?}", report.outcome);
517 };
518 assert!(!report.outcome.is_success());
519 assert_eq!(conflicts.len(), 1);
520 assert_eq!(conflicts[0].path, b"f");
521 assert!(matches!(conflicts[0].kind, ConflictKind::Content { .. }));
522 assert!(report.operations.is_empty());
523 assert_eq!(report.after, Some(ours));
524 assert_eq!(report.pushed, None);
525
526 // Nothing moved in braid, nothing was pushed.
527 assert_eq!(world.operations(), operations);
528 assert_eq!(world.head(), Some(ours));
529 let refs = world.braid.store().refs().unwrap();
530 assert_eq!(
531 refs.get(&report.remote_ref),
532 tracked.get(&report.remote_ref)
533 );
534 assert_eq!(refs.get(MAP_REF), tracked.get(MAP_REF));
535 assert_eq!(world.remote_head(), Some(theirs));
536 world.assert_forward_only();
537
538 // Again: the same conflicts, still nothing moved.
539 let again = world.sync();
540 assert_eq!(again.outcome, report.outcome);
541 assert_eq!(world.operations(), operations);
542}
543
544#[test]
545fn a_lease_that_fails_changes_nothing_and_the_next_sync_converges() {
546 let world = World::new();
547 world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
548 world.sync();
549 let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
550 let refs_before = world.braid.store().refs().unwrap();
551 let operations = world.operations();
552
553 // Sync fetches and decides to push; then someone else pushes first.
554 let options = world.options();
555 let sync = world.steps(&options);
556 let (lock, mirror) = sync.open_mirror().unwrap();
557 let store = world.braid.store();
558 let prepared = sync.prepare(store, &mirror).unwrap();
559 let decision = sync.decide(store, &prepared).unwrap();
560 assert!(matches!(decision, Decision::Push(id) if id == ours));
561 let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git first");
562 let report = sync.execute(&mirror, prepared, decision).unwrap();
563 drop(lock);
564
565 assert_eq!(
566 report.outcome,
567 SyncOutcome::RemoteMoved {
568 found: Some(oid(&theirs))
569 }
570 );
571 assert!(!report.outcome.is_success());
572 assert_eq!(report.pushed, None);
573 assert!(report.operations.is_empty());
574 // Nothing moved in braid: no ref, no operation.
575 assert_eq!(
576 world.braid.store().refs().unwrap().as_map(),
577 refs_before.as_map()
578 );
579 assert_eq!(world.operations(), operations);
580 assert_eq!(world.remote_head(), Some(theirs.clone()));
581
582 // The next sync takes the new commit in, merges, and pushes.
583 let report = world.sync();
584 assert!(
585 matches!(report.outcome, SyncOutcome::Merged { .. }),
586 "{:?}",
587 report.outcome
588 );
589 assert_eq!(world.remote_file("a"), "braid");
590 assert_eq!(world.remote_file("b"), "git");
591 world.assert_same_history();
592 world.assert_forward_only();
593 world.assert_sync_is_a_no_op();
594}
595
596#[test]
597fn a_crash_after_the_push_loses_nothing() {
598 let world = World::new();
599 world.push_elsewhere(&[("a", Some("1\n"))], "first");
600 world.sync();
601 world.commit_in_braid(&[("a", Some("2\n"))], "One\n");
602 let two = world.commit_in_braid(&[("b", Some("1\n"))], "Two\n");
603
604 // The steps of a sync up to the push, with a map that is never saved:
605 // the process dies right after the push.
606 let pushed = {
607 let options = world.options();
608 let sync = world.steps(&options);
609 let (_lock, mirror) = sync.open_mirror().unwrap();
610 let store = world.braid.store();
611 let mut prepared = sync.prepare(store, &mirror).unwrap();
612 let Decision::Push(target) = sync.decide(store, &prepared).unwrap() else {
613 panic!("expected a push");
614 };
615 let commit = sync.export(&mirror, &mut prepared.map, target).unwrap();
616 let expected = prepared.fetched.map(|(commit, _)| commit);
617 assert!(sync.push(&mirror, commit, expected).unwrap().is_ok());
618 commit
619 };
620 assert_eq!(world.remote_head(), Some(pushed.to_hex()));
621 assert_eq!(
622 world.map().changeset(&pushed),
623 None,
624 "the map was not saved"
625 );
626 let (operations, objects) = (world.operations(), world.objects());
627
628 // The next sync knows the remote's new commits as braid's own: nothing
629 // is imported, and only the map is saved.
630 let report = world.sync();
631 assert_eq!(report.outcome, SyncOutcome::UpToDate);
632 assert_eq!(report.imported, 0);
633 assert_eq!(report.fetched.map(|(commit, _)| commit), Some(pushed));
634 assert_eq!(report.after, Some(two));
635 assert_eq!(report.operations.len(), 1);
636 assert_eq!(world.operations(), operations + 1);
637 assert_eq!(
638 world.objects(),
639 objects + 1,
640 "the new map, and nothing else"
641 );
642 assert_eq!(world.map().changeset(&pushed), Some(two));
643 let refs = world.braid.store().refs().unwrap();
644 assert_eq!(refs.get(&report.remote_ref), Some(two));
645
646 world.assert_same_history();
647 world.assert_forward_only();
648 world.assert_sync_is_a_no_op();
649}
650
651#[test]
652fn a_remote_without_the_branch_gets_it() {
653 let world = World::new();
654 let first = world.commit_in_braid(&[("a", Some("1\n"))], "Root made in braid\n");
655 let second = world.commit_in_braid(&[("b", Some("2\n"))], "Second\n");
656
657 let report = world.sync();
658 assert_eq!(report.outcome, SyncOutcome::Pushed);
659 assert_eq!(report.fetched, None);
660 let pushed = report.pushed.unwrap();
661 assert_eq!(world.remote_head(), Some(pushed.to_hex()));
662 assert_eq!(world.map().commit(&second), Some(pushed));
663 assert!(world.map().commit(&first).is_some());
664 assert_eq!(git(&world.remote, &["rev-list", "--count", "main"]), "2");
665
666 world.assert_same_history();
667 world.assert_forward_only();
668 world.assert_sync_is_a_no_op();
669}
670
671#[test]
672fn nothing_to_sync() {
673 let world = World::new();
674 let result = world.sync_with(&world.options());
675 assert!(
676 matches!(&result, Err(Error::NothingToSync { branch }) if branch == "main"),
677 "{result:?}"
678 );
679}
680
681#[test]
682fn a_dry_run_writes_nothing() {
683 let world = World::new();
684 let dry = SyncOptions {
685 dry_run: true,
686 ..world.options()
687 };
688 world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
689
690 // Before any sync: not even a mirror.
691 let report = world.sync_with(&dry).unwrap();
692 assert!(report.dry_run);
693 assert_eq!(report.outcome, SyncOutcome::Created);
694 assert_eq!(world.head(), None);
695 assert_eq!(world.operations(), 0);
696 assert_eq!(world.objects(), 0);
697 assert!(!world.root.join("braid/.braid/git").exists());
698
699 world.sync();
700 let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
701 let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git");
702 let mirror_refs = |world: &World| {
703 let mirror = world.root.join("braid/.braid/git").join(format!(
704 "{}.git",
705 Remote::new(world.remote_address()).unwrap().label()
706 ));
707 git(&mirror, &["for-each-ref"])
708 };
709 let refs = world.braid.store().refs().unwrap();
710 let (operations, objects, mirrored) =
711 (world.operations(), world.objects(), mirror_refs(&world));
712
713 let report = world.sync_with(&dry).unwrap();
714 let SyncOutcome::Merged { merge, .. } = report.outcome else {
715 panic!("expected a merge, got {:?}", report.outcome);
716 };
717 assert_eq!(report.imported, 1);
718 assert!(report.pushed.is_some());
719 assert!(report.operations.is_empty());
720 assert_eq!(world.braid.store().refs().unwrap().as_map(), refs.as_map());
721 assert_eq!(world.operations(), operations);
722 assert_eq!(world.objects(), objects);
723 assert!(!world.braid.store().contains(&merge).unwrap());
724 assert_eq!(mirror_refs(&world), mirrored);
725 assert_eq!(world.remote_head(), Some(theirs));
726 assert_eq!(world.head(), Some(ours));
727
728 // The real sync does what the dry run said.
729 let real = world.sync();
730 assert!(matches!(real.outcome, SyncOutcome::Merged { .. }));
731 world.assert_forward_only();
732}
733
734#[test]
735fn a_remote_branch_with_another_name() {
736 let world = World::new();
737 world.push_elsewhere(&[("a", Some("1\n"))], "first");
738 git(&world.remote, &["branch", "-m", "main", "trunk"]);
739 let options = SyncOptions {
740 remote_branch: Some("trunk".to_owned()),
741 ..world.options()
742 };
743 let report = world.sync_with(&options).unwrap();
744 assert_eq!(report.outcome, SyncOutcome::Created);
745 assert_eq!(report.remote_branch, "trunk");
746 assert!(report.remote_ref.ends_with("/trunk"));
747 world.commit_in_braid(&[("a", Some("2\n"))], "In braid\n");
748 let report = world.sync_with(&options).unwrap();
749 assert_eq!(report.outcome, SyncOutcome::Pushed);
750 assert_eq!(
751 git(&world.remote, &["rev-parse", "trunk"]),
752 report.pushed.unwrap().to_hex()
753 );
754}
755
756#[test]
757fn the_merge_committer_comes_from_the_configuration() {
758 let world = World::new();
759 world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
760 world.sync();
761 std::fs::write(
762 world.root.join("braid/.braid/config"),
763 "name = Braid\nemail = braid-bot@example.org\n",
764 )
765 .unwrap();
766 world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
767 world.push_elsewhere(&[("b", Some("git\n"))], "In git");
768 let report = world.sync();
769 assert!(matches!(report.outcome, SyncOutcome::Merged { .. }));
770 let text = git(&world.remote, &["cat-file", "commit", "main"]);
771 assert!(
772 text.contains("\ncommitter tester <braid-bot@example.org> "),
773 "{text}"
774 );
775}
776
777#[test]
778fn names_sync_refuses() {
779 let world = World::new();
780 let options = world.options();
781 let sync = |remote: &str, branch: &str, agent: &str| {
782 world.braid.git_sync(remote, branch, agent, &options)
783 };
784 let remote = world.remote_address();
785 for branch in [
786 "remote/x/main",
787 "braid/git-map",
788 "tags/v1",
789 "git/refs/heads/x",
790 "",
791 ] {
792 assert!(
793 matches!(
794 sync(remote, branch, "tester"),
795 Err(Error::InvalidBranch { .. })
796 ),
797 "{branch:?}"
798 );
799 }
800 for branch in ["a..b", "a:b", "a b", "HEAD"] {
801 assert!(
802 matches!(
803 sync(remote, branch, "tester"),
804 Err(Error::InvalidBranch { .. })
805 ),
806 "{branch:?}"
807 );
808 }
809 assert!(matches!(
810 sync("--upload-pack=touch", "main", "tester"),
811 Err(Error::InvalidRemote { .. })
812 ));
813 assert!(matches!(
814 sync(remote, "main", "<bot>"),
815 Err(Error::InvalidAgent { .. })
816 ));
817}
818
819#[test]
820fn git_export_records_the_map() {
821 let world = World::new();
822 let first = world.commit_in_braid(&[("a", Some("1\n"))], "One\n");
823 let second = world.commit_in_braid(&[("b", Some("1\n"))], "Two\n");
824 let operations = world.operations();
825 world.braid.git_export(&world.remote, &[]).unwrap();
826 let map = world.map();
827 let commit = map.commit(&second).unwrap();
828 assert!(map.commit(&first).is_some());
829 assert_eq!(world.remote_head(), Some(commit.to_hex()));
830 let log = world.braid.store().log(1).unwrap();
831 assert_eq!(world.operations(), operations + 1);
832 assert_eq!(log[0].agent, crate::GIT_EXPORT_AGENT);
833
834 // Importing what was exported brings nothing new.
835 let import = world.braid.git_import(&world.remote, "tester").unwrap();
836 assert_eq!(import.report.commits, 0);
837 assert_eq!(import.report.refs[0].braid, second);
838 // Exporting again records nothing.
839 world.braid.git_export(&world.remote, &[]).unwrap();
840 assert_eq!(
841 world.operations(),
842 operations + 1 + usize::from(import.operation.is_some())
843 );
844}
845
846#[test]
847fn saving_the_map_merges_what_another_process_saved() {
848 let world = World::new();
849 world.push_elsewhere(&[("a", Some("1\n"))], "first");
850 world.sync();
851 let repo = &world.braid;
852 let base = repo.store().refs().unwrap().get(MAP_REF);
853 let mut ours = repo.working_map(base).unwrap();
854 let mut theirs = repo.working_map(base).unwrap();
855 let ours_commit = world.commit_in_braid(&[("x", Some("1\n"))], "Ours\n");
856 let theirs_commit = world.commit_in_braid(&[("y", Some("1\n"))], "Theirs\n");
857 for (map, changeset) in [(&mut ours, ours_commit), (&mut theirs, theirs_commit)] {
858 let mut exporter = braid_git::Exporter::new(repo.store(), &map.map);
859 exporter.commit_id(&changeset).unwrap();
860 let pairings = exporter.pairings();
861 map.map.record(&pairings);
862 }
863 repo.save_with_map("a", "theirs", &mut theirs, &[]).unwrap();
864 repo.save_with_map("b", "ours", &mut ours, &[]).unwrap();
865 let saved = world.map();
866 assert!(saved.commit(&ours_commit).is_some());
867 assert!(saved.commit(&theirs_commit).is_some());
868 assert_eq!(saved, ours.map);
869}
870
871#[test]
872#[should_panic(expected = "\"merge-base\", \"--is-ancestor\"")]
873fn the_forward_check_catches_a_forced_update() {
874 let world = World::new();
875 let first = world.push_elsewhere(&[("a", Some("1\n"))], "first");
876 world.push_elsewhere(&[("a", Some("2\n"))], "second");
877 git(&world.remote, &["update-ref", "refs/heads/main", &first]);
878 world.assert_forward_only();
879}
880
881#[test]
882fn history_rewritten_on_the_remote_is_merged_not_overwritten() {
883 let world = World::new();
884 let first = world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
885 let second = world.push_elsewhere(&[("a", Some("2\n"))], "second");
886 world.sync();
887 let synced = world.head().unwrap();
888 // Someone drops `second` from the remote and pushes something else.
889 git(&world.work, &["checkout", "--quiet", "-B", "main", &first]);
890 world.clock.set(world.clock.get() + 60);
891 std::fs::write(world.work.join("b"), "rewritten\n").unwrap();
892 git(&world.work, &["add", "b"]);
893 git_at(
894 &world.work,
895 world.clock.get(),
896 &["commit", "--quiet", "-m", "rewritten"],
897 );
898 git(
899 &world.work,
900 &["push", "--quiet", "--force", "origin", "main"],
901 );
902 let rewritten = world.remote_head().unwrap();
903
904 // Braid keeps what it had and merges: the remote fast-forwards from the
905 // rewritten history and gets `second` back.
906 let report = world.sync();
907 let SyncOutcome::Merged { merge, .. } = report.outcome else {
908 panic!("expected a merge, got {:?}", report.outcome);
909 };
910 assert_eq!(
911 read_changeset(world.braid.store(), merge).unwrap().parents[0],
912 synced
913 );
914 let pushed = report.pushed.unwrap().to_hex();
915 git(
916 &world.remote,
917 &["merge-base", "--is-ancestor", &rewritten, &pushed],
918 );
919 git(
920 &world.remote,
921 &["merge-base", "--is-ancestor", &second, &pushed],
922 );
923 assert_eq!(world.remote_file("a"), "2");
924 assert_eq!(world.remote_file("b"), "rewritten");
925 world.assert_same_history();
926 world.assert_sync_is_a_no_op();
927}
928
929#[test]
930fn an_unreachable_remote_is_an_error() {
931 let world = World::new();
932 world.commit_in_braid(&[("a", Some("1\n"))], "One\n");
933 let operations = world.operations();
934 let missing = world.root.join("nowhere.git");
935 let result = world.braid.git_sync(
936 missing.to_str().unwrap(),
937 "main",
938 "tester",
939 &world.options(),
940 );
941 assert!(
942 matches!(
943 &result,
944 Err(Error::GitCommand {
945 command: "fetch",
946 ..
947 })
948 ),
949 "{result:?}"
950 );
951 assert_eq!(world.operations(), operations);
952}
953
954#[test]
955fn a_crash_between_the_merge_and_its_push_loses_nothing() {
956 let world = World::new();
957 world.push_elsewhere(&[("a", Some("1\n")), ("b", Some("1\n"))], "first");
958 world.sync();
959 let ours = world.commit_in_braid(&[("a", Some("braid\n"))], "In braid\n");
960 let theirs = world.push_elsewhere(&[("b", Some("git\n"))], "In git");
961
962 // The braid branch moves to the merge, and the process dies before the
963 // push.
964 let merge = {
965 let options = world.options();
966 let sync = world.steps(&options);
967 let (_lock, mirror) = sync.open_mirror().unwrap();
968 let store = world.braid.store();
969 let mut prepared = sync.prepare(store, &mirror).unwrap();
970 let Decision::Merge { changeset, .. } = sync.decide(store, &prepared).unwrap() else {
971 panic!("expected a merge");
972 };
973 sync.export(&mirror, &mut prepared.map, changeset).unwrap();
974 let remote = prepared.fetched.map(|(_, changeset)| changeset);
975 sync.save(
976 "merge",
977 &mut prepared.map,
978 Some((Some(ours), changeset)),
979 remote,
980 )
981 .unwrap();
982 changeset
983 };
984 assert_eq!(world.head(), Some(merge));
985 assert_eq!(world.remote_head(), Some(theirs));
986
987 // The next sync finds braid ahead, and pushes the merge.
988 let report = world.sync();
989 assert_eq!(report.outcome, SyncOutcome::Pushed);
990 assert_eq!(report.imported, 0);
991 assert_eq!(report.after, Some(merge));
992 assert_eq!(world.map().commit(&merge), report.pushed);
993 world.assert_same_history();
994 world.assert_forward_only();
995 world.assert_sync_is_a_no_op();
996}
997
998#[test]
999fn syncs_with_one_remote_take_turns() {
1000 let world = World::new();
1001 world.push_elsewhere(&[("a", Some("1\n"))], "first");
1002 world.sync();
1003 world.commit_in_braid(&[("a", Some("2\n"))], "In braid\n");
1004 let (repo, remote, options) = (&world.braid, world.remote_address(), world.options());
1005 let outcomes: Vec<SyncOutcome> = std::thread::scope(|scope| {
1006 let runs: Vec<_> = (0..4)
1007 .map(|_| scope.spawn(|| repo.git_sync(remote, "main", "tester", &options)))
1008 .collect();
1009 runs.into_iter()
1010 .map(|run| run.join().unwrap().unwrap().outcome)
1011 .collect()
1012 });
1013 let pushed = outcomes
1014 .iter()
1015 .filter(|outcome| **outcome == SyncOutcome::Pushed)
1016 .count();
1017 assert_eq!(pushed, 1, "{outcomes:?}");
1018 assert!(
1019 outcomes
1020 .iter()
1021 .all(|outcome| matches!(outcome, SyncOutcome::Pushed | SyncOutcome::UpToDate)),
1022 "{outcomes:?}"
1023 );
1024 world.assert_same_history();
1025 world.assert_forward_only();
1026 world.assert_sync_is_a_no_op();
1027}