Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 20.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
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.
6//!
7//! A repository is a directory holding a `.braid` directory. Inside it,
8//! `store/` is the object store and op log shared by every process and every
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`]).
12//!
13//! A workspace is any directory holding a `.braid` *file* instead: a
14//! [`WorkspaceLink`] naming the repository and the workspace. [`locate`] and
15//! [`Repo::discover`] find the repository from inside either.
16//!
17//! A revision is a ref name, a full object id, or a short id: at least
18//! [`MIN_SHORT_ID`] hex digits that start the id of exactly one stored
19//! object (see [`Repo::resolve`]).
20//!
21//! [`Repo::history`] answers history queries (ancestry, the changes to a
22//! path, blame) with the derived data the store keeps, computing what is
23//! missing.
24
25#![forbid(unsafe_code)]
26
27mod clock;
28mod config;
29mod git;
30mod history;
31mod link;
32mod remote;
33mod sync;
34pub mod text;
35
36use std::fs;
37use std::io;
38use std::path::{Path, PathBuf};
39
40use braid_format::{Kind, ObjectId, Objects};
41use braid_store::{DerivedIndexFile, Options, Store};
42
43pub use braid_engine::{Conflict, ConflictHunk, ConflictKind, HunkSide};
44pub use clock::{local_now, signature_now};
45pub use config::{CONFIG_FILE, Config};
46pub use git::{
47 GIT_EXPORT_AGENT, GitImport, KeptReason, KeptRef, MAP_REF, REMOTE_PREFIX, braid_ref_for_git,
48 git_ref_for_braid, is_branch, remote_ref,
49};
50pub use history::{RepoHistory, StoreIndex};
51pub use link::{Location, WORK_DIR, WORKSPACES_DIR, WorkspaceLink, locate};
52pub use remote::Remote;
53pub use sync::{MIRRORS_DIR, SyncDirection, SyncOptions, SyncOutcome, SyncReport};
54
55/// Name of the directory that holds a repository's data.
56pub const DIR: &str = ".braid";
57
58/// Name of the object store inside [`DIR`].
59pub const STORE_DIR: &str = "store";
60
61/// Why a repository operation failed.
62#[derive(Debug, thiserror::Error)]
63#[non_exhaustive]
64pub enum Error {
65 /// No `.braid` directory or workspace file in the starting directory or
66 /// any parent.
67 #[error("not inside a braid repository")]
68 NotFound,
69 /// A workspace's `.braid` file cannot be read.
70 #[error("{}: not a valid workspace file: {detail}", .path.display())]
71 BadWorkspaceFile {
72 /// The file.
73 path: PathBuf,
74 /// What is wrong with it.
75 detail: String,
76 },
77 /// `init` on a directory that already holds a repository.
78 #[error("a braid repository already exists here")]
79 AlreadyExists,
80 /// A name that is neither a ref nor the id of a stored object.
81 #[error("no ref or object named {0:?}")]
82 UnknownRevision(String),
83 /// A short id that several stored objects start with.
84 #[error("{}", ambiguous(.prefix, .candidates, *.more))]
85 AmbiguousRevision {
86 /// The short id, as given.
87 prefix: String,
88 /// The first few objects it could name, sorted, with their kinds.
89 candidates: Vec<(ObjectId, Kind)>,
90 /// Whether more objects start with it than `candidates` lists.
91 more: bool,
92 },
93 /// A revision that names an object of another kind than the one needed.
94 #[error("{revision:?} is a {found}, not a {expected}")]
95 WrongKind {
96 /// The revision, as given.
97 revision: String,
98 /// The kind needed.
99 expected: Kind,
100 /// The kind of the object it names.
101 found: Kind,
102 },
103 /// The store failed.
104 #[error(transparent)]
105 Store(#[from] braid_store::Error),
106 /// The git bridge failed.
107 #[error(transparent)]
108 Git(#[from] braid_git::Error),
109 /// The stored git map does not decode.
110 #[error("the stored git map is damaged: {0}")]
111 GitMap(braid_format::DecodeError),
112 /// A ref names an object the git bridge cannot export.
113 #[error("ref {name:?} points at an object that has no git form")]
114 NotExportable {
115 /// The ref.
116 name: String,
117 },
118 /// The file system failed.
119 #[error(transparent)]
120 Io(#[from] io::Error),
121 /// A merge, or a walk of history, failed.
122 #[error(transparent)]
123 Engine(#[from] braid_engine::Error),
124 /// A git remote braid does not hand to git.
125 #[error("invalid remote {remote:?}: {reason}")]
126 InvalidRemote {
127 /// The remote as given.
128 remote: String,
129 /// Why it is refused.
130 reason: &'static str,
131 },
132 /// A branch name sync cannot use.
133 #[error("invalid branch name {name:?}: {reason}")]
134 InvalidBranch {
135 /// The name.
136 name: String,
137 /// Why it is refused.
138 reason: &'static str,
139 },
140 /// An agent label that cannot name the committer of a git commit.
141 #[error("the agent label {agent:?} cannot name a git committer: {reason}")]
142 InvalidAgent {
143 /// The label.
144 agent: String,
145 /// Why it cannot.
146 reason: &'static str,
147 },
148 /// A setting of the repository's configuration that cannot be used.
149 #[error("the setting {key:?} in .braid/config cannot be used: {reason}")]
150 InvalidConfig {
151 /// The setting.
152 key: &'static str,
153 /// Why.
154 reason: &'static str,
155 },
156 /// A branch that should point at a changeset, or a remote branch that
157 /// should point at a commit, does not.
158 #[error("{what} does not point at a changeset")]
159 NotAChangeset {
160 /// Which branch.
161 what: String,
162 },
163 /// Neither braid nor the remote has the branch to sync.
164 #[error("neither braid nor the remote has the branch {branch:?}")]
165 NothingToSync {
166 /// The braid branch.
167 branch: String,
168 },
169 /// Another operation moved a branch while sync was working on it.
170 /// Nothing was pushed; syncing again starts from where it is now.
171 #[error("branch {branch:?} moved during the sync; nothing was pushed, sync again")]
172 BranchMoved {
173 /// The branch.
174 branch: String,
175 },
176 /// A ref kept moving, so an operation could not be recorded.
177 #[error("ref {name:?} keeps moving; try again")]
178 Busy {
179 /// The ref.
180 name: String,
181 },
182 /// A git command failed.
183 #[error("git {command} failed: {detail}")]
184 GitCommand {
185 /// The git command.
186 command: &'static str,
187 /// What git said, or why it could not run.
188 detail: String,
189 },
190}
191
192/// An open repository.
193#[derive(Debug)]
194pub struct Repo {
195 root: PathBuf,
196 store: Store,
197 /// The store's derived index, read when first needed.
198 derived: DerivedIndexFile,
199}
200
201impl Repo {
202 /// Creates a repository in `dir`, which is created if needed.
203 pub fn init(dir: &Path) -> Result<Repo, Error> {
204 Repo::init_with(dir, Options::default())
205 }
206
207 /// Creates a repository in `dir` with the store opened with `options`:
208 /// a server passes [`Durability::Full`](braid_store::Durability::Full).
209 pub fn init_with(dir: &Path, options: Options) -> Result<Repo, Error> {
210 let store_dir = dir.join(DIR).join(STORE_DIR);
211 if store_dir.exists() {
212 return Err(Error::AlreadyExists);
213 }
214 fs::create_dir_all(dir.join(DIR))?;
215 let store = Store::init(&store_dir, options)?;
216 Ok(Repo {
217 root: dir.to_path_buf(),
218 store,
219 derived: DerivedIndexFile::new(&store_dir),
220 })
221 }
222
223 /// Opens the repository whose root is `dir`.
224 pub fn open(dir: &Path) -> Result<Repo, Error> {
225 Repo::open_with(dir, Options::default())
226 }
227
228 /// Opens the repository whose root is `dir`, its store with `options`.
229 pub fn open_with(dir: &Path, options: Options) -> Result<Repo, Error> {
230 let store_dir = dir.join(DIR).join(STORE_DIR);
231 if !store_dir.is_dir() {
232 return Err(Error::NotFound);
233 }
234 let store = Store::open(&store_dir, options)?;
235 Ok(Repo {
236 root: dir.to_path_buf(),
237 store,
238 derived: DerivedIndexFile::new(&store_dir),
239 })
240 }
241
242 /// Opens the repository that contains `start`: `start` itself or the
243 /// nearest parent with a `.braid` directory, or the repository named by
244 /// the `.braid` file of the workspace that contains `start`.
245 pub fn discover(start: &Path) -> Result<Repo, Error> {
246 Repo::discover_with(start, Options::default())
247 }
248
249 /// [`Repo::discover`], with the store opened with `options`.
250 pub fn discover_with(start: &Path, options: Options) -> Result<Repo, Error> {
251 match locate(start)? {
252 Location::Root(dir) => Repo::open_with(&dir, options),
253 Location::Workspace { link, .. } => Repo::open_with(&link.repository, options),
254 }
255 }
256
257 /// The directory that holds `.braid`.
258 pub fn root(&self) -> &Path {
259 &self.root
260 }
261
262 /// The object store and op log.
263 pub fn store(&self) -> &Store {
264 &self.store
265 }
266
267 /// Resolves a revision to an object id: a ref name, a full id, or a
268 /// short id, the first [`MIN_SHORT_ID`] or more hex digits of an id
269 /// that no other stored object starts with. A ref wins over a short id
270 /// that is spelled the same. Hex digits may be given in either case.
271 pub fn resolve(&self, revision: &str) -> Result<ObjectId, Error> {
272 self.lookup(revision, None)
273 }
274
275 /// Resolves a revision that must name an object of `kind`, as
276 /// [`resolve`](Self::resolve) does, except that a short id only has to
277 /// be unique among the objects of that kind.
278 pub fn resolve_kind(&self, revision: &str, kind: Kind) -> Result<ObjectId, Error> {
279 let id = self.lookup(revision, Some(kind))?;
280 match self.store.stat(&id)? {
281 Some((found, _)) if found == kind => Ok(id),
282 Some((found, _)) => Err(Error::WrongKind {
283 revision: revision.to_owned(),
284 expected: kind,
285 found,
286 }),
287 None => Err(Error::UnknownRevision(revision.to_owned())),
288 }
289 }
290
291 fn lookup(&self, revision: &str, kind: Option<Kind>) -> Result<ObjectId, Error> {
292 if let Some(id) = self.store.refs()?.get(revision) {
293 return Ok(id);
294 }
295 let unknown = || Error::UnknownRevision(revision.to_owned());
296 let digits = revision.len();
297 if !(MIN_SHORT_ID..=2 * ObjectId::LEN).contains(&digits)
298 || !revision.bytes().all(|byte| byte.is_ascii_hexdigit())
299 {
300 return Err(unknown());
301 }
302 let hex = revision.to_ascii_lowercase();
303 if digits == 2 * ObjectId::LEN {
304 let id: ObjectId = hex.parse().map_err(|_| unknown())?;
305 return if self.store.contains(&id)? {
306 Ok(id)
307 } else {
308 Err(unknown())
309 };
310 }
311 let mut candidates = Vec::new();
312 for id in self.store.ids_with_prefix(&hex, CANDIDATE_LIMIT)? {
313 if let Some((found, _)) = self.store.stat(&id)? {
314 candidates.push((id, found));
315 }
316 }
317 // Objects of the kind wanted settle it, if there are any.
318 if let Some(kind) = kind
319 && candidates.iter().any(|(_, found)| *found == kind)
320 {
321 candidates.retain(|(_, found)| *found == kind);
322 }
323 match candidates.as_slice() {
324 [] => Err(unknown()),
325 [(id, _)] => Ok(*id),
326 _ => {
327 let more = candidates.len() > CANDIDATES_SHOWN;
328 candidates.truncate(CANDIDATES_SHOWN);
329 Err(Error::AmbiguousRevision {
330 prefix: revision.to_owned(),
331 candidates,
332 more,
333 })
334 }
335 }
336 }
337}
338
339/// The fewest hex digits a short id may have.
340pub const MIN_SHORT_ID: usize = 6;
341
342/// How many objects starting with a short id are looked at, at most.
343const CANDIDATE_LIMIT: usize = 64;
344
345/// How many of them an ambiguous short id lists.
346const CANDIDATES_SHOWN: usize = 5;
347
348/// The message for an ambiguous short id: each candidate with enough digits
349/// to tell it from the others, and its kind.
350fn ambiguous(prefix: &str, candidates: &[(ObjectId, Kind)], more: bool) -> String {
351 let hexes: Vec<String> = candidates.iter().map(|(id, _)| id.to_hex()).collect();
352 let mut shown = ObjectId::SHORT_HEX;
353 for (i, a) in hexes.iter().enumerate() {
354 for b in &hexes[i + 1..] {
355 let shared = a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
356 shown = shown.max(shared + 1);
357 }
358 }
359 let mut listed: Vec<String> = hexes
360 .iter()
361 .zip(candidates)
362 .map(|(hex, (_, kind))| format!("{} ({kind})", &hex[..shown.min(hex.len())]))
363 .collect();
364 if more {
365 listed.push("and more".to_owned());
366 }
367 format!(
368 "the short id {prefix:?} is ambiguous: {}; give more digits",
369 listed.join(", ")
370 )
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use braid_format::Kind;
377 use braid_store::RefUpdate;
378
379 #[test]
380 fn init_open_discover_resolve() {
381 let dir = tempfile::tempdir().unwrap();
382 let repo = Repo::init(dir.path()).unwrap();
383 assert!(matches!(Repo::init(dir.path()), Err(Error::AlreadyExists)));
384
385 let id = repo.store().put(Kind::Blob, b"hello\n").unwrap();
386 repo.store()
387 .transact("test", "set main", |_| {
388 Ok::<_, std::convert::Infallible>(vec![RefUpdate::new("main", None, Some(id))])
389 })
390 .unwrap();
391
392 let nested = dir.path().join("a/b");
393 fs::create_dir_all(&nested).unwrap();
394 let found = Repo::discover(&nested).unwrap();
395 assert_eq!(found.root(), dir.path());
396 assert_eq!(found.resolve("main").unwrap(), id);
397 assert_eq!(found.resolve(&id.to_hex()).unwrap(), id);
398 assert!(matches!(
399 found.resolve("nope"),
400 Err(Error::UnknownRevision(_))
401 ));
402 let absent = ObjectId::hash(Kind::Blob, b"absent").to_hex();
403 assert!(matches!(
404 found.resolve(&absent),
405 Err(Error::UnknownRevision(_))
406 ));
407
408 let elsewhere = tempfile::tempdir().unwrap();
409 assert!(matches!(
410 Repo::discover(elsewhere.path()),
411 Err(Error::NotFound)
412 ));
413 }
414
415 /// Two payloads whose ids, as objects of `first` and of `second`, start
416 /// with the same three bytes: six hex digits or more.
417 fn twins(first: Kind, second: Kind) -> (Vec<u8>, Vec<u8>) {
418 let start = |kind, payload: &[u8]| -> [u8; 3] {
419 let bytes = ObjectId::hash(kind, payload);
420 [
421 bytes.as_bytes()[0],
422 bytes.as_bytes()[1],
423 bytes.as_bytes()[2],
424 ]
425 };
426 let mut firsts = std::collections::HashMap::new();
427 let mut seconds = std::collections::HashMap::new();
428 for n in 0u64.. {
429 let payload = format!("twin {n}").into_bytes();
430 let (a, b) = (start(first, &payload), start(second, &payload));
431 if let Some(other) = seconds.get(&a) {
432 return (payload, Vec::clone(other));
433 }
434 if let Some(other) = firsts.get(&b) {
435 return (Vec::clone(other), payload);
436 }
437 firsts.insert(a, payload.clone());
438 seconds.insert(b, payload);
439 }
440 unreachable!("the search ends")
441 }
442
443 fn put(repo: &Repo, kind: Kind, payload: &[u8]) -> ObjectId {
444 repo.store().put(kind, payload).unwrap()
445 }
446
447 #[test]
448 fn short_ids() {
449 let dir = tempfile::tempdir().unwrap();
450 let repo = Repo::init(dir.path()).unwrap();
451 let (a, b) = twins(Kind::Blob, Kind::Blob);
452 let (a, b) = (put(&repo, Kind::Blob, &a), put(&repo, Kind::Blob, &b));
453 let (hex_a, hex_b) = (a.to_hex(), b.to_hex());
454 let shared = hex_a
455 .bytes()
456 .zip(hex_b.bytes())
457 .take_while(|(x, y)| x == y)
458 .count();
459 assert!(shared >= MIN_SHORT_ID);
460
461 // Both start with six digits: an error that lists them.
462 let err = repo.resolve(&hex_a[..MIN_SHORT_ID]).unwrap_err();
463 let Error::AmbiguousRevision {
464 candidates, more, ..
465 } = &err
466 else {
467 panic!("expected an ambiguous short id, got {err:?}");
468 };
469 let mut both = vec![(a, Kind::Blob), (b, Kind::Blob)];
470 both.sort();
471 assert_eq!(*candidates, both);
472 assert!(!more);
473 let message = err.to_string();
474 let digits = (shared + 1).max(ObjectId::SHORT_HEX);
475 for hex in [&hex_a, &hex_b] {
476 assert!(
477 message.contains(&format!("{} (blob)", &hex[..digits])),
478 "{message}"
479 );
480 }
481 // One digit more tells them apart, in either case.
482 assert_eq!(repo.resolve(&hex_a[..shared + 1]).unwrap(), a);
483 let upper = hex_b[..shared + 1].to_ascii_uppercase();
484 assert_eq!(repo.resolve(&upper).unwrap(), b);
485 assert_eq!(repo.resolve(&hex_a.to_ascii_uppercase()).unwrap(), a);
486 // Too short, not hex, or starting no id.
487 let free = ["0", "f"]
488 .into_iter()
489 .find(|digit| !hex_a.starts_with(digit))
490 .unwrap();
491 for bad in [&hex_a[..MIN_SHORT_ID - 1], "zzzzzz", &free.repeat(8)] {
492 assert!(
493 matches!(repo.resolve(bad), Err(Error::UnknownRevision(_))),
494 "{bad}"
495 );
496 }
497 // A ref spelled like a short id wins.
498 repo.store()
499 .transact("test", "a ref that looks like an id", |_| {
500 Ok::<_, std::convert::Infallible>(vec![RefUpdate::new(
501 &hex_a[..MIN_SHORT_ID],
502 None,
503 Some(b),
504 )])
505 })
506 .unwrap();
507 assert_eq!(repo.resolve(&hex_a[..MIN_SHORT_ID]).unwrap(), b);
508
509 // A short id shared by objects of two kinds names the one of the
510 // kind wanted.
511 let (blob, changeset) = twins(Kind::Blob, Kind::Changeset);
512 let blob = put(&repo, Kind::Blob, &blob);
513 let changeset = put(&repo, Kind::Changeset, &changeset);
514 let short = &blob.to_hex()[..MIN_SHORT_ID];
515 assert!(matches!(
516 repo.resolve(short),
517 Err(Error::AmbiguousRevision { .. })
518 ));
519 assert_eq!(
520 repo.resolve_kind(short, Kind::Changeset).unwrap(),
521 changeset
522 );
523 assert_eq!(repo.resolve_kind(short, Kind::Blob).unwrap(), blob);
524 let err = repo
525 .resolve_kind(&blob.to_hex(), Kind::Changeset)
526 .unwrap_err();
527 assert!(
528 matches!(
529 err,
530 Error::WrongKind {
531 expected: Kind::Changeset,
532 found: Kind::Blob,
533 ..
534 }
535 ),
536 "{err:?}"
537 );
538 }
539
540 #[test]
541 fn discover_through_a_workspace_file() {
542 let repo_dir = tempfile::tempdir().unwrap();
543 Repo::init(repo_dir.path()).unwrap();
544 let elsewhere = tempfile::tempdir().unwrap();
545 let workspace = elsewhere.path().join("agent-1");
546 fs::create_dir_all(workspace.join("src/deep")).unwrap();
547 let link = WorkspaceLink {
548 repository: repo_dir.path().to_path_buf(),
549 name: "agent-1".to_owned(),
550 };
551 fs::write(workspace.join(DIR), link.encode()).unwrap();
552
553 let found = Repo::discover(&workspace.join("src/deep")).unwrap();
554 assert_eq!(found.root(), repo_dir.path());
555 match locate(&workspace.join("src")).unwrap() {
556 Location::Workspace { dir, link: read } => {
557 assert_eq!(dir, workspace);
558 assert_eq!(read, link);
559 }
560 other => panic!("expected a workspace, got {other:?}"),
561 }
562
563 // A damaged file is an error, not a reason to keep looking.
564 fs::write(workspace.join(DIR), b"something else\n").unwrap();
565 assert!(matches!(
566 Repo::discover(&workspace),
567 Err(Error::BadWorkspaceFile { .. })
568 ));
569 }
570}