| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `braid`, the command-line tool. |
| 5 | |
| 6 | mod sync; |
| 7 | mod work; |
| 8 | |
| 9 | use std::collections::HashMap; |
| 10 | use std::fs::File; |
| 11 | use std::io::{self, Read, Write}; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::process::ExitCode; |
| 14 | |
| 15 | use anyhow::{Context, Result, bail}; |
| 16 | use braid_format::changeset::decode_change_list; |
| 17 | use braid_format::{ |
| 18 | Change, ChangeOp, Changes, Changeset, IdHasher, Kind, ObjectId, Objects, Signature, |
| 19 | }; |
| 20 | use braid_repo::Repo; |
| 21 | use braid_store::{FsckReport, Operation, RefUpdate}; |
| 22 | use clap::{Parser, Subcommand}; |
| 23 | use serde_json::{Value, json}; |
| 24 | |
| 25 | /// Version control for many agents landing changes at once. |
| 26 | #[derive(Debug, Parser)] |
| 27 | #[command(name = "braid", version, about, long_about = None)] |
| 28 | struct Cli { |
| 29 | /// Print machine-readable JSON instead of text. |
| 30 | #[arg(long, global = true)] |
| 31 | json: bool, |
| 32 | |
| 33 | /// The repository's root directory (default: found from the current |
| 34 | /// directory, the nearest one, itself or a parent, that holds a `.braid` |
| 35 | /// directory, or, inside a workspace, its `.braid` file, which names |
| 36 | /// the repository). |
| 37 | #[arg(long, global = true, value_name = "DIR")] |
| 38 | repo: Option<PathBuf>, |
| 39 | |
| 40 | /// Who is acting: a label recorded in the op log with every ref this |
| 41 | /// command moves, and as the `agent` field of every changeset it |
| 42 | /// creates. |
| 43 | #[arg(long, global = true, env = "BRAID_AGENT", default_value = "cli")] |
| 44 | agent: String, |
| 45 | |
| 46 | /// Workspace to act on (default: the one containing the current |
| 47 | /// directory). |
| 48 | #[arg(long, global = true, value_name = "NAME")] |
| 49 | workspace: Option<String>, |
| 50 | |
| 51 | #[command(subcommand)] |
| 52 | command: Command, |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Subcommand)] |
| 56 | enum Command { |
| 57 | /// Create a repository. |
| 58 | Init { |
| 59 | /// Directory to create it in (default: the current directory). |
| 60 | dir: Option<PathBuf>, |
| 61 | }, |
| 62 | /// Print the braid blob id of each file ("-" reads standard input). |
| 63 | HashObject { |
| 64 | /// Also store each file in the repository. |
| 65 | #[arg(short, long)] |
| 66 | write: bool, |
| 67 | /// Files to hash. |
| 68 | #[arg(required = true)] |
| 69 | paths: Vec<PathBuf>, |
| 70 | }, |
| 71 | /// Write an object's raw payload to standard output. |
| 72 | CatObject { |
| 73 | /// A ref, an object id, or a short id (6 hex digits or more). |
| 74 | revision: String, |
| 75 | }, |
| 76 | /// List refs and the objects they point at. |
| 77 | Refs, |
| 78 | /// Move or delete a ref in one op log transaction. |
| 79 | Ref { |
| 80 | #[command(subcommand)] |
| 81 | action: RefAction, |
| 82 | }, |
| 83 | /// Inspect and rewind the op log. |
| 84 | Op { |
| 85 | #[command(subcommand)] |
| 86 | action: OpAction, |
| 87 | }, |
| 88 | /// Revert the newest operation that is not already undone. |
| 89 | Undo, |
| 90 | /// Show history, following first parents. |
| 91 | Log { |
| 92 | /// Where to start: a ref, a changeset id, or a short id (6 hex |
| 93 | /// digits or more). |
| 94 | #[arg(default_value = "main")] |
| 95 | revision: String, |
| 96 | /// How many changesets to show. |
| 97 | #[arg(short = 'n', long, default_value_t = 20)] |
| 98 | limit: usize, |
| 99 | }, |
| 100 | /// Show one changeset: parents, root, signatures, agent, message, and |
| 101 | /// the files it changes against its first parent, as A, M, D or T. |
| 102 | Show { |
| 103 | /// A ref, a changeset id, or a short id (6 hex digits or more). |
| 104 | #[arg(default_value = "main")] |
| 105 | revision: String, |
| 106 | }, |
| 107 | /// Show the files that differ between two changesets: A (added), M |
| 108 | /// (modified), D (deleted) or T (type changed), as `git diff |
| 109 | /// --name-status` does. |
| 110 | #[command(long_about = DIFF_HELP)] |
| 111 | Diff { |
| 112 | /// The changeset to compare from: a ref, an id, or a short id. |
| 113 | from: String, |
| 114 | /// The changeset to compare to: a ref, an id, or a short id. |
| 115 | to: String, |
| 116 | }, |
| 117 | /// Import from and export to git repositories. |
| 118 | Git { |
| 119 | #[command(subcommand)] |
| 120 | action: GitAction, |
| 121 | }, |
| 122 | /// Check every record, index, op log entry and ref of the store. |
| 123 | Fsck, |
| 124 | /// Create, list and remove workspaces. |
| 125 | Workspace { |
| 126 | #[command(subcommand)] |
| 127 | action: work::WorkspaceAction, |
| 128 | }, |
| 129 | /// Show how the workspace differs from its base and its branch. |
| 130 | #[command(long_about = work::STATUS_HELP)] |
| 131 | Status, |
| 132 | /// Record the workspace's changes as a changeset on its base. |
| 133 | Commit(work::CommitArgs), |
| 134 | /// Land the workspace's changesets on its branch (exit status 2 on |
| 135 | /// conflicts). |
| 136 | #[command(long_about = work::LAND_HELP)] |
| 137 | Land(work::LandArgs), |
| 138 | /// Bring the workspace onto its branch's head, rebasing its own |
| 139 | /// changesets (exit status 2 on conflicts). |
| 140 | #[command(long_about = work::UPDATE_HELP)] |
| 141 | Update(work::IdentityArgs), |
| 142 | /// Mark conflicts of a rebase in progress resolved. |
| 143 | Resolve { |
| 144 | /// Paths whose conflicts are settled. |
| 145 | #[arg(required = true)] |
| 146 | paths: Vec<PathBuf>, |
| 147 | }, |
| 148 | /// Let new files that look like secrets or are large be committed. |
| 149 | Track { |
| 150 | /// Files, or directories whose new files may be committed. |
| 151 | #[arg(required = true)] |
| 152 | paths: Vec<PathBuf>, |
| 153 | }, |
| 154 | /// Make changesets without a working copy. |
| 155 | Change { |
| 156 | #[command(subcommand)] |
| 157 | action: work::ChangeAction, |
| 158 | }, |
| 159 | } |
| 160 | |
| 161 | #[derive(Debug, Subcommand)] |
| 162 | enum RefAction { |
| 163 | /// Point a ref at an object. |
| 164 | Set { |
| 165 | /// Ref name. |
| 166 | name: String, |
| 167 | /// What to point at: a ref, an object id, or a short id (6 hex |
| 168 | /// digits or more). |
| 169 | target: String, |
| 170 | /// Only move the ref if it currently points at this id ("none" if it |
| 171 | /// must not exist yet). |
| 172 | #[arg(long, value_name = "ID")] |
| 173 | expect: Option<String>, |
| 174 | }, |
| 175 | /// Delete a ref. |
| 176 | Delete { |
| 177 | /// Ref name. |
| 178 | name: String, |
| 179 | }, |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Subcommand)] |
| 183 | enum GitAction { |
| 184 | /// Import every branch and tag of a git repository. Running it again |
| 185 | /// imports only what is new. |
| 186 | Import { |
| 187 | /// The git repository (a working tree or a bare repository). |
| 188 | path: PathBuf, |
| 189 | }, |
| 190 | /// Write braid refs, and everything they reach, into an existing git |
| 191 | /// repository. Git refs of the same names are overwritten. |
| 192 | Export { |
| 193 | /// The git repository. |
| 194 | path: PathBuf, |
| 195 | /// A braid ref to export; repeat for several (default: all). |
| 196 | #[arg(long = "ref", value_name = "NAME")] |
| 197 | refs: Vec<String>, |
| 198 | }, |
| 199 | /// Keep a braid branch and a branch of a git remote in step: fetch and |
| 200 | /// import the remote branch, then fast-forward the braid branch, or push |
| 201 | /// it (merging first when both moved) as a fast-forward with a lease. |
| 202 | /// Never force-pushes. Exits with 2 on conflicts and 1 when the push is |
| 203 | /// refused. |
| 204 | Sync { |
| 205 | /// The git remote: a URL or a path. |
| 206 | remote: String, |
| 207 | /// The braid branch. |
| 208 | #[arg(long, default_value = "main")] |
| 209 | branch: String, |
| 210 | /// The branch of the remote (default: the braid branch's name). |
| 211 | #[arg(long, value_name = "NAME")] |
| 212 | remote_branch: Option<String>, |
| 213 | /// Report what would happen without writing anything. |
| 214 | #[arg(long)] |
| 215 | dry_run: bool, |
| 216 | }, |
| 217 | } |
| 218 | |
| 219 | #[derive(Debug, Subcommand)] |
| 220 | enum OpAction { |
| 221 | /// Show the newest operations, newest first. |
| 222 | Log { |
| 223 | /// How many to show. |
| 224 | #[arg(short = 'n', long, default_value_t = 20)] |
| 225 | limit: usize, |
| 226 | }, |
| 227 | } |
| 228 | |
| 229 | fn main() -> ExitCode { |
| 230 | let cli = Cli::parse(); |
| 231 | match run(&cli) { |
| 232 | Ok(code) => code, |
| 233 | Err(err) => { |
| 234 | eprintln!("braid: error: {err:#}"); |
| 235 | ExitCode::FAILURE |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn run(cli: &Cli) -> Result<ExitCode> { |
| 241 | match &cli.command { |
| 242 | Command::Init { dir } => init(cli, dir.as_deref()), |
| 243 | Command::HashObject { write, paths } => hash_object(cli, paths, *write), |
| 244 | Command::CatObject { revision } => cat_object(cli, revision), |
| 245 | Command::Refs => refs(cli), |
| 246 | Command::Ref { action } => ref_action(cli, action), |
| 247 | Command::Op { |
| 248 | action: OpAction::Log { limit }, |
| 249 | } => op_log(cli, *limit), |
| 250 | Command::Undo => undo(cli), |
| 251 | Command::Log { revision, limit } => log(cli, revision, *limit), |
| 252 | Command::Show { revision } => show(cli, revision), |
| 253 | Command::Diff { from, to } => diff(cli, from, to), |
| 254 | Command::Git { |
| 255 | action: GitAction::Import { path }, |
| 256 | } => git_import(cli, path), |
| 257 | Command::Git { |
| 258 | action: GitAction::Export { path, refs }, |
| 259 | } => git_export(cli, path, refs), |
| 260 | Command::Git { |
| 261 | action: |
| 262 | GitAction::Sync { |
| 263 | remote, |
| 264 | branch, |
| 265 | remote_branch, |
| 266 | dry_run, |
| 267 | }, |
| 268 | } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run), |
| 269 | Command::Fsck => fsck(cli), |
| 270 | Command::Workspace { action } => work::workspace(cli, action), |
| 271 | Command::Status => work::status(cli), |
| 272 | Command::Commit(args) => work::commit(cli, args), |
| 273 | Command::Land(args) => work::land(cli, args), |
| 274 | Command::Update(args) => work::update(cli, args), |
| 275 | Command::Resolve { paths } => work::resolve(cli, paths), |
| 276 | Command::Track { paths } => work::track(cli, paths), |
| 277 | Command::Change { action } => work::change(cli, action), |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | fn open_repo(cli: &Cli) -> Result<Repo> { |
| 282 | let repo = match &cli.repo { |
| 283 | Some(dir) => Repo::open(dir), |
| 284 | None => Repo::discover(&std::env::current_dir()?), |
| 285 | }; |
| 286 | Ok(repo?) |
| 287 | } |
| 288 | |
| 289 | fn print_json(value: &Value) -> Result<()> { |
| 290 | let mut out = io::stdout().lock(); |
| 291 | serde_json::to_writer(&mut out, value)?; |
| 292 | writeln!(out)?; |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | fn init(cli: &Cli, dir: Option<&Path>) -> Result<ExitCode> { |
| 297 | let dir = match dir { |
| 298 | Some(dir) => dir.to_path_buf(), |
| 299 | None => std::env::current_dir()?, |
| 300 | }; |
| 301 | let repo = Repo::init(&dir)?; |
| 302 | if cli.json { |
| 303 | print_json(&json!({ "root": repo.root().to_string_lossy() }))?; |
| 304 | } else { |
| 305 | println!( |
| 306 | "Created an empty braid repository in {}", |
| 307 | repo.root().join(braid_repo::DIR).display() |
| 308 | ); |
| 309 | } |
| 310 | Ok(ExitCode::SUCCESS) |
| 311 | } |
| 312 | |
| 313 | struct Hashed<'a> { |
| 314 | path: &'a Path, |
| 315 | id: ObjectId, |
| 316 | size: u64, |
| 317 | } |
| 318 | |
| 319 | fn hash_object(cli: &Cli, paths: &[PathBuf], write: bool) -> Result<ExitCode> { |
| 320 | let repo = if write { Some(open_repo(cli)?) } else { None }; |
| 321 | let mut hashed = Vec::with_capacity(paths.len()); |
| 322 | for path in paths { |
| 323 | let (id, size) = match &repo { |
| 324 | // Storing needs the whole payload; the store compresses it. |
| 325 | Some(repo) => { |
| 326 | let bytes = read_input(path)?; |
| 327 | let id = repo.store().put(Kind::Blob, &bytes)?; |
| 328 | (id, bytes.len() as u64) |
| 329 | } |
| 330 | None if path.as_os_str() == "-" => { |
| 331 | hash_blob(io::stdin().lock()).context("cannot read standard input")? |
| 332 | } |
| 333 | None => { |
| 334 | let file = |
| 335 | File::open(path).with_context(|| format!("cannot open {}", path.display()))?; |
| 336 | hash_blob(file).with_context(|| format!("cannot read {}", path.display()))? |
| 337 | } |
| 338 | }; |
| 339 | hashed.push(Hashed { path, id, size }); |
| 340 | } |
| 341 | if let Some(repo) = &repo { |
| 342 | repo.store().sync()?; |
| 343 | } |
| 344 | |
| 345 | if cli.json { |
| 346 | let items: Vec<Value> = hashed |
| 347 | .iter() |
| 348 | .map(|h| { |
| 349 | json!({ |
| 350 | "path": h.path.to_string_lossy(), |
| 351 | "kind": Kind::Blob.name(), |
| 352 | "id": h.id.to_hex(), |
| 353 | "size": h.size, |
| 354 | }) |
| 355 | }) |
| 356 | .collect(); |
| 357 | print_json(&Value::Array(items))?; |
| 358 | } else { |
| 359 | let mut out = io::stdout().lock(); |
| 360 | for h in &hashed { |
| 361 | writeln!(out, "{} {}", h.id, h.path.display())?; |
| 362 | } |
| 363 | } |
| 364 | Ok(ExitCode::SUCCESS) |
| 365 | } |
| 366 | |
| 367 | fn read_input(path: &Path) -> Result<Vec<u8>> { |
| 368 | let mut bytes = Vec::new(); |
| 369 | if path.as_os_str() == "-" { |
| 370 | io::stdin() |
| 371 | .lock() |
| 372 | .read_to_end(&mut bytes) |
| 373 | .context("cannot read standard input")?; |
| 374 | } else { |
| 375 | File::open(path) |
| 376 | .with_context(|| format!("cannot open {}", path.display()))? |
| 377 | .read_to_end(&mut bytes) |
| 378 | .with_context(|| format!("cannot read {}", path.display()))?; |
| 379 | } |
| 380 | Ok(bytes) |
| 381 | } |
| 382 | |
| 383 | /// Hashes a stream as a blob without holding it in memory. |
| 384 | fn hash_blob(mut reader: impl Read) -> io::Result<(ObjectId, u64)> { |
| 385 | let mut hasher = IdHasher::new(Kind::Blob); |
| 386 | let mut buf = vec![0u8; 256 * 1024]; |
| 387 | let mut size = 0u64; |
| 388 | loop { |
| 389 | let n = match reader.read(&mut buf) { |
| 390 | Ok(0) => break, |
| 391 | Ok(n) => n, |
| 392 | Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, |
| 393 | Err(err) => return Err(err), |
| 394 | }; |
| 395 | hasher.update(&buf[..n]); |
| 396 | size += n as u64; |
| 397 | } |
| 398 | Ok((hasher.finalize(), size)) |
| 399 | } |
| 400 | |
| 401 | fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> { |
| 402 | let repo = open_repo(cli)?; |
| 403 | let id = repo.resolve(revision)?; |
| 404 | let Some((kind, payload)) = repo.store().get(&id)? else { |
| 405 | bail!("object {id} is not in the store"); |
| 406 | }; |
| 407 | if cli.json { |
| 408 | print_json(&json!({ |
| 409 | "id": id.to_hex(), |
| 410 | "kind": kind.name(), |
| 411 | "size": payload.len(), |
| 412 | }))?; |
| 413 | } else { |
| 414 | io::stdout().lock().write_all(&payload)?; |
| 415 | } |
| 416 | Ok(ExitCode::SUCCESS) |
| 417 | } |
| 418 | |
| 419 | fn refs(cli: &Cli) -> Result<ExitCode> { |
| 420 | let repo = open_repo(cli)?; |
| 421 | let refs = repo.store().refs()?; |
| 422 | if cli.json { |
| 423 | let map: serde_json::Map<String, Value> = refs |
| 424 | .iter() |
| 425 | .map(|(name, id)| (name.to_owned(), Value::String(id.to_hex()))) |
| 426 | .collect(); |
| 427 | print_json(&json!({ "seq": refs.seq(), "refs": map }))?; |
| 428 | } else { |
| 429 | for (name, id) in refs.iter() { |
| 430 | println!("{id} {name}"); |
| 431 | } |
| 432 | } |
| 433 | Ok(ExitCode::SUCCESS) |
| 434 | } |
| 435 | |
| 436 | fn parse_expect(text: &str) -> Result<Option<ObjectId>> { |
| 437 | if text == "none" { |
| 438 | Ok(None) |
| 439 | } else { |
| 440 | Ok(Some(text.parse().with_context(|| { |
| 441 | format!("--expect takes a full object id or \"none\", not {text:?}") |
| 442 | })?)) |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | fn ref_action(cli: &Cli, action: &RefAction) -> Result<ExitCode> { |
| 447 | let repo = open_repo(cli)?; |
| 448 | let (name, new, expect, description) = match action { |
| 449 | RefAction::Set { |
| 450 | name, |
| 451 | target, |
| 452 | expect, |
| 453 | } => ( |
| 454 | name, |
| 455 | Some(repo.resolve(target)?), |
| 456 | expect.as_deref().map(parse_expect).transpose()?, |
| 457 | format!("ref set {name}"), |
| 458 | ), |
| 459 | RefAction::Delete { name } => (name, None, None, format!("ref delete {name}")), |
| 460 | }; |
| 461 | let op = repo |
| 462 | .store() |
| 463 | .transact(&cli.agent, &description, |refs| { |
| 464 | let current = refs.get(name); |
| 465 | if let Some(expected) = expect |
| 466 | && expected != current |
| 467 | { |
| 468 | return Err(format!( |
| 469 | "ref {name} points at {}, not the expected {}", |
| 470 | show_id(current), |
| 471 | show_id(expected) |
| 472 | )); |
| 473 | } |
| 474 | if new.is_none() && current.is_none() { |
| 475 | return Err(format!("ref {name} does not exist")); |
| 476 | } |
| 477 | Ok(vec![RefUpdate::new(name.clone(), current, new)]) |
| 478 | }) |
| 479 | .map_err(|err| anyhow::anyhow!("{err}"))?; |
| 480 | print_operation(cli, &op)?; |
| 481 | Ok(ExitCode::SUCCESS) |
| 482 | } |
| 483 | |
| 484 | fn show_id(id: Option<ObjectId>) -> String { |
| 485 | id.map_or_else(|| "nothing".to_owned(), |id| id.to_hex()) |
| 486 | } |
| 487 | |
| 488 | fn operation_json(op: &Operation) -> Value { |
| 489 | json!({ |
| 490 | "seq": op.seq, |
| 491 | "time": format_time(op.time_ms), |
| 492 | "time_ms": op.time_ms, |
| 493 | "agent": op.agent, |
| 494 | "description": op.description, |
| 495 | "undoes": op.undoes, |
| 496 | "updates": op.updates.iter().map(|u| json!({ |
| 497 | "name": u.name, |
| 498 | "old": u.old.map(|id| id.to_hex()), |
| 499 | "new": u.new.map(|id| id.to_hex()), |
| 500 | })).collect::<Vec<_>>(), |
| 501 | }) |
| 502 | } |
| 503 | |
| 504 | fn print_operation(cli: &Cli, op: &Operation) -> Result<()> { |
| 505 | if cli.json { |
| 506 | return print_json(&operation_json(op)); |
| 507 | } |
| 508 | let mut out = io::stdout().lock(); |
| 509 | write_operation(&mut out, op)?; |
| 510 | Ok(()) |
| 511 | } |
| 512 | |
| 513 | fn write_operation(out: &mut impl Write, op: &Operation) -> io::Result<()> { |
| 514 | writeln!( |
| 515 | out, |
| 516 | "#{} {} {} {}", |
| 517 | op.seq, |
| 518 | format_time(op.time_ms), |
| 519 | op.agent, |
| 520 | op.description |
| 521 | )?; |
| 522 | for update in &op.updates { |
| 523 | writeln!( |
| 524 | out, |
| 525 | " {}: {} -> {}", |
| 526 | update.name, |
| 527 | short(update.old), |
| 528 | short(update.new) |
| 529 | )?; |
| 530 | } |
| 531 | Ok(()) |
| 532 | } |
| 533 | |
| 534 | fn short(id: Option<ObjectId>) -> String { |
| 535 | id.map_or_else(|| "(none)".to_owned(), |id| id.short()) |
| 536 | } |
| 537 | |
| 538 | fn op_log(cli: &Cli, limit: usize) -> Result<ExitCode> { |
| 539 | let repo = open_repo(cli)?; |
| 540 | let ops = repo.store().log(limit)?; |
| 541 | if cli.json { |
| 542 | print_json(&Value::Array(ops.iter().map(operation_json).collect()))?; |
| 543 | } else { |
| 544 | let mut out = io::stdout().lock(); |
| 545 | for op in &ops { |
| 546 | write_operation(&mut out, op)?; |
| 547 | } |
| 548 | } |
| 549 | Ok(ExitCode::SUCCESS) |
| 550 | } |
| 551 | |
| 552 | fn undo(cli: &Cli) -> Result<ExitCode> { |
| 553 | let repo = open_repo(cli)?; |
| 554 | let op = repo.store().undo_last(&cli.agent)?; |
| 555 | print_operation(cli, &op)?; |
| 556 | Ok(ExitCode::SUCCESS) |
| 557 | } |
| 558 | |
| 559 | fn fsck(cli: &Cli) -> Result<ExitCode> { |
| 560 | let repo = open_repo(cli)?; |
| 561 | let report: FsckReport = repo.store().fsck()?; |
| 562 | let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect(); |
| 563 | if cli.json { |
| 564 | print_json(&json!({ |
| 565 | "clean": report.is_clean(), |
| 566 | "segments": report.segments, |
| 567 | "sealed_segments": report.sealed_segments, |
| 568 | "records": report.records, |
| 569 | "objects": report.objects, |
| 570 | "operations": report.operations, |
| 571 | "refs": report.refs, |
| 572 | "problems": problems, |
| 573 | }))?; |
| 574 | } else { |
| 575 | println!( |
| 576 | "{} objects in {} segments, {} operations, {} refs", |
| 577 | report.objects, report.segments, report.operations, report.refs |
| 578 | ); |
| 579 | for problem in &problems { |
| 580 | println!("problem: {problem}"); |
| 581 | } |
| 582 | println!( |
| 583 | "{}", |
| 584 | if report.is_clean() { |
| 585 | "clean" |
| 586 | } else { |
| 587 | "NOT clean" |
| 588 | } |
| 589 | ); |
| 590 | } |
| 591 | Ok(if report.is_clean() { |
| 592 | ExitCode::SUCCESS |
| 593 | } else { |
| 594 | ExitCode::FAILURE |
| 595 | }) |
| 596 | } |
| 597 | |
| 598 | /// A changeset named by a ref, its id or a short id. |
| 599 | pub(crate) fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> { |
| 600 | Ok(repo.resolve_kind(revision, Kind::Changeset)?) |
| 601 | } |
| 602 | |
| 603 | fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> { |
| 604 | match repo.store().get(id)? { |
| 605 | Some((Kind::Changeset, bytes)) => { |
| 606 | Ok(Changeset::decode(&bytes) |
| 607 | .with_context(|| format!("changeset {id} does not decode"))?) |
| 608 | } |
| 609 | Some((kind, _)) => bail!("{id} is a {kind}, not a changeset"), |
| 610 | None => bail!("changeset {id} is not in the store"), |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | fn read_changes(repo: &Repo, changeset: &Changeset) -> Result<Vec<Change>> { |
| 615 | match &changeset.changes { |
| 616 | Changes::Inline(changes) => Ok(changes.clone()), |
| 617 | Changes::External { list, .. } => { |
| 618 | let Some((_, bytes)) = repo.store().get(list)? else { |
| 619 | bail!("change list {list} is not in the store"); |
| 620 | }; |
| 621 | Ok(decode_change_list(&bytes) |
| 622 | .with_context(|| format!("change list {list} does not decode"))?) |
| 623 | } |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | fn signature_json(signature: &Signature) -> Value { |
| 628 | json!({ |
| 629 | "name": String::from_utf8_lossy(&signature.name), |
| 630 | "email": String::from_utf8_lossy(&signature.email), |
| 631 | "seconds": signature.seconds, |
| 632 | "offset_minutes": signature.offset_minutes, |
| 633 | "time": format_signature_time(signature), |
| 634 | }) |
| 635 | } |
| 636 | |
| 637 | /// The agent a changeset names in its `agent` field, if it names one. |
| 638 | fn agent_of(changeset: &Changeset) -> Option<String> { |
| 639 | changeset |
| 640 | .extras |
| 641 | .iter() |
| 642 | .find(|(key, _)| key.as_slice() == braid_engine::AGENT) |
| 643 | .map(|(_, value)| String::from_utf8_lossy(value).into_owned()) |
| 644 | } |
| 645 | |
| 646 | fn changeset_json(id: &ObjectId, changeset: &Changeset) -> Value { |
| 647 | json!({ |
| 648 | "id": id.to_hex(), |
| 649 | "parents": changeset.parents.iter().map(ObjectId::to_hex).collect::<Vec<_>>(), |
| 650 | "root": changeset.root.to_hex(), |
| 651 | "author": signature_json(&changeset.author), |
| 652 | "committer": signature_json(&changeset.committer), |
| 653 | "agent": agent_of(changeset), |
| 654 | "message": String::from_utf8_lossy(&changeset.message), |
| 655 | "extras": changeset.extras.iter().map(|(k, v)| json!([ |
| 656 | String::from_utf8_lossy(k), String::from_utf8_lossy(v) |
| 657 | ])).collect::<Vec<_>>(), |
| 658 | "git_origin": changeset.git_origin.map(|id| id.to_hex()), |
| 659 | }) |
| 660 | } |
| 661 | |
| 662 | fn subject(message: &[u8]) -> String { |
| 663 | let text = String::from_utf8_lossy(message); |
| 664 | text.lines() |
| 665 | .find(|line| !line.trim().is_empty()) |
| 666 | .unwrap_or("") |
| 667 | .trim() |
| 668 | .to_owned() |
| 669 | } |
| 670 | |
| 671 | fn log(cli: &Cli, revision: &str, limit: usize) -> Result<ExitCode> { |
| 672 | let repo = open_repo(cli)?; |
| 673 | let mut next = Some(resolve_changeset(&repo, revision)?); |
| 674 | let mut entries = Vec::new(); |
| 675 | while let Some(id) = next { |
| 676 | if entries.len() == limit { |
| 677 | break; |
| 678 | } |
| 679 | let changeset = read_changeset(&repo, &id)?; |
| 680 | next = changeset.parents.first().copied(); |
| 681 | entries.push((id, changeset)); |
| 682 | } |
| 683 | if cli.json { |
| 684 | print_json(&Value::Array( |
| 685 | entries |
| 686 | .iter() |
| 687 | .map(|(id, changeset)| changeset_json(id, changeset)) |
| 688 | .collect(), |
| 689 | ))?; |
| 690 | } else { |
| 691 | let mut out = io::stdout().lock(); |
| 692 | for (id, changeset) in &entries { |
| 693 | let agent = agent_of(changeset).map_or_else(String::new, |agent| format!(" ({agent})")); |
| 694 | writeln!( |
| 695 | out, |
| 696 | "{} {} {}{agent} {}", |
| 697 | id.short(), |
| 698 | format_signature_time(&changeset.author), |
| 699 | String::from_utf8_lossy(&changeset.author.name), |
| 700 | subject(&changeset.message) |
| 701 | )?; |
| 702 | } |
| 703 | } |
| 704 | Ok(ExitCode::SUCCESS) |
| 705 | } |
| 706 | |
| 707 | fn change_json(change: &Change) -> Value { |
| 708 | let path = String::from_utf8_lossy(&change.path); |
| 709 | match &change.op { |
| 710 | ChangeOp::Delete => json!({ "path": path, "op": "delete" }), |
| 711 | ChangeOp::File { blob, size } => { |
| 712 | json!({ "path": path, "op": "file", "blob": blob.to_hex(), "size": size }) |
| 713 | } |
| 714 | ChangeOp::Executable { blob, size } => { |
| 715 | json!({ "path": path, "op": "executable", "blob": blob.to_hex(), "size": size }) |
| 716 | } |
| 717 | ChangeOp::Symlink { blob, size } => { |
| 718 | json!({ "path": path, "op": "symlink", "blob": blob.to_hex(), "size": size }) |
| 719 | } |
| 720 | ChangeOp::Gitlink { commit } => json!({ |
| 721 | "path": path, |
| 722 | "op": "gitlink", |
| 723 | "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(), |
| 724 | }), |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | /// How a path changed, as `git diff --name-status` says it: `A` added, `M` |
| 729 | /// modified (content or executable bit), `D` deleted, or `T` for a change |
| 730 | /// between a regular file, a symlink and a gitlink. `old` is what was there |
| 731 | /// before, if a file was. |
| 732 | fn change_status(old: Option<&ChangeOp>, new: &ChangeOp) -> &'static str { |
| 733 | let class = |op: &ChangeOp| match op { |
| 734 | ChangeOp::File { .. } | ChangeOp::Executable { .. } => 0, |
| 735 | ChangeOp::Symlink { .. } => 1, |
| 736 | ChangeOp::Gitlink { .. } => 2, |
| 737 | ChangeOp::Delete => 3, |
| 738 | }; |
| 739 | match (old, new) { |
| 740 | (_, ChangeOp::Delete) => "D", |
| 741 | (None, _) => "A", |
| 742 | (Some(old), new) if class(old) == class(new) => "M", |
| 743 | (Some(_), _) => "T", |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | /// What the tree `old` has at each path where the tree `new` differs from |
| 748 | /// it: the change list of the diff back from `new` to `old`, one walk over |
| 749 | /// the difference. |
| 750 | fn old_entries(repo: &Repo, old: ObjectId, new: ObjectId) -> Result<HashMap<Vec<u8>, ChangeOp>> { |
| 751 | Ok(braid_engine::diff(repo.store(), new, old)? |
| 752 | .into_iter() |
| 753 | .filter(|change| !matches!(change.op, ChangeOp::Delete)) |
| 754 | .map(|change| (change.path, change.op)) |
| 755 | .collect()) |
| 756 | } |
| 757 | |
| 758 | /// A change as JSON, with its status and the file it replaced. |
| 759 | fn change_with_status_json(change: &Change, old: Option<&ChangeOp>) -> Value { |
| 760 | let mut value = change_json(change); |
| 761 | value["status"] = Value::String(change_status(old, &change.op).to_owned()); |
| 762 | value["old"] = match old { |
| 763 | Some(op) => { |
| 764 | let mut old = change_json(&Change { |
| 765 | path: change.path.clone(), |
| 766 | op: op.clone(), |
| 767 | }); |
| 768 | if let Some(fields) = old.as_object_mut() { |
| 769 | fields.remove("path"); |
| 770 | } |
| 771 | old |
| 772 | } |
| 773 | None => Value::Null, |
| 774 | }; |
| 775 | value |
| 776 | } |
| 777 | |
| 778 | /// Prints changes as `git diff --name-status` does: the status, a tab and |
| 779 | /// the path. |
| 780 | fn write_name_status( |
| 781 | out: &mut impl Write, |
| 782 | changes: &[Change], |
| 783 | olds: &HashMap<Vec<u8>, ChangeOp>, |
| 784 | ) -> io::Result<()> { |
| 785 | for change in changes { |
| 786 | let status = change_status(olds.get(&change.path), &change.op); |
| 787 | writeln!(out, "{status}\t{}", String::from_utf8_lossy(&change.path))?; |
| 788 | } |
| 789 | Ok(()) |
| 790 | } |
| 791 | |
| 792 | /// The long help of `diff`. |
| 793 | const DIFF_HELP: &str = "Show the files that differ between two changesets, one line each: a |
| 794 | status, a tab and the path, as `git diff --name-status` prints them. The |
| 795 | status is A (added), M (modified: content or executable bit), D (deleted) |
| 796 | or T (type changed: between a regular file, a symlink and a gitlink). A |
| 797 | directory that became a file, or the other way round, is a D for every |
| 798 | file it had and an A for every file it has. |
| 799 | |
| 800 | With --json, diff prints from and to, the two changesets' full ids, and |
| 801 | changes: one per path, sorted by path bytes, with path, status, op (file, |
| 802 | executable, symlink, gitlink or delete) with blob and size, and old, what |
| 803 | the path held before, or null."; |
| 804 | |
| 805 | fn diff(cli: &Cli, from: &str, to: &str) -> Result<ExitCode> { |
| 806 | let repo = open_repo(cli)?; |
| 807 | let from = resolve_changeset(&repo, from)?; |
| 808 | let to = resolve_changeset(&repo, to)?; |
| 809 | let (from_root, to_root) = ( |
| 810 | read_changeset(&repo, &from)?.root, |
| 811 | read_changeset(&repo, &to)?.root, |
| 812 | ); |
| 813 | let changes = braid_engine::diff(repo.store(), from_root, to_root)?; |
| 814 | let olds = old_entries(&repo, from_root, to_root)?; |
| 815 | if cli.json { |
| 816 | print_json(&json!({ |
| 817 | "from": from.to_hex(), |
| 818 | "to": to.to_hex(), |
| 819 | "changes": changes |
| 820 | .iter() |
| 821 | .map(|change| change_with_status_json(change, olds.get(&change.path))) |
| 822 | .collect::<Vec<_>>(), |
| 823 | }))?; |
| 824 | } else { |
| 825 | write_name_status(&mut io::stdout().lock(), &changes, &olds)?; |
| 826 | } |
| 827 | Ok(ExitCode::SUCCESS) |
| 828 | } |
| 829 | |
| 830 | fn show(cli: &Cli, revision: &str) -> Result<ExitCode> { |
| 831 | let repo = open_repo(cli)?; |
| 832 | let id = resolve_changeset(&repo, revision)?; |
| 833 | let changeset = read_changeset(&repo, &id)?; |
| 834 | let changes = read_changes(&repo, &changeset)?; |
| 835 | // The change list is against the first parent: what that has at each |
| 836 | // path tells added from modified. |
| 837 | let parent_root = match changeset.parents.first() { |
| 838 | Some(parent) => read_changeset(&repo, parent)?.root, |
| 839 | None => braid_engine::EMPTY_TREE, |
| 840 | }; |
| 841 | let olds = old_entries(&repo, parent_root, changeset.root)?; |
| 842 | if cli.json { |
| 843 | let mut value = changeset_json(&id, &changeset); |
| 844 | value["changes"] = changes |
| 845 | .iter() |
| 846 | .map(|change| change_with_status_json(change, olds.get(&change.path))) |
| 847 | .collect(); |
| 848 | print_json(&value)?; |
| 849 | return Ok(ExitCode::SUCCESS); |
| 850 | } |
| 851 | let mut out = io::stdout().lock(); |
| 852 | writeln!(out, "changeset {id}")?; |
| 853 | for parent in &changeset.parents { |
| 854 | writeln!(out, "parent {parent}")?; |
| 855 | } |
| 856 | writeln!(out, "root {}", changeset.root)?; |
| 857 | for (label, signature) in [ |
| 858 | ("author", &changeset.author), |
| 859 | ("committer", &changeset.committer), |
| 860 | ] { |
| 861 | writeln!( |
| 862 | out, |
| 863 | "{label:<9} {} <{}> {}", |
| 864 | String::from_utf8_lossy(&signature.name), |
| 865 | String::from_utf8_lossy(&signature.email), |
| 866 | format_signature_time(signature) |
| 867 | )?; |
| 868 | } |
| 869 | if let Some(agent) = agent_of(&changeset) { |
| 870 | writeln!(out, "agent {agent}")?; |
| 871 | } |
| 872 | writeln!(out)?; |
| 873 | for line in String::from_utf8_lossy(&changeset.message).lines() { |
| 874 | writeln!(out, " {line}")?; |
| 875 | } |
| 876 | writeln!(out)?; |
| 877 | write_name_status(&mut out, &changes, &olds)?; |
| 878 | Ok(ExitCode::SUCCESS) |
| 879 | } |
| 880 | |
| 881 | fn git_import(cli: &Cli, path: &Path) -> Result<ExitCode> { |
| 882 | let repo = open_repo(cli)?; |
| 883 | let import = repo.git_import(path, &cli.agent)?; |
| 884 | let report = &import.report; |
| 885 | let refs: Vec<Value> = report |
| 886 | .refs |
| 887 | .iter() |
| 888 | .map(|r| { |
| 889 | json!({ |
| 890 | "git": String::from_utf8_lossy(&r.name), |
| 891 | "braid": braid_repo::braid_ref_for_git(&r.name), |
| 892 | "id": r.braid.to_hex(), |
| 893 | }) |
| 894 | }) |
| 895 | .collect(); |
| 896 | if cli.json { |
| 897 | print_json(&json!({ |
| 898 | "commits": report.commits, |
| 899 | "trees": report.trees, |
| 900 | "raw_trees": report.raw_trees, |
| 901 | "blobs": report.blobs, |
| 902 | "tags": report.tags, |
| 903 | "refs": refs, |
| 904 | "operation": import.operation.as_ref().map(|op| op.seq), |
| 905 | }))?; |
| 906 | } else { |
| 907 | println!( |
| 908 | "Imported {} commits, {} trees, {} blobs, {} tags; {} refs", |
| 909 | report.commits, |
| 910 | report.trees, |
| 911 | report.blobs, |
| 912 | report.tags, |
| 913 | report.refs.len() |
| 914 | ); |
| 915 | if import.operation.is_none() { |
| 916 | println!("Nothing changed."); |
| 917 | } |
| 918 | } |
| 919 | Ok(ExitCode::SUCCESS) |
| 920 | } |
| 921 | |
| 922 | fn git_export(cli: &Cli, path: &Path, names: &[String]) -> Result<ExitCode> { |
| 923 | let repo = open_repo(cli)?; |
| 924 | let report = repo.git_export_as(path, names, &cli.agent)?; |
| 925 | if cli.json { |
| 926 | print_json(&json!({ |
| 927 | "commits": report.commits, |
| 928 | "trees": report.trees, |
| 929 | "blobs": report.blobs, |
| 930 | "tags": report.tags, |
| 931 | "refs": report.refs.iter().map(|(name, oid)| json!({ |
| 932 | "name": String::from_utf8_lossy(name), |
| 933 | "id": oid.to_string(), |
| 934 | })).collect::<Vec<_>>(), |
| 935 | }))?; |
| 936 | } else { |
| 937 | println!( |
| 938 | "Wrote {} commits, {} trees, {} blobs, {} tags; {} refs", |
| 939 | report.commits, |
| 940 | report.trees, |
| 941 | report.blobs, |
| 942 | report.tags, |
| 943 | report.refs.len() |
| 944 | ); |
| 945 | } |
| 946 | Ok(ExitCode::SUCCESS) |
| 947 | } |
| 948 | |
| 949 | /// Formats a signature's time in its own offset: `YYYY-MM-DD HH:MM ±HHMM`. |
| 950 | fn format_signature_time(signature: &Signature) -> String { |
| 951 | let local = signature |
| 952 | .seconds |
| 953 | .saturating_add(signature.offset_minutes.saturating_mul(60)); |
| 954 | let days = local.div_euclid(86_400); |
| 955 | let of_day = local.rem_euclid(86_400); |
| 956 | let (year, month, day) = civil_from_days(days); |
| 957 | let sign = if signature.offset_minutes < 0 { |
| 958 | '-' |
| 959 | } else { |
| 960 | '+' |
| 961 | }; |
| 962 | let offset = signature.offset_minutes.unsigned_abs(); |
| 963 | format!( |
| 964 | "{year:04}-{month:02}-{day:02} {:02}:{:02} {sign}{:02}{:02}", |
| 965 | of_day / 3600, |
| 966 | of_day % 3600 / 60, |
| 967 | offset / 60, |
| 968 | offset % 60 |
| 969 | ) |
| 970 | } |
| 971 | |
| 972 | /// Formats milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SS UTC`. |
| 973 | fn format_time(time_ms: i64) -> String { |
| 974 | let seconds = time_ms.div_euclid(1000); |
| 975 | let days = seconds.div_euclid(86_400); |
| 976 | let of_day = seconds.rem_euclid(86_400); |
| 977 | let (year, month, day) = civil_from_days(days); |
| 978 | format!( |
| 979 | "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02} UTC", |
| 980 | of_day / 3600, |
| 981 | of_day % 3600 / 60, |
| 982 | of_day % 60 |
| 983 | ) |
| 984 | } |
| 985 | |
| 986 | /// Days since 1970-01-01 to a proleptic Gregorian date. |
| 987 | fn civil_from_days(days: i64) -> (i64, u32, u32) { |
| 988 | let z = days + 719_468; |
| 989 | let era = z.div_euclid(146_097); |
| 990 | let doe = z.rem_euclid(146_097); |
| 991 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 992 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 993 | let mp = (5 * doy + 2) / 153; |
| 994 | let day = (doy - (153 * mp + 2) / 5 + 1) as u32; |
| 995 | let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; |
| 996 | let year = yoe + era * 400 + i64::from(month <= 2); |
| 997 | (year, month, day) |
| 998 | } |
| 999 | |
| 1000 | #[cfg(test)] |
| 1001 | mod tests { |
| 1002 | use super::*; |
| 1003 | |
| 1004 | #[test] |
| 1005 | fn the_status_help_states_the_walk_limit() { |
| 1006 | let limit = format!("more than {}", braid_wc::BEHIND_LIMIT); |
| 1007 | assert!(work::STATUS_HELP.contains(&limit)); |
| 1008 | } |
| 1009 | |
| 1010 | #[test] |
| 1011 | fn time_formatting() { |
| 1012 | assert_eq!(format_time(0), "1970-01-01 00:00:00 UTC"); |
| 1013 | assert_eq!(format_time(1_700_000_000_000), "2023-11-14 22:13:20 UTC"); |
| 1014 | assert_eq!(format_time(951_782_400_000), "2000-02-29 00:00:00 UTC"); |
| 1015 | assert_eq!(format_time(-1000), "1969-12-31 23:59:59 UTC"); |
| 1016 | } |
| 1017 | } |