Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 21.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Importing from and exporting to git repositories.
5//!
6//! The map between git and braid ids is a derived object in the store, and the
7//! ref [`MAP_REF`] points at its current version. An import moves that ref in
8//! 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.
16
17use std::convert::Infallible;
18use std::path::Path;
19
20use braid_format::{Kind, ObjectId, Objects};
21use braid_git::{GitMap, ImportOptions, ImportReport, MapCounts, RefTarget, WriteReport};
22use braid_store::{Operation, RefUpdate, TransactError};
23
24use crate::{Error, Repo};
25
26/// The ref that points at the current git map.
27pub const MAP_REF: &str = "braid/git-map";
28
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.
32pub const REMOTE_PREFIX: &str = "remote/";
33
34/// The agent label of the operations [`Repo::git_export`] records.
35pub 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.
39pub(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.
43const MAP_ATTEMPTS: usize = 16;
44
45/// The braid ref for a git ref: branches keep their short name, tags go under
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/`.
49pub fn braid_ref_for_git(name: &[u8]) -> Option<String> {
50 let name = std::str::from_utf8(name).ok()?;
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 {
55 branch.to_owned()
56 } else if let Some(tag) = name.strip_prefix("refs/tags/") {
57 format!("tags/{tag}")
58 } else {
59 format!("git/{name}")
60 })
61}
62
63/// Whether a braid ref is a branch: a name outside braid's own namespaces
64/// (`braid/`, `git/`, `remote/` and `tags/`), which exports as
65/// `refs/heads/<name>`.
66pub fn is_branch(name: &str) -> bool {
67 !RESERVED.iter().any(|prefix| name.starts_with(prefix))
68}
69
70/// The git ref for a braid ref, or `None` for braid's own refs and for the
71/// refs that record the branches of remotes.
72pub fn git_ref_for_braid(name: &str) -> Option<String> {
73 if name.starts_with("braid/") || name.starts_with(REMOTE_PREFIX) {
74 None
75 } else if let Some(tag) = name.strip_prefix("tags/") {
76 Some(format!("refs/tags/{tag}"))
77 } else if let Some(full) = name.strip_prefix("git/") {
78 Some(full.to_owned())
79 } else {
80 Some(format!("refs/heads/{name}"))
81 }
82}
83
84/// The braid ref that records where `branch` of the remote labelled `label`
85/// was last seen: `remote/<label>/<branch>`.
86pub fn remote_ref(label: &str, branch: &str) -> String {
87 format!("{REMOTE_PREFIX}{label}/{branch}")
88}
89
90/// What `git_import` did.
91#[derive(Debug)]
92pub struct GitImport {
93 /// What the bridge imported.
94 pub report: ImportReport,
95 /// The operation that moved the refs, or `None` when nothing changed.
96 pub operation: Option<Operation>,
97 /// Braid refs the import left where they were, because moving them would
98 /// have dropped work braid has and git has not.
99 pub kept: Vec<KeptRef>,
100}
101
102/// A braid ref that an import did not move, and why.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct KeptRef {
105 /// The braid ref.
106 pub name: String,
107 /// Where it stays.
108 pub braid: ObjectId,
109 /// What git's ref points to, as a braid object.
110 pub git: ObjectId,
111 /// Why it was not moved.
112 pub reason: KeptReason,
113}
114
115/// Why an import did not move a braid ref.
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117pub enum KeptReason {
118 /// Braid's ref already contains git's commit: braid is ahead.
119 Ahead,
120 /// Each side has work the other does not.
121 Diverged,
122 /// One side is not a changeset, for example a tag that moved in git.
123 NotAChangeset,
124 /// The ref moved while the import ran.
125 Moved,
126}
127
128impl KeptReason {
129 /// The name used in JSON output.
130 pub fn code(self) -> &'static str {
131 match self {
132 KeptReason::Ahead => "ahead",
133 KeptReason::Diverged => "diverged",
134 KeptReason::NotAChangeset => "not_a_changeset",
135 KeptReason::Moved => "moved",
136 }
137 }
138}
139
140fn store_error(err: TransactError<Infallible>) -> Error {
141 match err {
142 TransactError::Store(err) => Error::Store(err),
143 TransactError::Aborted(never) => match never {},
144 }
145}
146
147/// A git map being added to, and the stored map it started from.
148#[derive(Debug)]
149pub(crate) struct WorkingMap {
150 /// The map.
151 pub(crate) map: GitMap,
152 /// What [`MAP_REF`] pointed at when the map was read.
153 base: Option<ObjectId>,
154 /// What that map held.
155 counts: MapCounts,
156}
157
158impl WorkingMap {
159 /// Whether the map holds more than the stored map it started from.
160 pub(crate) fn changed(&self) -> bool {
161 self.map.counts() != self.counts
162 }
163}
164
165/// What an operation that saves the git map expects of a ref.
166#[derive(Clone, Debug)]
167pub(crate) struct Move {
168 /// The ref.
169 pub(crate) name: String,
170 /// The value it must hold, `None` for a ref that must not exist; or, when
171 /// this is `None` itself, whatever it holds.
172 pub(crate) expect: Option<Option<ObjectId>>,
173 /// Its new value.
174 pub(crate) new: ObjectId,
175}
176
177/// Why an operation that saves the git map recorded nothing.
178enum Abort {
179 /// [`MAP_REF`] moved since the map was read.
180 MapMoved(Option<ObjectId>),
181 /// A ref did not hold the value the operation expected.
182 Moved(String),
183 /// Nothing would change.
184 Nothing,
185}
186
187impl Repo {
188 /// The current git map, empty if nothing was imported yet.
189 pub fn git_map(&self) -> Result<GitMap, Error> {
190 self.git_map_at(self.store.refs()?.get(MAP_REF))
191 }
192
193 /// Adds to the stored git map every entry of `map` that it lacks, as one
194 /// operation by `agent` that moves [`MAP_REF`], and returns it, or `None`
195 /// when the stored map holds them all. Where the two disagree, what the
196 /// stored map knows wins (see [`GitMap::absorb`]).
197 ///
198 /// This is how a server that computes the commits of its changesets with
199 /// an [`Exporter`](braid_git::Exporter), without writing them into a git
200 /// repository, keeps what it computed: exports are deterministic, so the
201 /// pairings stay true, and the next export starts from them.
202 pub fn git_record(&self, map: &GitMap, agent: &str) -> Result<Option<Operation>, Error> {
203 let mut working = self.working_map(self.store.refs()?.get(MAP_REF))?;
204 let added = working.map.absorb(map);
205 if !working.changed() {
206 return Ok(None);
207 }
208 let description = format!(
209 "git map: {} commits, {} trees and {} blobs recorded",
210 added.commits, added.trees, added.blobs
211 );
212 self.save_with_map(agent, &description, &mut working, &[])
213 }
214
215 /// The git map stored as `id`, or the empty map.
216 fn git_map_at(&self, id: Option<ObjectId>) -> Result<GitMap, Error> {
217 let Some(id) = id else {
218 return Ok(GitMap::new());
219 };
220 let Some((_, bytes)) = self.store.get(&id)? else {
221 return Err(Error::UnknownRevision(MAP_REF.to_owned()));
222 };
223 GitMap::from_bytes(&bytes).map_err(Error::GitMap)
224 }
225
226 /// The git map stored as `base`, the value of [`MAP_REF`], to add to.
227 pub(crate) fn working_map(&self, base: Option<ObjectId>) -> Result<WorkingMap, Error> {
228 let map = self.git_map_at(base)?;
229 let counts = map.counts();
230 Ok(WorkingMap { map, base, counts })
231 }
232
233 /// Records one operation by `agent` that makes the `moves` and, if the
234 /// map grew, points [`MAP_REF`] at it. Returns `None` when nothing would
235 /// change.
236 ///
237 /// If another operation saved a map meanwhile, the two are merged (see
238 /// [`GitMap::absorb`]) and the operation is tried again, so that no
239 /// pairing is lost. If a ref of `moves` does not hold what it should,
240 /// nothing is recorded and the error is [`Error::BranchMoved`].
241 pub(crate) fn save_with_map(
242 &self,
243 agent: &str,
244 description: &str,
245 map: &mut WorkingMap,
246 moves: &[Move],
247 ) -> Result<Option<Operation>, Error> {
248 for _ in 0..MAP_ATTEMPTS {
249 let map_id = if map.changed() {
250 let id = self.put_map(&map.map, map.base)?;
251 self.store.sync()?;
252 Some(id)
253 } else {
254 None
255 };
256 let base = map.base;
257 let result = self.store.transact(agent, description, |refs| {
258 let mut updates = Vec::new();
259 for wanted in moves {
260 let found = refs.get(&wanted.name);
261 if wanted.expect.is_some_and(|expected| expected != found) {
262 return Err(Abort::Moved(wanted.name.clone()));
263 }
264 if found != Some(wanted.new) {
265 updates.push(RefUpdate::new(wanted.name.clone(), found, Some(wanted.new)));
266 }
267 }
268 if let Some(id) = map_id {
269 let found = refs.get(MAP_REF);
270 if found != base {
271 return Err(Abort::MapMoved(found));
272 }
273 updates.push(RefUpdate::new(MAP_REF, found, Some(id)));
274 }
275 if updates.is_empty() {
276 return Err(Abort::Nothing);
277 }
278 Ok(updates)
279 });
280 match result {
281 Ok(operation) => {
282 if let Some(id) = map_id {
283 map.base = Some(id);
284 map.counts = map.map.counts();
285 }
286 return Ok(Some(operation));
287 }
288 Err(TransactError::Aborted(Abort::Nothing)) => return Ok(None),
289 Err(TransactError::Aborted(Abort::MapMoved(found))) => {
290 let mut current = self.git_map_at(found)?;
291 let counts = current.counts();
292 current.absorb(&map.map);
293 *map = WorkingMap {
294 map: current,
295 base: found,
296 counts,
297 };
298 }
299 Err(TransactError::Aborted(Abort::Moved(name))) => {
300 return Err(Error::BranchMoved { branch: name });
301 }
302 Err(TransactError::Store(err)) => return Err(Error::Store(err)),
303 }
304 }
305 Err(Error::Busy {
306 name: MAP_REF.to_owned(),
307 })
308 }
309
310 /// Stores a git map, with the map it grew from, if any, as a hint: the
311 /// store may keep it as a delta against it instead of whole again.
312 fn put_map(&self, map: &GitMap, previous: Option<ObjectId>) -> Result<ObjectId, Error> {
313 let bytes = map.to_bytes();
314 Ok(match previous {
315 Some(previous) => self.store.put_similar(Kind::Derived, &bytes, &previous)?,
316 None => self.store.put(Kind::Derived, &bytes)?,
317 })
318 }
319
320 /// Imports every branch and tag of the git repository at `git_repo`,
321 /// incrementally, on one thread per core (up to eight), and points the
322 /// matching braid refs at them.
323 pub fn git_import(&self, git_repo: &Path, agent: &str) -> Result<GitImport, Error> {
324 let previous = self.store.refs()?.get(MAP_REF);
325 let mut map = self.git_map_at(previous)?;
326 let options = ImportOptions::default();
327 let report = braid_git::import_parallel(git_repo, &self.store, &mut map, &options, 0)?;
328 let map_id = self.put_map(&map, previous)?;
329 self.store.sync()?;
330
331 let mut wanted: Vec<(String, ObjectId)> = report
332 .refs
333 .iter()
334 .filter_map(|r| braid_ref_for_git(&r.name).map(|name| (name, r.braid)))
335 .collect();
336 wanted.push((MAP_REF.to_owned(), map_id));
337
338 // Decide which refs may move before taking the op log lock: a ref that
339 // does not exist yet, or one git's commit descends from. A braid ref
340 // with work git does not have stays where it is, so an import never
341 // takes a branch backwards or sideways.
342 let current = self.store.refs()?;
343 let mut moves: Vec<(String, Option<ObjectId>, ObjectId)> = Vec::new();
344 let mut kept = Vec::new();
345 for (name, id) in &wanted {
346 let now = current.get(name);
347 if now == Some(*id) {
348 continue;
349 }
350 match now {
351 Some(now) if name != MAP_REF => match self.import_may_move(now, *id)? {
352 None => moves.push((name.clone(), Some(now), *id)),
353 Some(reason) => kept.push(KeptRef {
354 name: name.clone(),
355 braid: now,
356 git: *id,
357 reason,
358 }),
359 },
360 _ => moves.push((name.clone(), now, *id)),
361 }
362 }
363 if moves.is_empty() {
364 return Ok(GitImport {
365 report,
366 operation: None,
367 kept,
368 });
369 }
370 let moved = moves.iter().filter(|(name, ..)| name != MAP_REF).count();
371 let description = if kept.is_empty() {
372 format!("git import of {moved} refs")
373 } else {
374 format!("git import of {moved} refs, {} kept", kept.len())
375 };
376 let mut moved_meanwhile = Vec::new();
377 let operation = self
378 .store
379 .transact(agent, &description, |refs| {
380 let mut updates = Vec::with_capacity(moves.len());
381 for (name, old, new) in &moves {
382 let now = refs.get(name);
383 if now == *old || name == MAP_REF {
384 updates.push(RefUpdate::new(name.clone(), now, Some(*new)));
385 } else if let Some(now) = now {
386 moved_meanwhile.push(KeptRef {
387 name: name.clone(),
388 braid: now,
389 git: *new,
390 reason: KeptReason::Moved,
391 });
392 }
393 }
394 Ok(updates)
395 })
396 .map_err(store_error)?;
397 kept.extend(moved_meanwhile);
398 Ok(GitImport {
399 report,
400 operation: Some(operation),
401 kept,
402 })
403 }
404
405 /// Whether an import may move a braid ref from `braid` to `git`: `None`
406 /// when git's commit descends from braid's, otherwise why it may not.
407 fn import_may_move(&self, braid: ObjectId, git: ObjectId) -> Result<Option<KeptReason>, Error> {
408 let changeset = |id: &ObjectId| -> Result<bool, Error> {
409 Ok(matches!(self.store.stat(id)?, Some((Kind::Changeset, _))))
410 };
411 if !changeset(&braid)? || !changeset(&git)? {
412 return Ok(Some(KeptReason::NotAChangeset));
413 }
414 if braid_engine::is_ancestor(&self.store, braid, git)? {
415 return Ok(None);
416 }
417 if braid_engine::is_ancestor(&self.store, git, braid)? {
418 return Ok(Some(KeptReason::Ahead));
419 }
420 Ok(Some(KeptReason::Diverged))
421 }
422
423 /// Writes the given braid refs (all of them when `names` is empty) into
424 /// the git repository at `git_repo`, which must exist. Existing git refs
425 /// of the same names are overwritten.
426 ///
427 /// The commits, trees and blobs the export generated for changesets made
428 /// in braid are recorded in the git map, as an operation by
429 /// [`GIT_EXPORT_AGENT`]; [`git_export_as`](Self::git_export_as) names
430 /// the agent.
431 pub fn git_export(&self, git_repo: &Path, names: &[String]) -> Result<WriteReport, Error> {
432 self.git_export_as(git_repo, names, GIT_EXPORT_AGENT)
433 }
434
435 /// [`git_export`](Self::git_export), recording the git map as an
436 /// operation by `agent`.
437 pub fn git_export_as(
438 &self,
439 git_repo: &Path,
440 names: &[String],
441 agent: &str,
442 ) -> Result<WriteReport, Error> {
443 let refs = self.store.refs()?;
444 let mut map = self.working_map(refs.get(MAP_REF))?;
445 let mut updates = Vec::new();
446 for (name, id) in refs.iter() {
447 if !names.is_empty() && !names.iter().any(|n| n == name) {
448 continue;
449 }
450 let Some(git_name) = git_ref_for_braid(name) else {
451 continue;
452 };
453 let target = match self.store.stat(&id)? {
454 Some((Kind::Changeset, _)) => RefTarget::Changeset(id),
455 Some((Kind::Blob, _)) => match map.map.git_tag(&id) {
456 Some(tag) => RefTarget::Git(tag),
457 None => {
458 return Err(Error::NotExportable {
459 name: name.to_owned(),
460 });
461 }
462 },
463 _ => {
464 return Err(Error::NotExportable {
465 name: name.to_owned(),
466 });
467 }
468 };
469 updates.push(braid_git::RefUpdate {
470 name: git_name.into_bytes(),
471 target,
472 });
473 }
474 for name in names {
475 if refs.get(name).is_none() {
476 return Err(Error::UnknownRevision(name.clone()));
477 }
478 }
479 let report =
480 braid_git::write_to_repo_recording(git_repo, &self.store, &mut map.map, &updates)?;
481 if map.changed() {
482 let description = format!("git export of {} refs", updates.len());
483 self.save_with_map(agent, &description, &mut map, &[])?;
484 }
485 Ok(report)
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn ref_names_round_trip() {
495 for (git, braid) in [
496 ("refs/heads/main", "main"),
497 ("refs/heads/feature/x", "feature/x"),
498 ("refs/tags/v1.0", "tags/v1.0"),
499 ("refs/notes/commits", "git/refs/notes/commits"),
500 // Branches named like braid's own namespaces keep their full
501 // names, so that none of them lands there.
502 ("refs/heads/tags/v1", "git/refs/heads/tags/v1"),
503 ("refs/heads/git/x", "git/refs/heads/git/x"),
504 ("refs/heads/remote/a/main", "git/refs/heads/remote/a/main"),
505 ("refs/heads/braid/git-map", "git/refs/heads/braid/git-map"),
506 ("refs/heads/remotes", "remotes"),
507 ("refs/heads/tags", "tags"),
508 ] {
509 assert_eq!(braid_ref_for_git(git.as_bytes()).as_deref(), Some(braid));
510 assert_eq!(git_ref_for_braid(braid).as_deref(), Some(git));
511 }
512 assert_eq!(git_ref_for_braid(MAP_REF), None);
513 assert_eq!(braid_ref_for_git(b"refs/heads/\xff"), None);
514 let remote = remote_ref("origin-0123456789ab", "main");
515 assert_eq!(remote, "remote/origin-0123456789ab/main");
516 assert_eq!(git_ref_for_braid(&remote), None);
517 }
518
519 #[test]
520 fn what_an_export_computed_is_recorded_once() {
521 use braid_format::{Change, ChangeOp, Signature};
522
523 let dir = tempfile::tempdir().unwrap();
524 let repo = Repo::init(dir.path()).unwrap();
525 let blob = repo.store().put(Kind::Blob, b"hello\n").unwrap();
526 let signature = Signature {
527 name: b"Ada".to_vec(),
528 email: b"ada@example.org".to_vec(),
529 seconds: 1_700_000_000,
530 offset_minutes: 0,
531 };
532 let changeset = braid_engine::commit(
533 repo.store(),
534 Vec::new(),
535 vec![Change {
536 path: b"hello.txt".to_vec(),
537 op: ChangeOp::File { blob, size: 6 },
538 }],
539 signature.clone(),
540 signature,
541 b"hello\n".to_vec(),
542 Vec::new(),
543 )
544 .unwrap();
545 repo.store().sync().unwrap();
546
547 // Computed in memory, without a git repository.
548 let mut map = repo.git_map().unwrap();
549 let mut exporter = braid_git::Exporter::new(repo.store(), &map);
550 let commit = exporter.commit_id(&changeset).unwrap();
551 let pairings = exporter.pairings();
552 map.record(&pairings);
553
554 let operation = repo.git_record(&map, "hub").unwrap().unwrap();
555 assert_eq!(operation.agent, "hub");
556 let stored = repo.git_map().unwrap();
557 assert_eq!(stored.commit(&changeset), Some(commit));
558 assert_eq!(stored.changeset(&commit), Some(changeset));
559 // Nothing new: nothing recorded.
560 assert!(repo.git_record(&map, "hub").unwrap().is_none());
561 }
562
563 #[test]
564 fn branches_are_the_refs_outside_braids_namespaces() {
565 for branch in ["main", "feature/x", "tags", "remotes", "gitlab"] {
566 assert!(is_branch(branch), "{branch}");
567 assert_eq!(
568 git_ref_for_braid(branch),
569 Some(format!("refs/heads/{branch}"))
570 );
571 }
572 for other in [
573 MAP_REF,
574 "tags/v1",
575 "git/refs/notes/commits",
576 "remote/a/main",
577 ] {
578 assert!(!is_branch(other), "{other}");
579 }
580 }
581}