utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | d5697ef85ee63c21d510b0bd21b566b9f0b42ec5cd73db67ab9d1ceaddb2d650 |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:56 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:56 +02:00 |
| Parents | bd46a4a90e4e |
8 files changed
modified Cargo.lock +2 −0
| @@ -401,6 +401,7 @@ | ||
| 401 | 401 | "anyhow", |
| 402 | 402 | "clap", |
| 403 | 403 | "elffuss-braid-format", |
| 404 | + "elffuss-braid-git", | |
| 404 | 405 | "elffuss-braid-repo", |
| 405 | 406 | "elffuss-braid-store", |
| 406 | 407 | "serde_json", |
| @@ -430,6 +431,7 @@ | ||
| 430 | 431 | version = "0.0.1" |
| 431 | 432 | dependencies = [ |
| 432 | 433 | "elffuss-braid-format", |
| 434 | + "elffuss-braid-git", | |
| 433 | 435 | "elffuss-braid-store", |
| 434 | 436 | "tempfile", |
| 435 | 437 | "thiserror", |
modified Cargo.toml +1 −0
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | braid-format = { package = "elffuss-braid-format", path = "crates/format" } |
| 17 | 17 | braid-store = { package = "elffuss-braid-store", path = "crates/store" } |
| 18 | 18 | braid-repo = { package = "elffuss-braid-repo", path = "crates/repo" } |
| 19 | +braid-git = { package = "elffuss-braid-git", path = "crates/git" } | |
| 19 | 20 | anyhow = "1.0" |
| 20 | 21 | blake3 = "1.8" |
| 21 | 22 | clap = { version = "4.6", features = ["derive", "env"] } |
modified crates/cli/Cargo.toml +1 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | |
| 16 | 16 | [dependencies] |
| 17 | 17 | braid-format.workspace = true |
| 18 | +braid-git.workspace = true | |
| 18 | 19 | braid-repo.workspace = true |
| 19 | 20 | braid-store.workspace = true |
| 20 | 21 | anyhow.workspace = true |
modified crates/cli/src/main.rs +303 −1
| @@ -9,7 +9,10 @@ | ||
| 9 | 9 | use std::process::ExitCode; |
| 10 | 10 | |
| 11 | 11 | use anyhow::{Context, Result, bail}; |
| 12 | -use braid_format::{IdHasher, Kind, ObjectId, Objects}; | |
| 12 | +use braid_format::changeset::decode_change_list; | |
| 13 | +use braid_format::{ | |
| 14 | + Change, ChangeOp, Changes, Changeset, IdHasher, Kind, ObjectId, Objects, Signature, | |
| 15 | +}; | |
| 13 | 16 | use braid_repo::Repo; |
| 14 | 17 | use braid_store::{FsckReport, Operation, RefUpdate}; |
| 15 | 18 | use clap::{Parser, Subcommand}; |
| @@ -71,6 +74,26 @@ | ||
| 71 | 74 | }, |
| 72 | 75 | /// Revert the newest operation that is not already undone. |
| 73 | 76 | Undo, |
| 77 | + /// Show history, following first parents. | |
| 78 | + Log { | |
| 79 | + /// Where to start: a ref name or a full changeset id. | |
| 80 | + #[arg(default_value = "main")] | |
| 81 | + revision: String, | |
| 82 | + /// How many changesets to show. | |
| 83 | + #[arg(short = 'n', long, default_value_t = 20)] | |
| 84 | + limit: usize, | |
| 85 | + }, | |
| 86 | + /// Show one changeset: parents, root, signatures, message, changed paths. | |
| 87 | + Show { | |
| 88 | + /// A ref name or a full changeset id. | |
| 89 | + #[arg(default_value = "main")] | |
| 90 | + revision: String, | |
| 91 | + }, | |
| 92 | + /// Import from and export to git repositories. | |
| 93 | + Git { | |
| 94 | + #[command(subcommand)] | |
| 95 | + action: GitAction, | |
| 96 | + }, | |
| 74 | 97 | /// Check every record, index, op log entry and ref of the store. |
| 75 | 98 | Fsck, |
| 76 | 99 | } |
| @@ -95,6 +118,25 @@ | ||
| 95 | 118 | }, |
| 96 | 119 | } |
| 97 | 120 | |
| 121 | +#[derive(Debug, Subcommand)] | |
| 122 | +enum GitAction { | |
| 123 | + /// Import every branch and tag of a git repository. Running it again | |
| 124 | + /// imports only what is new. | |
| 125 | + Import { | |
| 126 | + /// The git repository (a working tree or a bare repository). | |
| 127 | + path: PathBuf, | |
| 128 | + }, | |
| 129 | + /// Write braid refs, and everything they reach, into an existing git | |
| 130 | + /// repository. Git refs of the same names are overwritten. | |
| 131 | + Export { | |
| 132 | + /// The git repository. | |
| 133 | + path: PathBuf, | |
| 134 | + /// A braid ref to export; repeat for several (default: all). | |
| 135 | + #[arg(long = "ref", value_name = "NAME")] | |
| 136 | + refs: Vec<String>, | |
| 137 | + }, | |
| 138 | +} | |
| 139 | + | |
| 98 | 140 | #[derive(Debug, Subcommand)] |
| 99 | 141 | enum OpAction { |
| 100 | 142 | /// Show the newest operations, newest first. |
| @@ -127,6 +169,14 @@ | ||
| 127 | 169 | action: OpAction::Log { limit }, |
| 128 | 170 | } => op_log(cli, *limit), |
| 129 | 171 | Command::Undo => undo(cli), |
| 172 | + Command::Log { revision, limit } => log(cli, revision, *limit), | |
| 173 | + Command::Show { revision } => show(cli, revision), | |
| 174 | + Command::Git { | |
| 175 | + action: GitAction::Import { path }, | |
| 176 | + } => git_import(cli, path), | |
| 177 | + Command::Git { | |
| 178 | + action: GitAction::Export { path, refs }, | |
| 179 | + } => git_export(cli, path, refs), | |
| 130 | 180 | Command::Fsck => fsck(cli), |
| 131 | 181 | } |
| 132 | 182 | } |
| @@ -448,6 +498,258 @@ | ||
| 448 | 498 | }) |
| 449 | 499 | } |
| 450 | 500 | |
| 501 | +fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> { | |
| 502 | + match repo.store().get(id)? { | |
| 503 | + Some((Kind::Changeset, bytes)) => { | |
| 504 | + Ok(Changeset::decode(&bytes) | |
| 505 | + .with_context(|| format!("changeset {id} does not decode"))?) | |
| 506 | + } | |
| 507 | + Some((kind, _)) => bail!("{id} is a {kind}, not a changeset"), | |
| 508 | + None => bail!("changeset {id} is not in the store"), | |
| 509 | + } | |
| 510 | +} | |
| 511 | + | |
| 512 | +fn read_changes(repo: &Repo, changeset: &Changeset) -> Result<Vec<Change>> { | |
| 513 | + match &changeset.changes { | |
| 514 | + Changes::Inline(changes) => Ok(changes.clone()), | |
| 515 | + Changes::External { list, .. } => { | |
| 516 | + let Some((_, bytes)) = repo.store().get(list)? else { | |
| 517 | + bail!("change list {list} is not in the store"); | |
| 518 | + }; | |
| 519 | + Ok(decode_change_list(&bytes) | |
| 520 | + .with_context(|| format!("change list {list} does not decode"))?) | |
| 521 | + } | |
| 522 | + } | |
| 523 | +} | |
| 524 | + | |
| 525 | +fn signature_json(signature: &Signature) -> Value { | |
| 526 | + json!({ | |
| 527 | + "name": String::from_utf8_lossy(&signature.name), | |
| 528 | + "email": String::from_utf8_lossy(&signature.email), | |
| 529 | + "seconds": signature.seconds, | |
| 530 | + "offset_minutes": signature.offset_minutes, | |
| 531 | + "time": format_signature_time(signature), | |
| 532 | + }) | |
| 533 | +} | |
| 534 | + | |
| 535 | +fn changeset_json(id: &ObjectId, changeset: &Changeset) -> Value { | |
| 536 | + json!({ | |
| 537 | + "id": id.to_hex(), | |
| 538 | + "parents": changeset.parents.iter().map(ObjectId::to_hex).collect::<Vec<_>>(), | |
| 539 | + "root": changeset.root.to_hex(), | |
| 540 | + "author": signature_json(&changeset.author), | |
| 541 | + "committer": signature_json(&changeset.committer), | |
| 542 | + "message": String::from_utf8_lossy(&changeset.message), | |
| 543 | + "extras": changeset.extras.iter().map(|(k, v)| json!([ | |
| 544 | + String::from_utf8_lossy(k), String::from_utf8_lossy(v) | |
| 545 | + ])).collect::<Vec<_>>(), | |
| 546 | + "git_origin": changeset.git_origin.map(|id| id.to_hex()), | |
| 547 | + }) | |
| 548 | +} | |
| 549 | + | |
| 550 | +fn subject(message: &[u8]) -> String { | |
| 551 | + let text = String::from_utf8_lossy(message); | |
| 552 | + text.lines() | |
| 553 | + .find(|line| !line.trim().is_empty()) | |
| 554 | + .unwrap_or("") | |
| 555 | + .trim() | |
| 556 | + .to_owned() | |
| 557 | +} | |
| 558 | + | |
| 559 | +fn log(cli: &Cli, revision: &str, limit: usize) -> Result<ExitCode> { | |
| 560 | + let repo = open_repo(cli)?; | |
| 561 | + let mut next = Some(repo.resolve(revision)?); | |
| 562 | + let mut entries = Vec::new(); | |
| 563 | + while let Some(id) = next { | |
| 564 | + if entries.len() == limit { | |
| 565 | + break; | |
| 566 | + } | |
| 567 | + let changeset = read_changeset(&repo, &id)?; | |
| 568 | + next = changeset.parents.first().copied(); | |
| 569 | + entries.push((id, changeset)); | |
| 570 | + } | |
| 571 | + if cli.json { | |
| 572 | + print_json(&Value::Array( | |
| 573 | + entries | |
| 574 | + .iter() | |
| 575 | + .map(|(id, changeset)| changeset_json(id, changeset)) | |
| 576 | + .collect(), | |
| 577 | + ))?; | |
| 578 | + } else { | |
| 579 | + let mut out = io::stdout().lock(); | |
| 580 | + for (id, changeset) in &entries { | |
| 581 | + writeln!( | |
| 582 | + out, | |
| 583 | + "{} {} {} {}", | |
| 584 | + id.short(), | |
| 585 | + format_signature_time(&changeset.author), | |
| 586 | + String::from_utf8_lossy(&changeset.author.name), | |
| 587 | + subject(&changeset.message) | |
| 588 | + )?; | |
| 589 | + } | |
| 590 | + } | |
| 591 | + Ok(ExitCode::SUCCESS) | |
| 592 | +} | |
| 593 | + | |
| 594 | +fn change_json(change: &Change) -> Value { | |
| 595 | + let path = String::from_utf8_lossy(&change.path); | |
| 596 | + match &change.op { | |
| 597 | + ChangeOp::Delete => json!({ "path": path, "op": "delete" }), | |
| 598 | + ChangeOp::File { blob, size } => { | |
| 599 | + json!({ "path": path, "op": "file", "blob": blob.to_hex(), "size": size }) | |
| 600 | + } | |
| 601 | + ChangeOp::Executable { blob, size } => { | |
| 602 | + json!({ "path": path, "op": "executable", "blob": blob.to_hex(), "size": size }) | |
| 603 | + } | |
| 604 | + ChangeOp::Symlink { blob, size } => { | |
| 605 | + json!({ "path": path, "op": "symlink", "blob": blob.to_hex(), "size": size }) | |
| 606 | + } | |
| 607 | + ChangeOp::Gitlink { commit } => json!({ | |
| 608 | + "path": path, | |
| 609 | + "op": "gitlink", | |
| 610 | + "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(), | |
| 611 | + }), | |
| 612 | + } | |
| 613 | +} | |
| 614 | + | |
| 615 | +fn show(cli: &Cli, revision: &str) -> Result<ExitCode> { | |
| 616 | + let repo = open_repo(cli)?; | |
| 617 | + let id = repo.resolve(revision)?; | |
| 618 | + let changeset = read_changeset(&repo, &id)?; | |
| 619 | + let changes = read_changes(&repo, &changeset)?; | |
| 620 | + if cli.json { | |
| 621 | + let mut value = changeset_json(&id, &changeset); | |
| 622 | + value["changes"] = Value::Array(changes.iter().map(change_json).collect()); | |
| 623 | + print_json(&value)?; | |
| 624 | + return Ok(ExitCode::SUCCESS); | |
| 625 | + } | |
| 626 | + let mut out = io::stdout().lock(); | |
| 627 | + writeln!(out, "changeset {id}")?; | |
| 628 | + for parent in &changeset.parents { | |
| 629 | + writeln!(out, "parent {parent}")?; | |
| 630 | + } | |
| 631 | + writeln!(out, "root {}", changeset.root)?; | |
| 632 | + for (label, signature) in [ | |
| 633 | + ("author", &changeset.author), | |
| 634 | + ("committer", &changeset.committer), | |
| 635 | + ] { | |
| 636 | + writeln!( | |
| 637 | + out, | |
| 638 | + "{label:<9} {} <{}> {}", | |
| 639 | + String::from_utf8_lossy(&signature.name), | |
| 640 | + String::from_utf8_lossy(&signature.email), | |
| 641 | + format_signature_time(signature) | |
| 642 | + )?; | |
| 643 | + } | |
| 644 | + writeln!(out)?; | |
| 645 | + for line in String::from_utf8_lossy(&changeset.message).lines() { | |
| 646 | + writeln!(out, " {line}")?; | |
| 647 | + } | |
| 648 | + writeln!(out)?; | |
| 649 | + for change in &changes { | |
| 650 | + let op = match change.op { | |
| 651 | + ChangeOp::Delete => "delete", | |
| 652 | + ChangeOp::File { .. } => "file", | |
| 653 | + ChangeOp::Executable { .. } => "exec", | |
| 654 | + ChangeOp::Symlink { .. } => "link", | |
| 655 | + ChangeOp::Gitlink { .. } => "gitlink", | |
| 656 | + }; | |
| 657 | + writeln!(out, "{op:<8} {}", String::from_utf8_lossy(&change.path))?; | |
| 658 | + } | |
| 659 | + Ok(ExitCode::SUCCESS) | |
| 660 | +} | |
| 661 | + | |
| 662 | +fn git_import(cli: &Cli, path: &Path) -> Result<ExitCode> { | |
| 663 | + let repo = open_repo(cli)?; | |
| 664 | + let import = repo.git_import(path, &cli.agent)?; | |
| 665 | + let report = &import.report; | |
| 666 | + let refs: Vec<Value> = report | |
| 667 | + .refs | |
| 668 | + .iter() | |
| 669 | + .map(|r| { | |
| 670 | + json!({ | |
| 671 | + "git": String::from_utf8_lossy(&r.name), | |
| 672 | + "braid": braid_repo::braid_ref_for_git(&r.name), | |
| 673 | + "id": r.braid.to_hex(), | |
| 674 | + }) | |
| 675 | + }) | |
| 676 | + .collect(); | |
| 677 | + if cli.json { | |
| 678 | + print_json(&json!({ | |
| 679 | + "commits": report.commits, | |
| 680 | + "trees": report.trees, | |
| 681 | + "raw_trees": report.raw_trees, | |
| 682 | + "blobs": report.blobs, | |
| 683 | + "tags": report.tags, | |
| 684 | + "refs": refs, | |
| 685 | + "operation": import.operation.as_ref().map(|op| op.seq), | |
| 686 | + }))?; | |
| 687 | + } else { | |
| 688 | + println!( | |
| 689 | + "Imported {} commits, {} trees, {} blobs, {} tags; {} refs", | |
| 690 | + report.commits, | |
| 691 | + report.trees, | |
| 692 | + report.blobs, | |
| 693 | + report.tags, | |
| 694 | + report.refs.len() | |
| 695 | + ); | |
| 696 | + if import.operation.is_none() { | |
| 697 | + println!("Nothing changed."); | |
| 698 | + } | |
| 699 | + } | |
| 700 | + Ok(ExitCode::SUCCESS) | |
| 701 | +} | |
| 702 | + | |
| 703 | +fn git_export(cli: &Cli, path: &Path, names: &[String]) -> Result<ExitCode> { | |
| 704 | + let repo = open_repo(cli)?; | |
| 705 | + let report = repo.git_export(path, names)?; | |
| 706 | + if cli.json { | |
| 707 | + print_json(&json!({ | |
| 708 | + "commits": report.commits, | |
| 709 | + "trees": report.trees, | |
| 710 | + "blobs": report.blobs, | |
| 711 | + "tags": report.tags, | |
| 712 | + "refs": report.refs.iter().map(|(name, oid)| json!({ | |
| 713 | + "name": String::from_utf8_lossy(name), | |
| 714 | + "id": oid.to_string(), | |
| 715 | + })).collect::<Vec<_>>(), | |
| 716 | + }))?; | |
| 717 | + } else { | |
| 718 | + println!( | |
| 719 | + "Wrote {} commits, {} trees, {} blobs, {} tags; {} refs", | |
| 720 | + report.commits, | |
| 721 | + report.trees, | |
| 722 | + report.blobs, | |
| 723 | + report.tags, | |
| 724 | + report.refs.len() | |
| 725 | + ); | |
| 726 | + } | |
| 727 | + Ok(ExitCode::SUCCESS) | |
| 728 | +} | |
| 729 | + | |
| 730 | +/// Formats a signature's time in its own offset: `YYYY-MM-DD HH:MM ±HHMM`. | |
| 731 | +fn format_signature_time(signature: &Signature) -> String { | |
| 732 | + let local = signature | |
| 733 | + .seconds | |
| 734 | + .saturating_add(signature.offset_minutes.saturating_mul(60)); | |
| 735 | + let days = local.div_euclid(86_400); | |
| 736 | + let of_day = local.rem_euclid(86_400); | |
| 737 | + let (year, month, day) = civil_from_days(days); | |
| 738 | + let sign = if signature.offset_minutes < 0 { | |
| 739 | + '-' | |
| 740 | + } else { | |
| 741 | + '+' | |
| 742 | + }; | |
| 743 | + let offset = signature.offset_minutes.unsigned_abs(); | |
| 744 | + format!( | |
| 745 | + "{year:04}-{month:02}-{day:02} {:02}:{:02} {sign}{:02}{:02}", | |
| 746 | + of_day / 3600, | |
| 747 | + of_day % 3600 / 60, | |
| 748 | + offset / 60, | |
| 749 | + offset % 60 | |
| 750 | + ) | |
| 751 | +} | |
| 752 | + | |
| 451 | 753 | /// Formats milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SS UTC`. |
| 452 | 754 | fn format_time(time_ms: i64) -> String { |
| 453 | 755 | let seconds = time_ms.div_euclid(1000); |
modified crates/cli/tests/cli.rs +88 −0
| @@ -175,3 +175,91 @@ | ||
| 175 | 175 | let err = String::from_utf8(out.stderr).unwrap(); |
| 176 | 176 | assert!(err.contains("not inside a braid repository"), "{err}"); |
| 177 | 177 | } |
| 178 | + | |
| 179 | +/// Runs git with a fixed identity and dates, ignoring the user's config. | |
| 180 | +fn git(dir: &std::path::Path, args: &[&str]) -> String { | |
| 181 | + let out = Command::new("git") | |
| 182 | + .current_dir(dir) | |
| 183 | + .args(args) | |
| 184 | + .env("GIT_CONFIG_GLOBAL", "/dev/null") | |
| 185 | + .env("GIT_CONFIG_NOSYSTEM", "1") | |
| 186 | + .env("GIT_AUTHOR_NAME", "Ada") | |
| 187 | + .env("GIT_AUTHOR_EMAIL", "ada@example.org") | |
| 188 | + .env("GIT_COMMITTER_NAME", "Ada") | |
| 189 | + .env("GIT_COMMITTER_EMAIL", "ada@example.org") | |
| 190 | + .env("GIT_AUTHOR_DATE", "1700000000 +0100") | |
| 191 | + .env("GIT_COMMITTER_DATE", "1700000000 +0100") | |
| 192 | + .output() | |
| 193 | + .unwrap(); | |
| 194 | + assert!( | |
| 195 | + out.status.success(), | |
| 196 | + "git {args:?}: {}", | |
| 197 | + String::from_utf8_lossy(&out.stderr) | |
| 198 | + ); | |
| 199 | + String::from_utf8(out.stdout).unwrap() | |
| 200 | +} | |
| 201 | + | |
| 202 | +#[test] | |
| 203 | +fn git_import_log_show_export() { | |
| 204 | + let work = tempfile::tempdir().unwrap(); | |
| 205 | + let src = work.path().join("src"); | |
| 206 | + std::fs::create_dir(&src).unwrap(); | |
| 207 | + git(&src, &["init", "-q", "-b", "main"]); | |
| 208 | + std::fs::write(src.join("README.md"), "hello\n").unwrap(); | |
| 209 | + git(&src, &["add", "README.md"]); | |
| 210 | + git(&src, &["commit", "-q", "-m", "First"]); | |
| 211 | + std::fs::create_dir(src.join("src")).unwrap(); | |
| 212 | + std::fs::write(src.join("src/lib.rs"), "pub fn f() {}\n").unwrap(); | |
| 213 | + git(&src, &["add", "src/lib.rs"]); | |
| 214 | + git(&src, &["commit", "-q", "-m", "Second\n\nWith a body."]); | |
| 215 | + git(&src, &["tag", "-a", "v1", "-m", "Version 1"]); | |
| 216 | + | |
| 217 | + let repo = work.path().join("braid"); | |
| 218 | + assert!( | |
| 219 | + braid() | |
| 220 | + .arg("init") | |
| 221 | + .arg(&repo) | |
| 222 | + .output() | |
| 223 | + .unwrap() | |
| 224 | + .status | |
| 225 | + .success() | |
| 226 | + ); | |
| 227 | + let import = run_json(braid_in(&repo).args(["git", "import"]).arg(&src)); | |
| 228 | + assert_eq!(import["commits"], 2); | |
| 229 | + assert_eq!(import["tags"], 1); | |
| 230 | + // Importing again finds nothing new and moves no ref. | |
| 231 | + let again = run_json(braid_in(&repo).args(["git", "import"]).arg(&src)); | |
| 232 | + assert_eq!(again["commits"], 0); | |
| 233 | + assert!(again["operation"].is_null()); | |
| 234 | + | |
| 235 | + let log = run_json(braid_in(&repo).args(["log", "main"])); | |
| 236 | + let log = log.as_array().unwrap(); | |
| 237 | + assert_eq!(log.len(), 2); | |
| 238 | + assert_eq!(log[0]["message"], "Second\n\nWith a body.\n"); | |
| 239 | + assert_eq!(log[0]["author"]["email"], "ada@example.org"); | |
| 240 | + assert_eq!(log[0]["author"]["offset_minutes"], 60); | |
| 241 | + | |
| 242 | + let show = run_json(braid_in(&repo).args(["show", "main"])); | |
| 243 | + assert_eq!(show["changes"][0]["path"], "src/lib.rs"); | |
| 244 | + assert_eq!(show["changes"][0]["op"], "file"); | |
| 245 | + assert!(show["git_origin"].is_string()); | |
| 246 | + | |
| 247 | + // Export into an empty repository: the same commit and tag ids. | |
| 248 | + let mirror = work.path().join("mirror.git"); | |
| 249 | + std::fs::create_dir(&mirror).unwrap(); | |
| 250 | + git(&mirror, &["init", "-q", "--bare"]); | |
| 251 | + run_json(braid_in(&repo).args(["git", "export"]).arg(&mirror)); | |
| 252 | + for name in ["refs/heads/main", "refs/tags/v1"] { | |
| 253 | + assert_eq!( | |
| 254 | + git(&src, &["rev-parse", name]), | |
| 255 | + git(&mirror, &["rev-parse", name]), | |
| 256 | + "{name}" | |
| 257 | + ); | |
| 258 | + } | |
| 259 | + | |
| 260 | + // The import is one operation: undo takes every ref back. | |
| 261 | + run_json(braid_in(&repo).arg("undo")); | |
| 262 | + let refs = run_json(braid_in(&repo).arg("refs")); | |
| 263 | + assert!(refs["refs"].as_object().unwrap().is_empty()); | |
| 264 | + assert_eq!(run_json(braid_in(&repo).arg("fsck"))["clean"], true); | |
| 265 | +} |
modified crates/repo/Cargo.toml +1 −0
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | [dependencies] |
| 16 | 16 | braid-format.workspace = true |
| 17 | 17 | braid-store.workspace = true |
| 18 | +braid-git.workspace = true | |
| 18 | 19 | thiserror = "2" |
| 19 | 20 | |
| 20 | 21 | [dev-dependencies] |
added crates/repo/src/git.rs +185 −0
| @@ -0,0 +1,185 @@ | ||
| 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 | + | |
| 10 | +use std::convert::Infallible; | |
| 11 | +use std::path::Path; | |
| 12 | + | |
| 13 | +use braid_format::{Kind, ObjectId, Objects}; | |
| 14 | +use braid_git::{GitMap, ImportOptions, ImportReport, RefTarget, WriteReport}; | |
| 15 | +use braid_store::{Operation, RefUpdate, TransactError}; | |
| 16 | + | |
| 17 | +use crate::{Error, Repo}; | |
| 18 | + | |
| 19 | +/// The ref that points at the current git map. | |
| 20 | +pub const MAP_REF: &str = "braid/git-map"; | |
| 21 | + | |
| 22 | +/// The braid ref for a git ref: branches keep their short name, tags go under | |
| 23 | +/// `tags/`, and any other ref keeps its full name under `git/`. | |
| 24 | +pub fn braid_ref_for_git(name: &[u8]) -> Option<String> { | |
| 25 | + let name = std::str::from_utf8(name).ok()?; | |
| 26 | + Some(if let Some(branch) = name.strip_prefix("refs/heads/") { | |
| 27 | + branch.to_owned() | |
| 28 | + } else if let Some(tag) = name.strip_prefix("refs/tags/") { | |
| 29 | + format!("tags/{tag}") | |
| 30 | + } else { | |
| 31 | + format!("git/{name}") | |
| 32 | + }) | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// The git ref for a braid ref, or `None` for braid's own refs. | |
| 36 | +pub fn git_ref_for_braid(name: &str) -> Option<String> { | |
| 37 | + if name.starts_with("braid/") { | |
| 38 | + None | |
| 39 | + } else if let Some(tag) = name.strip_prefix("tags/") { | |
| 40 | + Some(format!("refs/tags/{tag}")) | |
| 41 | + } else if let Some(full) = name.strip_prefix("git/") { | |
| 42 | + Some(full.to_owned()) | |
| 43 | + } else { | |
| 44 | + Some(format!("refs/heads/{name}")) | |
| 45 | + } | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// What `git_import` did. | |
| 49 | +#[derive(Debug)] | |
| 50 | +pub struct GitImport { | |
| 51 | + /// What the bridge imported. | |
| 52 | + pub report: ImportReport, | |
| 53 | + /// The operation that moved the refs, or `None` when nothing changed. | |
| 54 | + pub operation: Option<Operation>, | |
| 55 | +} | |
| 56 | + | |
| 57 | +fn store_error(err: TransactError<Infallible>) -> Error { | |
| 58 | + match err { | |
| 59 | + TransactError::Store(err) => Error::Store(err), | |
| 60 | + TransactError::Aborted(never) => match never {}, | |
| 61 | + } | |
| 62 | +} | |
| 63 | + | |
| 64 | +impl Repo { | |
| 65 | + /// The current git map, empty if nothing was imported yet. | |
| 66 | + pub fn git_map(&self) -> Result<GitMap, Error> { | |
| 67 | + let Some(id) = self.store.refs()?.get(MAP_REF) else { | |
| 68 | + return Ok(GitMap::new()); | |
| 69 | + }; | |
| 70 | + let Some((_, bytes)) = self.store.get(&id)? else { | |
| 71 | + return Err(Error::UnknownRevision(MAP_REF.to_owned())); | |
| 72 | + }; | |
| 73 | + GitMap::from_bytes(&bytes).map_err(Error::GitMap) | |
| 74 | + } | |
| 75 | + | |
| 76 | + /// Imports every branch and tag of the git repository at `git_repo`, | |
| 77 | + /// incrementally, and points the matching braid refs at them. | |
| 78 | + pub fn git_import(&self, git_repo: &Path, agent: &str) -> Result<GitImport, Error> { | |
| 79 | + let mut map = self.git_map()?; | |
| 80 | + let report = braid_git::import(git_repo, &self.store, &mut map, &ImportOptions::default())?; | |
| 81 | + let map_id = self.store.put(Kind::Derived, &map.to_bytes())?; | |
| 82 | + self.store.sync()?; | |
| 83 | + | |
| 84 | + let mut wanted: Vec<(String, ObjectId)> = report | |
| 85 | + .refs | |
| 86 | + .iter() | |
| 87 | + .filter_map(|r| braid_ref_for_git(&r.name).map(|name| (name, r.braid))) | |
| 88 | + .collect(); | |
| 89 | + wanted.push((MAP_REF.to_owned(), map_id)); | |
| 90 | + | |
| 91 | + let current = self.store.refs()?; | |
| 92 | + if wanted | |
| 93 | + .iter() | |
| 94 | + .all(|(name, id)| current.get(name) == Some(*id)) | |
| 95 | + { | |
| 96 | + return Ok(GitImport { | |
| 97 | + report, | |
| 98 | + operation: None, | |
| 99 | + }); | |
| 100 | + } | |
| 101 | + let description = format!("git import of {} refs", wanted.len() - 1); | |
| 102 | + let operation = self | |
| 103 | + .store | |
| 104 | + .transact(agent, &description, |refs| { | |
| 105 | + Ok(wanted | |
| 106 | + .iter() | |
| 107 | + .filter(|(name, id)| refs.get(name) != Some(*id)) | |
| 108 | + .map(|(name, id)| RefUpdate::new(name.clone(), refs.get(name), Some(*id))) | |
| 109 | + .collect()) | |
| 110 | + }) | |
| 111 | + .map_err(store_error)?; | |
| 112 | + Ok(GitImport { | |
| 113 | + report, | |
| 114 | + operation: Some(operation), | |
| 115 | + }) | |
| 116 | + } | |
| 117 | + | |
| 118 | + /// Writes the given braid refs (all of them when `names` is empty) into | |
| 119 | + /// the git repository at `git_repo`, which must exist. Existing git refs | |
| 120 | + /// of the same names are overwritten. | |
| 121 | + pub fn git_export(&self, git_repo: &Path, names: &[String]) -> Result<WriteReport, Error> { | |
| 122 | + let map = self.git_map()?; | |
| 123 | + let refs = self.store.refs()?; | |
| 124 | + let mut updates = Vec::new(); | |
| 125 | + for (name, id) in refs.iter() { | |
| 126 | + if !names.is_empty() && !names.iter().any(|n| n == name) { | |
| 127 | + continue; | |
| 128 | + } | |
| 129 | + let Some(git_name) = git_ref_for_braid(name) else { | |
| 130 | + continue; | |
| 131 | + }; | |
| 132 | + let target = match self.store.stat(&id)? { | |
| 133 | + Some((Kind::Changeset, _)) => RefTarget::Changeset(id), | |
| 134 | + Some((Kind::Blob, _)) => match map.git_tag(&id) { | |
| 135 | + Some(tag) => RefTarget::Git(tag), | |
| 136 | + None => { | |
| 137 | + return Err(Error::NotExportable { | |
| 138 | + name: name.to_owned(), | |
| 139 | + }); | |
| 140 | + } | |
| 141 | + }, | |
| 142 | + _ => { | |
| 143 | + return Err(Error::NotExportable { | |
| 144 | + name: name.to_owned(), | |
| 145 | + }); | |
| 146 | + } | |
| 147 | + }; | |
| 148 | + updates.push(braid_git::RefUpdate { | |
| 149 | + name: git_name.into_bytes(), | |
| 150 | + target, | |
| 151 | + }); | |
| 152 | + } | |
| 153 | + for name in names { | |
| 154 | + if refs.get(name).is_none() { | |
| 155 | + return Err(Error::UnknownRevision(name.clone())); | |
| 156 | + } | |
| 157 | + } | |
| 158 | + Ok(braid_git::write_to_repo( | |
| 159 | + git_repo, | |
| 160 | + &self.store, | |
| 161 | + &map, | |
| 162 | + &updates, | |
| 163 | + )?) | |
| 164 | + } | |
| 165 | +} | |
| 166 | + | |
| 167 | +#[cfg(test)] | |
| 168 | +mod tests { | |
| 169 | + use super::*; | |
| 170 | + | |
| 171 | + #[test] | |
| 172 | + fn ref_names_round_trip() { | |
| 173 | + for (git, braid) in [ | |
| 174 | + ("refs/heads/main", "main"), | |
| 175 | + ("refs/heads/feature/x", "feature/x"), | |
| 176 | + ("refs/tags/v1.0", "tags/v1.0"), | |
| 177 | + ("refs/notes/commits", "git/refs/notes/commits"), | |
| 178 | + ] { | |
| 179 | + assert_eq!(braid_ref_for_git(git.as_bytes()).as_deref(), Some(braid)); | |
| 180 | + assert_eq!(git_ref_for_braid(braid).as_deref(), Some(git)); | |
| 181 | + } | |
| 182 | + assert_eq!(git_ref_for_braid(MAP_REF), None); | |
| 183 | + assert_eq!(braid_ref_for_git(b"refs/heads/\xff"), None); | |
| 184 | + } | |
| 185 | +} |
modified crates/repo/src/lib.rs +16 −0
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | |
| 11 | 11 | #![forbid(unsafe_code)] |
| 12 | 12 | |
| 13 | +mod git; | |
| 14 | + | |
| 13 | 15 | use std::fs; |
| 14 | 16 | use std::io; |
| 15 | 17 | use std::path::{Path, PathBuf}; |
| @@ -17,6 +19,8 @@ | ||
| 17 | 19 | use braid_format::{ObjectId, Objects}; |
| 18 | 20 | use braid_store::{Options, Store}; |
| 19 | 21 | |
| 22 | +pub use git::{GitImport, MAP_REF, braid_ref_for_git, git_ref_for_braid}; | |
| 23 | + | |
| 20 | 24 | /// Name of the directory that holds a repository's data. |
| 21 | 25 | pub const DIR: &str = ".braid"; |
| 22 | 26 | |
| @@ -39,6 +43,18 @@ | ||
| 39 | 43 | /// The store failed. |
| 40 | 44 | #[error(transparent)] |
| 41 | 45 | Store(#[from] braid_store::Error), |
| 46 | + /// The git bridge failed. | |
| 47 | + #[error(transparent)] | |
| 48 | + Git(#[from] braid_git::Error), | |
| 49 | + /// The stored git map does not decode. | |
| 50 | + #[error("the stored git map is damaged: {0}")] | |
| 51 | + GitMap(braid_format::DecodeError), | |
| 52 | + /// A ref names an object the git bridge cannot export. | |
| 53 | + #[error("ref {name:?} points at an object that has no git form")] | |
| 54 | + NotExportable { | |
| 55 | + /// The ref. | |
| 56 | + name: String, | |
| 57 | + }, | |
| 42 | 58 | /// The file system failed. |
| 43 | 59 | #[error(transparent)] |
| 44 | 60 | Io(#[from] io::Error), |