Elffuss BraidHub

utopia-ia/elffuss-braid public

356f55034aff · 31.9 KiBRawPermalink
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
8use std::ffi::OsString;
9use std::fs::{self, File, OpenOptions};
10use std::path::{Path, PathBuf};
11
12use braid_engine::{AGENT, Conflict, MergeOutcome, is_ancestor, merge};
13use braid_format::{Kind, MemoryObjects, ObjectId, Objects, Signature};
14use braid_git::{Exporter, GitKind, GitOid, ImportOptions, RefTarget};
15use braid_store::{Operation, Store};
16
17use crate::git::{MAP_REF, Move, RESERVED, WorkingMap, remote_ref};
18use crate::remote::{Fetched, Git, Pushed, Remote, Scratch};
19use crate::{DIR, Error, Repo};
20
21/// The directory inside [`DIR`] that holds the mirrors of git remotes.
22pub const MIRRORS_DIR: &str = "git";
23
24/// What [`Repo::git_sync`] does besides its defaults.
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
26pub struct SyncOptions {
27 /// The branch of the remote, when its name differs from the braid
28 /// branch's.
29 pub remote_branch: Option<String>,
30 /// Find out what the sync would do, and write nothing: no braid object,
31 /// ref or operation, no mirror, no push. The remote branch is fetched
32 /// into a temporary repository, removed afterwards.
33 pub dry_run: bool,
34 /// Environment variables to set for the git commands, on top of the
35 /// process's own.
36 pub git_env: Vec<(OsString, OsString)>,
37 /// Which way changes may go.
38 pub direction: SyncDirection,
39}
40
41/// Which way a sync may move changes.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum SyncDirection {
44 /// Both ways: the braid branch takes what the remote has, the remote
45 /// takes what braid has, and when both moved they are merged and the
46 /// merge is pushed. Writes made to the remote by anyone else end up in
47 /// braid.
48 #[default]
49 Both,
50 /// Braid to the remote only: the remote branch must be the braid branch
51 /// or one of its ancestors, or absent. Anything else is
52 /// [`SyncOutcome::Diverged`], and nothing is recorded, merged or pushed.
53 Publish,
54 /// The remote to braid only: the braid branch must be the remote branch
55 /// or one of its ancestors, or absent. Anything else, a remote that went
56 /// back included, is [`SyncOutcome::Diverged`], and nothing is recorded
57 /// or pushed.
58 Follow,
59}
60
61impl SyncDirection {
62 /// The name used on the command line and in reports: `both`, `publish`
63 /// or `follow`.
64 pub fn code(self) -> &'static str {
65 match self {
66 SyncDirection::Both => "both",
67 SyncDirection::Publish => "publish",
68 SyncDirection::Follow => "follow",
69 }
70 }
71}
72
73/// What a sync did, or would do.
74#[derive(Clone, Debug, PartialEq, Eq)]
75#[non_exhaustive]
76pub enum SyncOutcome {
77 /// The braid branch and the remote branch were at the same changeset.
78 UpToDate,
79 /// The braid branch did not exist; it was created at the remote's head.
80 Created,
81 /// The remote was ahead: the braid branch fast-forwarded to it.
82 FastForwarded,
83 /// Braid was ahead, or the remote had no such branch: the remote
84 /// fast-forwarded to the braid branch, or the branch was created there.
85 Pushed,
86 /// Both had moved: braid merged them, moved its branch to the merge, and
87 /// the remote fast-forwarded to it.
88 Merged {
89 /// The merge changeset.
90 merge: ObjectId,
91 /// The paths both sides changed, merged line by line or by kind.
92 merged_paths: Vec<Vec<u8>>,
93 },
94 /// Both had moved, and the changes conflict. Nothing moved, and nothing
95 /// was pushed.
96 Conflicts(Vec<Conflict>),
97 /// The push was refused because the remote branch moved after the fetch.
98 /// Braid changed nothing, except that its branch is at the merge when
99 /// one was made; the next sync takes the new commits in.
100 RemoteMoved {
101 /// Where the remote branch was found after the push failed.
102 found: Option<GitOid>,
103 },
104 /// The remote refused the push for another reason, such as a protected
105 /// branch. Braid changed nothing, except that its branch is at the merge
106 /// when one was made.
107 Rejected {
108 /// Git's reason.
109 reason: String,
110 },
111 /// The branches are not in the relation the [`SyncDirection`] requires.
112 /// Nothing was recorded, merged or pushed.
113 Diverged {
114 /// What was found.
115 reason: String,
116 },
117}
118
119impl SyncOutcome {
120 /// A short, stable name for the outcome, for reports and JSON:
121 /// `up_to_date`, `created`, `fast_forwarded`, `pushed`, `merged`,
122 /// `conflicts`, `remote_moved`, `rejected` or `diverged`.
123 pub fn code(&self) -> &'static str {
124 match self {
125 SyncOutcome::UpToDate => "up_to_date",
126 SyncOutcome::Created => "created",
127 SyncOutcome::FastForwarded => "fast_forwarded",
128 SyncOutcome::Pushed => "pushed",
129 SyncOutcome::Merged { .. } => "merged",
130 SyncOutcome::Conflicts(_) => "conflicts",
131 SyncOutcome::RemoteMoved { .. } => "remote_moved",
132 SyncOutcome::Rejected { .. } => "rejected",
133 SyncOutcome::Diverged { .. } => "diverged",
134 }
135 }
136
137 /// Whether the two branches are in step at the end: every outcome but
138 /// conflicts, refused pushes and divergence.
139 pub fn is_success(&self) -> bool {
140 !matches!(
141 self,
142 SyncOutcome::Conflicts(_)
143 | SyncOutcome::RemoteMoved { .. }
144 | SyncOutcome::Rejected { .. }
145 | SyncOutcome::Diverged { .. }
146 )
147 }
148}
149
150/// What [`Repo::git_sync`] did, or with a dry run, would do.
151#[derive(Clone, Debug, PartialEq, Eq)]
152pub struct SyncReport {
153 /// The remote's label, which names its mirror and its braid ref.
154 pub label: String,
155 /// The braid branch.
156 pub branch: String,
157 /// The branch of the remote.
158 pub remote_branch: String,
159 /// The braid ref that records where the remote branch was last seen.
160 pub remote_ref: String,
161 /// What happened.
162 pub outcome: SyncOutcome,
163 /// The braid branch before the sync.
164 pub before: Option<ObjectId>,
165 /// The braid branch after it.
166 pub after: Option<ObjectId>,
167 /// The remote branch as fetched, its commit and its changeset, or `None`
168 /// when the remote has no such branch.
169 pub fetched: Option<(GitOid, ObjectId)>,
170 /// The commit pushed to the remote branch, or with a dry run, the commit
171 /// that would be.
172 pub pushed: Option<GitOid>,
173 /// How many commits were imported from the remote.
174 pub imported: usize,
175 /// Whether this was a dry run, which writes nothing.
176 pub dry_run: bool,
177 /// The operations recorded in the op log, oldest first.
178 pub operations: Vec<Operation>,
179}
180
181/// What the branches call for, once the remote branch is imported.
182enum Decision {
183 UpToDate,
184 Create(ObjectId),
185 FastForward(ObjectId),
186 Push(ObjectId),
187 Merge {
188 changeset: ObjectId,
189 merged_paths: Vec<Vec<u8>>,
190 },
191 Conflicts(Vec<Conflict>),
192 Diverged(String),
193}
194
195/// The state after fetching and importing.
196struct Prepared {
197 map: WorkingMap,
198 head: Option<ObjectId>,
199 fetched: Option<(GitOid, ObjectId)>,
200 imported: usize,
201}
202
203/// A push that did not go through.
204enum Refused {
205 RemoteMoved(Option<GitOid>),
206 Rejected(String),
207}
208
209impl Refused {
210 fn outcome(self) -> SyncOutcome {
211 match self {
212 Refused::RemoteMoved(found) => SyncOutcome::RemoteMoved { found },
213 Refused::Rejected(reason) => SyncOutcome::Rejected { reason },
214 }
215 }
216}
217
218impl Repo {
219 /// Keeps the braid branch `branch` and a branch of the git remote
220 /// `remote` in step: fetches and imports the remote branch, then
221 /// fast-forwards the braid branch, or pushes it (merging first when both
222 /// moved) as a fast-forward with a lease, so that the remote's history is
223 /// never rewritten. Operations are recorded by `agent`, who is also the
224 /// committer of a merge, with the `email` of the repository's
225 /// [`Config`](crate::Config) or `<agent>@example.org`, and whom the
226 /// merge's [`AGENT`] field names.
227 ///
228 /// # The mirror
229 ///
230 /// Braid keeps a bare git repository per remote, its mirror, at
231 /// `.braid/git/<label>.git`, where `<label>` is the remote's label (see
232 /// [`Remote::new`](crate::Remote::new)). In it,
233 /// `refs/remotes/origin/<branch>` is the remote branch as last fetched,
234 /// and `refs/heads/<branch>` the braid branch as last exported.
235 /// `.braid/git/<label>.lock` is held while a sync with that remote runs,
236 /// so syncs with one remote take turns.
237 ///
238 /// # Steps
239 ///
240 /// 1. The commits of the changesets on the braid branch are computed
241 /// (exports are deterministic) and recorded in the git map, so that
242 /// their copies on the remote import as the same changesets.
243 /// 2. The remote branch is fetched into the mirror, with an explicit
244 /// refspec and no tags, and imported. Its changeset G is recorded in
245 /// the braid ref `remote/<label>/<branch>` (see [`remote_ref`]).
246 /// 3. With B the head of the braid branch:
247 /// - B is G: nothing to do;
248 /// - there is no B: the braid branch is created at G;
249 /// - B is an ancestor of G: the braid branch fast-forwards to G;
250 /// - G is an ancestor of B, or the remote has no such branch: B is
251 /// exported into the mirror and pushed;
252 /// - otherwise the two are merged (see [`braid_engine::merge`]). A
253 /// clean merge M moves the braid branch from B to M, and M is
254 /// exported and pushed. Conflicts change nothing and are reported.
255 ///
256 /// The braid branch only ever moves with a compare and swap, in one
257 /// operation with the git map and `remote/<label>/<branch>`.
258 ///
259 /// [`SyncOptions::direction`] restricts this. With
260 /// [`SyncDirection::Publish`] only the first and the fourth case go
261 /// ahead (and creating the remote branch); with
262 /// [`SyncDirection::Follow`] only the first three. Any other case is
263 /// [`SyncOutcome::Diverged`]: no merge is made, and no ref, map entry
264 /// or remote branch moves. The objects of the fetched commits may stay
265 /// in the store, which only appends.
266 /// 4. A push is atomic and leased: `git push --atomic --porcelain
267 /// --force-with-lease=refs/heads/<branch>:<fetched> <remote>
268 /// <commit>:refs/heads/<branch>`, where `<fetched>` is G's commit as
269 /// this same sync fetched it, or nothing when the remote had no such
270 /// branch. What is pushed descends from G, so the remote only ever
271 /// fast-forwards. If the remote moved meanwhile, the lease fails and
272 /// nothing changes in braid (beyond the merge already made, if any);
273 /// the next sync takes the new commits in.
274 ///
275 /// # Crashes
276 ///
277 /// A crash after a push and before braid records it loses nothing: the
278 /// next sync computes the same commits again in step 1, so the commits it
279 /// fetches are known as the changesets they came from, and nothing is
280 /// imported twice. A crash between moving the braid branch to a merge and
281 /// pushing it leaves the braid branch ahead, and the next sync pushes it.
282 ///
283 /// Conflicts and refused pushes are outcomes, not errors: see
284 /// [`SyncOutcome`]. With [`SyncOptions::dry_run`], nothing is written.
285 pub fn git_sync(
286 &self,
287 remote: &str,
288 branch: &str,
289 agent: &str,
290 options: &SyncOptions,
291 ) -> Result<SyncReport, Error> {
292 let sync = Sync::new(self, remote, branch, agent, options)?;
293 if options.dry_run {
294 sync.dry_run()
295 } else {
296 sync.run()
297 }
298 }
299
300 /// The committer of the changesets sync makes: the agent label, and the
301 /// email of the configuration or `<agent>@example.org`.
302 fn sync_committer(&self, agent: &str) -> Result<Signature, Error> {
303 if let Some(reason) = unfit_for_git(agent) {
304 return Err(Error::InvalidAgent {
305 agent: agent.to_owned(),
306 reason,
307 });
308 }
309 let email = match self.config()?.email {
310 Some(email) => {
311 if let Some(reason) = unfit_for_git(&email) {
312 return Err(Error::InvalidConfig {
313 key: "email",
314 reason,
315 });
316 }
317 email
318 }
319 None => format!("{}@example.org", email_name(agent)),
320 };
321 Ok(crate::signature_now(agent.as_bytes(), email.as_bytes()))
322 }
323}
324
325/// Why a name or an address cannot be written in a git signature, if it
326/// cannot.
327fn unfit_for_git(text: &str) -> Option<&'static str> {
328 if text.trim().is_empty() {
329 Some("it is empty")
330 } else if text.contains(['<', '>', '\n', '\0']) {
331 Some("it holds '<', '>', a newline or NUL")
332 } else {
333 None
334 }
335}
336
337/// The agent label as the local part of an email address.
338fn email_name(agent: &str) -> String {
339 let mut name = String::new();
340 for c in agent.chars() {
341 let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
342 c
343 } else {
344 '-'
345 };
346 if !(c == '-' && name.ends_with('-')) {
347 name.push(c);
348 }
349 }
350 let name = name.trim_matches(['-', '.']);
351 if name.is_empty() {
352 "braid".to_owned()
353 } else {
354 name.to_owned()
355 }
356}
357
358/// Checks the names: a braid branch outside braid's own namespaces, and a
359/// remote branch git accepts.
360fn check_branches(branch: &str, remote_branch: &str) -> Result<(), Error> {
361 let invalid = |name: &str, reason| Error::InvalidBranch {
362 name: name.to_owned(),
363 reason,
364 };
365 if branch.is_empty() || branch.contains('\0') {
366 return Err(invalid(branch, "it is empty or holds NUL"));
367 }
368 if RESERVED.iter().any(|prefix| branch.starts_with(prefix)) {
369 return Err(invalid(branch, "it is in one of braid's own namespaces"));
370 }
371 if !braid_git::is_branch_name(remote_branch) {
372 return Err(invalid(remote_branch, "git does not accept it as a branch"));
373 }
374 Ok(())
375}
376
377/// One sync with one remote.
378struct Sync<'r> {
379 repo: &'r Repo,
380 git: Git<'r>,
381 remote: Remote,
382 agent: &'r str,
383 committer: Signature,
384 /// The braid branch.
385 branch: String,
386 /// The branch of the remote.
387 remote_branch: String,
388 /// Its full name, `refs/heads/<remote branch>`: on the remote, and in
389 /// the mirror for the braid branch as last exported.
390 branch_ref: String,
391 /// The braid ref recording the remote branch.
392 remote_ref: String,
393 /// The mirror's ref for the remote branch as fetched.
394 tracking_ref: String,
395 /// The directory of the mirrors, absolute.
396 mirrors: PathBuf,
397 /// Which way changes may go.
398 direction: SyncDirection,
399}
400
401impl<'r> Sync<'r> {
402 fn new(
403 repo: &'r Repo,
404 remote: &str,
405 branch: &str,
406 agent: &'r str,
407 options: &'r SyncOptions,
408 ) -> Result<Self, Error> {
409 let remote = Remote::new(remote)?;
410 let remote_branch = options
411 .remote_branch
412 .clone()
413 .unwrap_or_else(|| branch.to_owned());
414 check_branches(branch, &remote_branch)?;
415 Ok(Sync {
416 repo,
417 git: Git::new(&options.git_env),
418 remote_ref: remote_ref(remote.label(), &remote_branch),
419 branch_ref: format!("refs/heads/{remote_branch}"),
420 tracking_ref: format!("refs/remotes/origin/{remote_branch}"),
421 committer: repo.sync_committer(agent)?,
422 mirrors: std::path::absolute(repo.root.join(DIR).join(MIRRORS_DIR))?,
423 branch: branch.to_owned(),
424 remote_branch,
425 remote,
426 agent,
427 direction: options.direction,
428 })
429 }
430
431 /// The remote's mirror.
432 fn mirror(&self) -> PathBuf {
433 self.mirrors.join(format!("{}.git", self.remote.label()))
434 }
435
436 fn run(&self) -> Result<SyncReport, Error> {
437 let (_lock, mirror) = self.open_mirror()?;
438 let store = self.repo.store();
439 let prepared = self.prepare(store, &mirror)?;
440 let decision = self.decide(store, &prepared)?;
441 self.execute(&mirror, prepared, decision)
442 }
443
444 /// Takes the remote's lock, held until the returned file is dropped, and
445 /// creates its mirror if there is none: an empty bare repository, made
446 /// under a temporary name and renamed into place.
447 fn open_mirror(&self) -> Result<(File, PathBuf), Error> {
448 fs::create_dir_all(&self.mirrors)?;
449 let label = self.remote.label();
450 let lock = OpenOptions::new()
451 .create(true)
452 .truncate(false)
453 .write(true)
454 .open(self.mirrors.join(format!("{label}.lock")))?;
455 lock.lock()?;
456 let mirror = self.mirror();
457 if !mirror.join("HEAD").is_file() {
458 let partial = self.mirrors.join(format!("{label}.git.tmp"));
459 if partial.exists() {
460 fs::remove_dir_all(&partial)?;
461 }
462 self.git.init_bare(&partial)?;
463 fs::rename(&partial, &mirror)?;
464 }
465 Ok((lock, mirror))
466 }
467
468 /// Records the commits of the braid branch, fetches the remote branch
469 /// into `fetch_repo` and imports it.
470 fn prepare<O: Objects<Error = braid_store::Error>>(
471 &self,
472 objects: &O,
473 fetch_repo: &Path,
474 ) -> Result<Prepared, Error> {
475 let refs = self.repo.store().refs()?;
476 let head = refs.get(&self.branch);
477 let mut map = self.repo.working_map(refs.get(MAP_REF))?;
478 if let Some(head) = head {
479 if !matches!(objects.stat(&head)?, Some((Kind::Changeset, _))) {
480 return Err(Error::NotAChangeset {
481 what: format!("branch {:?}", self.branch),
482 });
483 }
484 // Exports are deterministic: the commits of braid's changesets
485 // are what a remote holds of them, whether or not an earlier sync
486 // got to record them. A head that cannot be exported fails later,
487 // where it would be pushed.
488 let pairings = {
489 let mut exporter = Exporter::new(objects, &map.map);
490 exporter.commit_id(&head).map(|_| exporter.pairings())
491 };
492 if let Ok(pairings) = pairings {
493 map.map.record(&pairings);
494 }
495 }
496
497 let mut imported = 0;
498 let fetched = match self.git.fetch(
499 fetch_repo,
500 self.remote.address(),
501 &self.branch_ref,
502 &self.tracking_ref,
503 )? {
504 Fetched::Absent => None,
505 Fetched::Branch => {
506 let options = ImportOptions {
507 refs: vec![self.tracking_ref.clone().into_bytes()],
508 };
509 let report = braid_git::import(fetch_repo, objects, &mut map.map, &options)?;
510 imported = report.commits;
511 let fetched = report.refs.into_iter().next().ok_or(Error::NotAChangeset {
512 what: "the remote branch".to_owned(),
513 })?;
514 if fetched.kind != GitKind::Commit {
515 return Err(Error::NotAChangeset {
516 what: "the remote branch".to_owned(),
517 });
518 }
519 Some((fetched.oid, fetched.braid))
520 }
521 };
522 Ok(Prepared {
523 map,
524 head,
525 fetched,
526 imported,
527 })
528 }
529
530 /// What the two heads call for. A merge is made, and stored in
531 /// `objects`, when both moved.
532 fn decide<O: Objects<Error = braid_store::Error>>(
533 &self,
534 objects: &O,
535 prepared: &Prepared,
536 ) -> Result<Decision, Error> {
537 let remote = prepared.fetched.map(|(_, changeset)| changeset);
538 if let (None, None) = (prepared.head, remote) {
539 return Err(Error::NothingToSync {
540 branch: self.branch.clone(),
541 });
542 }
543 let diverged = |why: &str| Ok(Decision::Diverged(why.to_owned()));
544 match (self.direction, prepared.head, remote) {
545 (SyncDirection::Both, ..) => {}
546 (SyncDirection::Publish, None, Some(_)) => {
547 return diverged("braid has no such branch, and the remote has one");
548 }
549 (SyncDirection::Publish, Some(head), Some(remote))
550 if head != remote && !is_ancestor(objects, remote, head)? =>
551 {
552 return diverged("the remote branch has commits the braid branch does not have");
553 }
554 (SyncDirection::Follow, Some(_), None) => {
555 return diverged("the remote has no such branch, and braid has one");
556 }
557 (SyncDirection::Follow, Some(head), Some(remote))
558 if head != remote && !is_ancestor(objects, head, remote)? =>
559 {
560 return diverged("the braid branch has changesets the remote branch does not have");
561 }
562 _ => {}
563 }
564 Ok(match (prepared.head, remote) {
565 (None, None) => unreachable!("handled above"),
566 (None, Some(remote)) => Decision::Create(remote),
567 (Some(head), None) => Decision::Push(head),
568 (Some(head), Some(remote)) if head == remote => Decision::UpToDate,
569 (Some(head), Some(remote)) if is_ancestor(objects, remote, head)? => {
570 Decision::Push(head)
571 }
572 (Some(head), Some(remote)) => {
573 let message = format!("Merge {} into {}\n", self.remote_ref, self.branch);
574 let agent = vec![(AGENT.to_vec(), self.agent.as_bytes().to_vec())];
575 match merge(
576 objects,
577 head,
578 remote,
579 self.committer.clone(),
580 message.into_bytes(),
581 agent,
582 )? {
583 MergeOutcome::UpToDate => Decision::Push(head),
584 MergeOutcome::FastForward(to) => Decision::FastForward(to),
585 MergeOutcome::Merged {
586 changeset,
587 merged_paths,
588 } => Decision::Merge {
589 changeset,
590 merged_paths,
591 },
592 MergeOutcome::Conflicts(conflicts) => Decision::Conflicts(conflicts),
593 }
594 }
595 })
596 }
597
598 fn report(&self, prepared: &Prepared, dry_run: bool) -> SyncReport {
599 SyncReport {
600 label: self.remote.label().to_owned(),
601 branch: self.branch.clone(),
602 remote_branch: self.remote_branch.clone(),
603 remote_ref: self.remote_ref.clone(),
604 outcome: SyncOutcome::UpToDate,
605 before: prepared.head,
606 after: prepared.head,
607 fetched: prepared.fetched,
608 pushed: None,
609 imported: prepared.imported,
610 dry_run,
611 operations: Vec::new(),
612 }
613 }
614
615 /// Carries a decision out.
616 fn execute(
617 &self,
618 mirror: &Path,
619 mut prepared: Prepared,
620 decision: Decision,
621 ) -> Result<SyncReport, Error> {
622 let mut report = self.report(&prepared, false);
623 let head = prepared.head;
624 let fetched = prepared.fetched.map(|(commit, _)| commit);
625 let remote = prepared.fetched.map(|(_, changeset)| changeset);
626 let map = &mut prepared.map;
627 report.outcome = match decision {
628 Decision::UpToDate => {
629 // What step 1 and the import added to the map, and where the
630 // remote branch is.
631 report
632 .operations
633 .extend(self.save("up to date", map, None, remote)?);
634 SyncOutcome::UpToDate
635 }
636 Decision::Create(to) => {
637 report.operations.extend(self.save(
638 &format!("created {}", self.branch),
639 map,
640 Some((None, to)),
641 Some(to),
642 )?);
643 report.after = Some(to);
644 SyncOutcome::Created
645 }
646 Decision::FastForward(to) => {
647 report.operations.extend(self.save(
648 "fast-forward",
649 map,
650 Some((head, to)),
651 Some(to),
652 )?);
653 report.after = Some(to);
654 SyncOutcome::FastForwarded
655 }
656 Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
657 Decision::Diverged(reason) => SyncOutcome::Diverged { reason },
658 Decision::Push(target) => {
659 let commit = self.export(mirror, map, target)?;
660 match self.push(mirror, commit, fetched)? {
661 Ok(()) => {
662 report.operations.extend(self.save(
663 &format!("pushed {commit}"),
664 map,
665 None,
666 Some(target),
667 )?);
668 report.pushed = Some(commit);
669 SyncOutcome::Pushed
670 }
671 Err(refused) => refused.outcome(),
672 }
673 }
674 Decision::Merge {
675 changeset,
676 merged_paths,
677 } => {
678 let commit = self.export(mirror, map, changeset)?;
679 report.operations.extend(self.save(
680 "merge",
681 map,
682 Some((head, changeset)),
683 remote,
684 )?);
685 report.after = Some(changeset);
686 match self.push(mirror, commit, fetched)? {
687 Ok(()) => {
688 report.operations.extend(self.save(
689 &format!("pushed {commit}"),
690 map,
691 None,
692 Some(changeset),
693 )?);
694 report.pushed = Some(commit);
695 SyncOutcome::Merged {
696 merge: changeset,
697 merged_paths,
698 }
699 }
700 Err(refused) => refused.outcome(),
701 }
702 }
703 };
704 Ok(report)
705 }
706
707 /// Records an operation: the braid branch moved from one value to
708 /// another, the remote ref to its value, and the map when it grew.
709 fn save(
710 &self,
711 what: &str,
712 map: &mut WorkingMap,
713 branch: Option<(Option<ObjectId>, ObjectId)>,
714 remote: Option<ObjectId>,
715 ) -> Result<Option<Operation>, Error> {
716 let mut moves = Vec::new();
717 if let Some((from, to)) = branch {
718 moves.push(Move {
719 name: self.branch.clone(),
720 expect: Some(from),
721 new: to,
722 });
723 }
724 if let Some(remote) = remote {
725 moves.push(Move {
726 name: self.remote_ref.clone(),
727 expect: None,
728 new: remote,
729 });
730 }
731 let description = format!("git sync {} with {}: {what}", self.branch, self.remote_ref);
732 self.repo
733 .save_with_map(self.agent, &description, map, &moves)
734 }
735
736 /// Exports a changeset into the mirror, as the mirror's branch, and
737 /// records in the map what the export generated. Returns its commit.
738 fn export(
739 &self,
740 mirror: &Path,
741 map: &mut WorkingMap,
742 changeset: ObjectId,
743 ) -> Result<GitOid, Error> {
744 let report = braid_git::write_to_repo_recording(
745 mirror,
746 self.repo.store(),
747 &mut map.map,
748 &[braid_git::RefUpdate {
749 name: self.branch_ref.clone().into_bytes(),
750 target: RefTarget::Changeset(changeset),
751 }],
752 )?;
753 Ok(report.refs[0].1)
754 }
755
756 /// Pushes a commit with a lease on what was fetched.
757 fn push(
758 &self,
759 mirror: &Path,
760 commit: GitOid,
761 expected: Option<GitOid>,
762 ) -> Result<Result<(), Refused>, Error> {
763 let address = self.remote.address();
764 let reason = match self
765 .git
766 .push(mirror, address, &self.branch_ref, commit, expected)?
767 {
768 Pushed::Done => return Ok(Ok(())),
769 Pushed::Refused(reason) => reason,
770 };
771 // Whether the remote moved, or refused for another reason.
772 Ok(
773 match self.git.ls_remote(mirror, address, &self.branch_ref) {
774 Ok(found) if found == Some(commit) => Ok(()),
775 Ok(found) if found != expected => Err(Refused::RemoteMoved(found)),
776 _ => Err(Refused::Rejected(reason)),
777 },
778 )
779 }
780
781 /// Everything [`run`](Self::run) would do up to the push, on a copy:
782 /// the remote branch is fetched into a temporary repository that borrows
783 /// the mirror's objects, and braid objects go to memory.
784 fn dry_run(&self) -> Result<SyncReport, Error> {
785 let mirror = self.mirror();
786 let borrow = mirror.join("HEAD").is_file().then_some(mirror.as_path());
787 let scratch = Scratch::create(&self.git, borrow)?;
788 let overlay = Overlay {
789 store: self.repo.store(),
790 added: MemoryObjects::new(),
791 };
792 let prepared = self.prepare(&overlay, scratch.path())?;
793 let decision = self.decide(&overlay, &prepared)?;
794 let mut report = self.report(&prepared, true);
795 let commit_of = |changeset: ObjectId| -> Result<GitOid, Error> {
796 Ok(Exporter::new(&overlay, &prepared.map.map).commit_id(&changeset)?)
797 };
798 report.outcome = match decision {
799 Decision::UpToDate => SyncOutcome::UpToDate,
800 Decision::Create(to) => {
801 report.after = Some(to);
802 SyncOutcome::Created
803 }
804 Decision::FastForward(to) => {
805 report.after = Some(to);
806 SyncOutcome::FastForwarded
807 }
808 Decision::Push(target) => {
809 report.pushed = Some(commit_of(target)?);
810 SyncOutcome::Pushed
811 }
812 Decision::Merge {
813 changeset,
814 merged_paths,
815 } => {
816 report.pushed = Some(commit_of(changeset)?);
817 report.after = Some(changeset);
818 SyncOutcome::Merged {
819 merge: changeset,
820 merged_paths,
821 }
822 }
823 Decision::Conflicts(conflicts) => SyncOutcome::Conflicts(conflicts),
824 Decision::Diverged(reason) => SyncOutcome::Diverged { reason },
825 };
826 Ok(report)
827 }
828}
829
830/// The store, with what is written kept in memory: what a dry run works on.
831struct Overlay<'s> {
832 store: &'s Store,
833 added: MemoryObjects,
834}
835
836impl Objects for Overlay<'_> {
837 type Error = braid_store::Error;
838
839 fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> {
840 let Ok(found) = self.added.get(id);
841 match found {
842 Some(found) => Ok(Some(found)),
843 None => self.store.get(id),
844 }
845 }
846
847 fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> {
848 let Ok(id) = self.added.put(kind, payload);
849 Ok(id)
850 }
851
852 fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> {
853 let Ok(found) = self.added.contains(id);
854 if found {
855 return Ok(true);
856 }
857 self.store.contains(id)
858 }
859
860 fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> {
861 let Ok(found) = self.added.stat(id);
862 match found {
863 Some(found) => Ok(Some(found)),
864 None => self.store.stat(id),
865 }
866 }
867}
868
869#[cfg(test)]
870mod tests;