Elffuss BraidHub

utopia-ia/elffuss-braid public

9e7f0f69e18e · 54.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid`, the command-line tool.
5
6mod agents;
7mod history;
8mod hub;
9mod revert;
10mod sync;
11mod verify;
12mod work;
13
14use std::collections::HashMap;
15use std::fs::File;
16use std::io::{self, Read, Write};
17use std::path::{Path, PathBuf};
18use std::process::ExitCode;
19
20use anyhow::{Context, Result, bail};
21use braid_format::changeset::decode_change_list;
22use braid_format::{
23 Change, ChangeOp, Changes, Changeset, EntryKind, IdHasher, Kind, ObjectId, Objects, Signature,
24};
25use braid_repo::Repo;
26use braid_store::{FsckReport, Operation, RefUpdate};
27use clap::parser::ValueSource;
28use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser, Subcommand};
29use serde_json::{Value, json};
30use sync::Direction;
31
32/// Version control for many agents landing changes at once.
33#[derive(Debug, Parser)]
34#[command(name = "braid", version, about, long_about = None)]
35struct Cli {
36 /// Print machine-readable JSON instead of text.
37 #[arg(long, global = true)]
38 json: bool,
39
40 /// The repository's root directory (default: found from the current
41 /// directory, the nearest one, itself or a parent, that holds a `.braid`
42 /// directory, or, inside a workspace, its `.braid` file, which names
43 /// the repository).
44 #[arg(long, global = true, value_name = "DIR")]
45 repo: Option<PathBuf>,
46
47 /// Who is acting: a label recorded in the op log with every ref this
48 /// command moves, and as the `agent` field of every changeset it
49 /// creates.
50 #[arg(long, global = true, env = "BRAID_AGENT", default_value = "cli")]
51 agent: String,
52
53 /// Workspace to act on (default: the one containing the current
54 /// directory).
55 #[arg(long, global = true, value_name = "NAME")]
56 workspace: Option<String>,
57
58 /// How hard the store pushes writes to stable storage: `ordered` may
59 /// lose the last operations on power loss, never consistency; `full`
60 /// keeps everything a command acknowledged, at some cost.
61 #[arg(
62 long,
63 global = true,
64 value_enum,
65 env = "BRAID_DURABILITY",
66 default_value_t = DurabilityArg::Ordered
67 )]
68 durability: DurabilityArg,
69
70 #[command(subcommand)]
71 command: Command,
72
73 /// The global flags given on the command line, as a hint repeats them:
74 /// empty, or each flag and its value followed by a space.
75 #[arg(skip)]
76 given: String,
77}
78
79/// `--durability`.
80#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
81enum DurabilityArg {
82 /// Consistent after a crash; the last operations may be lost.
83 Ordered,
84 /// Everything acknowledged survives a power loss.
85 Full,
86}
87
88impl Cli {
89 /// The store options `--durability` asks for.
90 pub(crate) fn store_options(&self) -> braid_store::Options {
91 braid_store::Options {
92 durability: match self.durability {
93 DurabilityArg::Ordered => braid_store::Durability::Ordered,
94 DurabilityArg::Full => braid_store::Durability::Full,
95 },
96 ..braid_store::Options::default()
97 }
98 }
99
100 /// A command for a hint to print: `braid`, the global flags this
101 /// command was given (`--repo`, `--agent`, `--workspace`), then `rest`,
102 /// so that a hint followed as written acts on the same workspace, for
103 /// the same agent.
104 pub(crate) fn hint(&self, rest: &str) -> String {
105 format!("braid {}{rest}", self.given)
106 }
107}
108
109/// The global flags typed on the command line, as [`Cli::given`] holds
110/// them. A value that came from the environment, such as `BRAID_AGENT`, is
111/// left out: the environment that set it sets it again.
112fn given_flags(cli: &Cli, matches: &ArgMatches) -> String {
113 // A global flag is recorded where it was typed, before or after a
114 // subcommand, and copied to the others.
115 let typed = |id: &str| {
116 let mut current = Some(matches);
117 while let Some(found) = current {
118 if found.value_source(id) == Some(ValueSource::CommandLine) {
119 return true;
120 }
121 current = found.subcommand().map(|(_, sub)| sub);
122 }
123 false
124 };
125 let mut given = String::new();
126 let repo = cli.repo.as_ref().map(|repo| repo.to_string_lossy());
127 for (id, value) in [
128 ("repo", repo.as_deref()),
129 ("agent", Some(cli.agent.as_str())),
130 ("workspace", cli.workspace.as_deref()),
131 ] {
132 if let Some(value) = value
133 && typed(id)
134 {
135 given.push_str(&flag(id, value));
136 given.push(' ');
137 }
138 }
139 given
140}
141
142/// `--name value`, quoted for a POSIX shell where it needs to be, or
143/// `--name=value` when the value starts with `-`.
144fn flag(name: &str, value: &str) -> String {
145 let word = shell_word(value);
146 if value.starts_with('-') {
147 format!("--{name}={word}")
148 } else {
149 format!("--{name} {word}")
150 }
151}
152
153/// `text` as one word of a POSIX shell: as it is when that is safe, or
154/// between single quotes.
155pub(crate) fn shell_word(text: &str) -> String {
156 let plain = !text.is_empty()
157 && text
158 .bytes()
159 .all(|byte| byte.is_ascii_alphanumeric() || b"_-./:@%+=,".contains(&byte));
160 if plain {
161 text.to_owned()
162 } else {
163 format!("'{}'", text.replace('\'', r"'\''"))
164 }
165}
166
167#[derive(Debug, Subcommand)]
168enum Command {
169 /// Create a repository.
170 Init {
171 /// Directory to create it in (default: the current directory).
172 dir: Option<PathBuf>,
173 },
174 /// Set a project up for coding agents: the rules in its AGENTS.md.
175 Agents {
176 #[command(subcommand)]
177 action: agents::AgentsAction,
178 },
179 /// Print the braid blob id of each file ("-" reads standard input).
180 HashObject {
181 /// Also store each file in the repository.
182 #[arg(short, long)]
183 write: bool,
184 /// Files to hash.
185 #[arg(required = true)]
186 paths: Vec<PathBuf>,
187 },
188 /// Write an object's raw payload to standard output: a file's content,
189 /// for one named REV:PATH.
190 CatObject {
191 /// A ref, an object id, a short id (6 hex digits or more), or
192 /// REV:PATH, the file or directory at PATH, from the repository's
193 /// root, in the changeset REV.
194 revision: String,
195 },
196 /// List refs and the objects they point at.
197 Refs,
198 /// Move or delete a ref in one op log transaction.
199 Ref {
200 #[command(subcommand)]
201 action: RefAction,
202 },
203 /// Inspect and rewind the op log.
204 Op {
205 #[command(subcommand)]
206 action: OpAction,
207 },
208 /// Revert the newest operation that is not already undone.
209 Undo,
210 /// Show history, following first parents; after `--`, only the
211 /// changesets that change one of the paths or anything below them.
212 #[command(long_about = LOG_HELP)]
213 Log {
214 /// Where to start: a ref, a changeset id, or a short id (6 hex
215 /// digits or more).
216 #[arg(default_value = "main")]
217 revision: String,
218 /// How many changesets to show.
219 #[arg(short = 'n', long, default_value_t = 20)]
220 limit: usize,
221 /// Paths, from the repository's root, after `--`.
222 #[arg(last = true, value_name = "PATH")]
223 paths: Vec<String>,
224 },
225 /// Show the changeset that last changed each line of a file, along
226 /// first parents.
227 #[command(long_about = history::BLAME_HELP)]
228 Blame {
229 /// The revision: a ref, a changeset id, or a short id.
230 revision: String,
231 /// The file, from the repository's root.
232 path: String,
233 },
234 /// Compute derived data ahead of time: generation numbers, skip
235 /// pointers and changed-path filters.
236 #[command(long_about = history::DERIVE_HELP)]
237 Derive {
238 /// Every changeset reachable from any ref.
239 #[arg(long)]
240 all: bool,
241 /// Revisions whose history to derive (default: main, unless --all).
242 revisions: Vec<String>,
243 },
244 /// Show one changeset: parents, root, signatures, agent, message, and
245 /// the files it changes against its first parent, as A, M, D or T.
246 Show {
247 /// A ref, a changeset id, or a short id (6 hex digits or more).
248 #[arg(default_value = "main")]
249 revision: String,
250 },
251 /// Show the files that differ between two changesets: A (added), M
252 /// (modified), D (deleted) or T (type changed), as `git diff
253 /// --name-status` does.
254 #[command(long_about = DIFF_HELP)]
255 Diff {
256 /// The changeset to compare from: a ref, an id, or a short id.
257 from: String,
258 /// The changeset to compare to: a ref, an id, or a short id.
259 to: String,
260 },
261 /// Import from and export to git repositories.
262 Git {
263 #[command(subcommand)]
264 action: GitAction,
265 },
266 /// Sign in to a hub, with GitHub's device flow.
267 #[command(long_about = hub::LOGIN_HELP)]
268 Login(hub::LoginArgs),
269 /// Sign out of a hub: revoke the saved token, and delete it here.
270 #[command(long_about = hub::LOGOUT_HELP)]
271 Logout(hub::LoginArgs),
272 /// Put the repository on a hub, clone one, fetch from it, and compare.
273 Hub {
274 #[command(subcommand)]
275 action: hub::HubAction,
276 },
277 /// Check every record, index, op log entry and ref of the store.
278 Fsck,
279 /// Show what the store holds: objects by kind and by codec, with their
280 /// sizes as stored and decoded.
281 #[command(long_about = STATS_HELP)]
282 Stats,
283 /// Create, list and remove workspaces.
284 Workspace {
285 #[command(subcommand)]
286 action: work::WorkspaceAction,
287 },
288 /// Show how the workspace differs from its base and its branch.
289 #[command(long_about = work::STATUS_HELP)]
290 Status(work::IdentityArgs),
291 /// Record the workspace's changes as a changeset on its base.
292 Commit(work::CommitArgs),
293 /// Land the workspace's changesets on its branch (exit status 2 on
294 /// conflicts).
295 #[command(long_about = work::LAND_HELP)]
296 Land(work::LandArgs),
297 /// Bring the workspace onto its branch's head, rebasing its own
298 /// changesets (exit status 2 on conflicts).
299 #[command(long_about = work::UPDATE_HELP)]
300 Update(work::UpdateArgs),
301 /// Mark conflicts of a rebase in progress resolved.
302 Resolve {
303 /// Paths whose conflicts are settled.
304 #[arg(required = true)]
305 paths: Vec<PathBuf>,
306 },
307 /// Let new files that look like secrets or are large be committed.
308 Track {
309 /// Files, or directories whose new files may be committed.
310 #[arg(required = true)]
311 paths: Vec<PathBuf>,
312 },
313 /// Make changesets without a working copy.
314 Change {
315 #[command(subcommand)]
316 action: work::ChangeAction,
317 },
318 /// Undo a changeset with a new one, and land it (exit status 2 on
319 /// conflicts).
320 #[command(long_about = revert::REVERT_HELP)]
321 Revert(revert::RevertArgs),
322 /// Run the tests on a branch's head, keep braid/green/<branch> at the
323 /// newest changeset that passed, and find what broke them (exit status
324 /// 4 when the branch is red).
325 #[command(long_about = verify::VERIFY_HELP)]
326 Verify(verify::VerifyArgs),
327}
328
329#[derive(Debug, Subcommand)]
330enum RefAction {
331 /// Point a ref at an object.
332 Set {
333 /// Ref name.
334 name: String,
335 /// What to point at: a ref, an object id, or a short id (6 hex
336 /// digits or more).
337 target: String,
338 /// Only move the ref if it currently points at this id ("none" if it
339 /// must not exist yet).
340 #[arg(long, value_name = "ID")]
341 expect: Option<String>,
342 },
343 /// Delete a ref.
344 Delete {
345 /// Ref name.
346 name: String,
347 },
348}
349
350#[derive(Debug, Subcommand)]
351enum GitAction {
352 /// Import every branch and tag of a git repository. Running it again
353 /// imports only what is new.
354 Import {
355 /// The git repository (a working tree or a bare repository).
356 path: PathBuf,
357 },
358 /// Write braid refs, and everything they reach, into an existing git
359 /// repository. Git refs of the same names are overwritten.
360 Export {
361 /// The git repository.
362 path: PathBuf,
363 /// A braid ref to export; repeat for several (default: all).
364 #[arg(long = "ref", value_name = "NAME")]
365 refs: Vec<String>,
366 },
367 /// Keep a braid branch and a branch of a git remote in step: fetch and
368 /// import the remote branch, then fast-forward the braid branch, or push
369 /// it (merging first when both moved) as a fast-forward with a lease, so
370 /// the remote's history is never rewritten. By default a remote that
371 /// someone else wrote to is merged in; `--direction publish` or `follow`
372 /// stops instead. Exits with 2 on conflicts, 3 when the branches are not
373 /// in the relation `--direction` requires, and 1 when the push is refused.
374 Sync {
375 /// The git remote: a URL or a path.
376 remote: String,
377 /// The braid branch.
378 #[arg(long, default_value = "main")]
379 branch: String,
380 /// The branch of the remote (default: the braid branch's name).
381 #[arg(long, value_name = "NAME")]
382 remote_branch: Option<String>,
383 /// Which way changes may go: `both` merges when both sides moved;
384 /// `publish` only pushes, and stops unless the remote branch is the
385 /// braid branch or one of its ancestors; `follow` only takes the
386 /// remote's commits in, and stops unless the braid branch is the
387 /// remote branch or one of its ancestors.
388 #[arg(long, value_enum, default_value_t = Direction::Both)]
389 direction: Direction,
390 /// Report what would happen without writing anything.
391 #[arg(long)]
392 dry_run: bool,
393 },
394}
395
396#[derive(Debug, Subcommand)]
397enum OpAction {
398 /// Show the newest operations, newest first.
399 Log {
400 /// How many to show.
401 #[arg(short = 'n', long, default_value_t = 20)]
402 limit: usize,
403 },
404}
405
406/// The exit status of a command whose reader closed standard output early,
407/// as a shell reports a process that SIGPIPE ended: 128 + 13.
408const BROKEN_PIPE: i32 = 141;
409
410fn main() -> ExitCode {
411 quiet_on_broken_pipe();
412 let matches = Cli::command().get_matches();
413 let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|err| err.exit());
414 cli.given = given_flags(&cli, &matches);
415 match run(&cli) {
416 Ok(code) => code,
417 // A reader that stopped early is no failure: say nothing, as git
418 // does. braid writes to no other pipe (git runs with no input), so a
419 // broken pipe is standard output's.
420 Err(err) if broken_pipe(&err) => ExitCode::from(BROKEN_PIPE as u8),
421 Err(err) => {
422 eprintln!("braid: error: {err:#}");
423 ExitCode::FAILURE
424 }
425 }
426}
427
428/// Whether `err` comes from a write to a reader that went away.
429fn broken_pipe(err: &anyhow::Error) -> bool {
430 err.chain().any(|cause| {
431 cause
432 .downcast_ref::<io::Error>()
433 .is_some_and(|err| err.kind() == io::ErrorKind::BrokenPipe)
434 || cause
435 .downcast_ref::<serde_json::Error>()
436 .is_some_and(|err| err.io_error_kind() == Some(io::ErrorKind::BrokenPipe))
437 })
438}
439
440/// Makes `print!` and `println!` exit quietly, with [`BROKEN_PIPE`], once
441/// the reader of standard output went away (`braid log | head`), instead
442/// of panicking. Standard error is left alone.
443fn quiet_on_broken_pipe() {
444 let default = std::panic::take_hook();
445 std::panic::set_hook(Box::new(move |info| {
446 let payload = info.payload();
447 let message = payload
448 .downcast_ref::<String>()
449 .map(String::as_str)
450 .or_else(|| payload.downcast_ref::<&str>().copied())
451 .unwrap_or("");
452 if message.starts_with("failed printing to stdout")
453 && (message.contains("Broken pipe") || message.contains("os error 32"))
454 {
455 std::process::exit(BROKEN_PIPE);
456 }
457 default(info);
458 }));
459}
460
461/// Exits quietly with [`BROKEN_PIPE`] when a write to standard output failed
462/// because its reader went away; any other error is returned.
463fn stdout_written<T>(result: io::Result<T>) -> io::Result<T> {
464 if let Err(err) = &result
465 && err.kind() == io::ErrorKind::BrokenPipe
466 {
467 std::process::exit(BROKEN_PIPE);
468 }
469 result
470}
471
472fn run(cli: &Cli) -> Result<ExitCode> {
473 match &cli.command {
474 Command::Init { dir } => init(cli, dir.as_deref()),
475 Command::Agents { action } => agents::agents(cli, action),
476 Command::HashObject { write, paths } => hash_object(cli, paths, *write),
477 Command::CatObject { revision } => cat_object(cli, revision),
478 Command::Refs => refs(cli),
479 Command::Ref { action } => ref_action(cli, action),
480 Command::Op {
481 action: OpAction::Log { limit },
482 } => op_log(cli, *limit),
483 Command::Undo => undo(cli),
484 Command::Log {
485 revision,
486 limit,
487 paths,
488 } => log(cli, revision, *limit, paths),
489 Command::Blame { revision, path } => history::blame(cli, revision, path),
490 Command::Derive { all, revisions } => history::derive(cli, *all, revisions),
491 Command::Show { revision } => show(cli, revision),
492 Command::Diff { from, to } => diff(cli, from, to),
493 Command::Git {
494 action: GitAction::Import { path },
495 } => git_import(cli, path),
496 Command::Git {
497 action: GitAction::Export { path, refs },
498 } => git_export(cli, path, refs),
499 Command::Git {
500 action:
501 GitAction::Sync {
502 remote,
503 branch,
504 remote_branch,
505 direction,
506 dry_run,
507 },
508 } => sync::git_sync(
509 cli,
510 remote,
511 branch,
512 remote_branch.as_deref(),
513 *direction,
514 *dry_run,
515 ),
516 Command::Login(args) => hub::login(cli, args),
517 Command::Logout(args) => hub::logout(cli, args),
518 Command::Hub { action } => hub::hub(cli, action),
519 Command::Fsck => fsck(cli),
520 Command::Stats => stats(cli),
521 Command::Workspace { action } => work::workspace(cli, action),
522 Command::Status(args) => work::status(cli, args),
523 Command::Commit(args) => work::commit(cli, args),
524 Command::Land(args) => work::land(cli, args),
525 Command::Update(args) => work::update(cli, args),
526 Command::Resolve { paths } => work::resolve(cli, paths),
527 Command::Track { paths } => work::track(cli, paths),
528 Command::Change { action } => work::change(cli, action),
529 Command::Revert(args) => revert::revert(cli, args),
530 Command::Verify(args) => verify::verify(cli, args),
531 }
532}
533
534fn open_repo(cli: &Cli) -> Result<Repo> {
535 let repo = match &cli.repo {
536 Some(dir) => Repo::open_with(dir, cli.store_options()),
537 None => Repo::discover_with(&std::env::current_dir()?, cli.store_options()),
538 };
539 Ok(repo?)
540}
541
542fn print_json(value: &Value) -> Result<()> {
543 // Serialized first, so that a closed pipe shows up as an I/O error here
544 // rather than inside serde_json's own error type.
545 let mut text = serde_json::to_vec(value)?;
546 text.push(b'\n');
547 let mut out = io::stdout().lock();
548 stdout_written(out.write_all(&text))?;
549 stdout_written(out.flush())?;
550 Ok(())
551}
552
553fn init(cli: &Cli, dir: Option<&Path>) -> Result<ExitCode> {
554 let dir = match dir {
555 Some(dir) => dir.to_path_buf(),
556 None => std::env::current_dir()?,
557 };
558 let repo = Repo::init_with(&dir, cli.store_options())?;
559 if cli.json {
560 print_json(&json!({ "root": repo.root().to_string_lossy() }))?;
561 } else {
562 println!(
563 "Created an empty braid repository in {}",
564 repo.root().join(braid_repo::DIR).display()
565 );
566 }
567 Ok(ExitCode::SUCCESS)
568}
569
570struct Hashed<'a> {
571 path: &'a Path,
572 id: ObjectId,
573 size: u64,
574}
575
576fn hash_object(cli: &Cli, paths: &[PathBuf], write: bool) -> Result<ExitCode> {
577 let repo = if write { Some(open_repo(cli)?) } else { None };
578 let mut hashed = Vec::with_capacity(paths.len());
579 for path in paths {
580 let (id, size) = match &repo {
581 // Streamed into the store: large files are cut into chunks as
582 // they are read, never held in memory whole.
583 Some(repo) if path.as_os_str() == "-" => repo
584 .store()
585 .put_blob_from(io::stdin().lock(), None)
586 .context("cannot store standard input")?,
587 Some(repo) => {
588 let file =
589 File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
590 let size = file.metadata().ok().map(|meta| meta.len());
591 repo.store()
592 .put_blob_from(file, size)
593 .with_context(|| format!("cannot store {}", path.display()))?
594 }
595 None if path.as_os_str() == "-" => {
596 hash_blob(io::stdin().lock()).context("cannot read standard input")?
597 }
598 None => {
599 let file =
600 File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
601 hash_blob(file).with_context(|| format!("cannot read {}", path.display()))?
602 }
603 };
604 hashed.push(Hashed { path, id, size });
605 }
606 if let Some(repo) = &repo {
607 repo.store().sync()?;
608 }
609
610 if cli.json {
611 let items: Vec<Value> = hashed
612 .iter()
613 .map(|h| {
614 json!({
615 "path": h.path.to_string_lossy(),
616 "kind": Kind::Blob.name(),
617 "id": h.id.to_hex(),
618 "size": h.size,
619 })
620 })
621 .collect();
622 print_json(&Value::Array(items))?;
623 } else {
624 let mut out = io::stdout().lock();
625 for h in &hashed {
626 writeln!(out, "{} {}", h.id, h.path.display())?;
627 }
628 }
629 Ok(ExitCode::SUCCESS)
630}
631
632/// Hashes a stream as a blob without holding it in memory.
633fn hash_blob(mut reader: impl Read) -> io::Result<(ObjectId, u64)> {
634 let mut hasher = IdHasher::new(Kind::Blob);
635 let mut buf = vec![0u8; 256 * 1024];
636 let mut size = 0u64;
637 loop {
638 let n = match reader.read(&mut buf) {
639 Ok(0) => break,
640 Ok(n) => n,
641 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
642 Err(err) => return Err(err),
643 };
644 hasher.update(&buf[..n]);
645 size += n as u64;
646 }
647 Ok((hasher.finalize(), size))
648}
649
650/// The object a revision names, or for `REV:PATH`, the object at PATH in
651/// the tree of the changeset REV: the blob of a file or symlink, or the tree
652/// of a directory. A revision that resolves as it is wins, so a ref with a
653/// `:` in its name still names that ref.
654fn resolve_object(repo: &Repo, revision: &str) -> Result<ObjectId> {
655 let (rev, path) = match (repo.resolve(revision), revision.split_once(':')) {
656 (Ok(id), _) => return Ok(id),
657 (Err(braid_repo::Error::UnknownRevision(_)), Some(split)) => split,
658 (Err(err), _) => return Err(err.into()),
659 };
660 let root = read_changeset(repo, &resolve_changeset(repo, rev)?)?.root;
661 let path = path.strip_prefix("./").unwrap_or(path).trim_matches('/');
662 if path.is_empty() {
663 return Ok(root);
664 }
665 match braid_engine::entry_at(repo.store(), root, path.as_bytes())? {
666 Some(
667 EntryKind::File { blob, .. }
668 | EntryKind::Executable { blob, .. }
669 | EntryKind::Symlink { blob, .. },
670 ) => Ok(blob),
671 Some(EntryKind::Tree { tree }) => Ok(tree),
672 Some(EntryKind::Gitlink { .. }) => {
673 bail!("{path:?} is a submodule in {rev}: its content is in another repository")
674 }
675 None => bail!("{rev} has no file or directory at {path:?}"),
676 }
677}
678
679fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> {
680 let repo = open_repo(cli)?;
681 let id = resolve_object(&repo, revision)?;
682 if cli.json {
683 // The size is in the record's header: nothing needs decoding.
684 let Some((kind, size)) = repo.store().stat(&id)? else {
685 bail!("object {id} is not in the store");
686 };
687 print_json(&json!({
688 "id": id.to_hex(),
689 "kind": kind.name(),
690 "size": size,
691 }))?;
692 } else {
693 // Streamed: a large blob is written a chunk at a time.
694 let mut out = io::stdout().lock();
695 if repo.store().read_to(&id, &mut out)?.is_none() {
696 bail!("object {id} is not in the store");
697 }
698 out.flush()?;
699 }
700 Ok(ExitCode::SUCCESS)
701}
702
703fn refs(cli: &Cli) -> Result<ExitCode> {
704 let repo = open_repo(cli)?;
705 let refs = repo.store().refs()?;
706 if cli.json {
707 let map: serde_json::Map<String, Value> = refs
708 .iter()
709 .map(|(name, id)| (name.to_owned(), Value::String(id.to_hex())))
710 .collect();
711 print_json(&json!({ "seq": refs.seq(), "refs": map }))?;
712 } else {
713 for (name, id) in refs.iter() {
714 println!("{id} {name}");
715 }
716 }
717 Ok(ExitCode::SUCCESS)
718}
719
720fn parse_expect(text: &str) -> Result<Option<ObjectId>> {
721 if text == "none" {
722 Ok(None)
723 } else {
724 Ok(Some(text.parse().with_context(|| {
725 format!("--expect takes a full object id or \"none\", not {text:?}")
726 })?))
727 }
728}
729
730fn ref_action(cli: &Cli, action: &RefAction) -> Result<ExitCode> {
731 let repo = open_repo(cli)?;
732 let (name, new, expect, description) = match action {
733 RefAction::Set {
734 name,
735 target,
736 expect,
737 } => (
738 name,
739 Some(repo.resolve(target)?),
740 expect.as_deref().map(parse_expect).transpose()?,
741 format!("ref set {name}"),
742 ),
743 RefAction::Delete { name } => (name, None, None, format!("ref delete {name}")),
744 };
745 let op = repo
746 .store()
747 .transact(&cli.agent, &description, |refs| {
748 let current = refs.get(name);
749 if let Some(expected) = expect
750 && expected != current
751 {
752 return Err(format!(
753 "ref {name} points at {}, not the expected {}",
754 show_id(current),
755 show_id(expected)
756 ));
757 }
758 if new.is_none() && current.is_none() {
759 return Err(format!("ref {name} does not exist"));
760 }
761 Ok(vec![RefUpdate::new(name.clone(), current, new)])
762 })
763 .map_err(|err| anyhow::anyhow!("{err}"))?;
764 print_operation(cli, &op)?;
765 Ok(ExitCode::SUCCESS)
766}
767
768fn show_id(id: Option<ObjectId>) -> String {
769 id.map_or_else(|| "nothing".to_owned(), |id| id.to_hex())
770}
771
772fn operation_json(op: &Operation) -> Value {
773 json!({
774 "seq": op.seq,
775 "time": format_time(op.time_ms),
776 "time_ms": op.time_ms,
777 "agent": op.agent,
778 "description": op.description,
779 "undoes": op.undoes,
780 "updates": op.updates.iter().map(|u| json!({
781 "name": u.name,
782 "old": u.old.map(|id| id.to_hex()),
783 "new": u.new.map(|id| id.to_hex()),
784 })).collect::<Vec<_>>(),
785 })
786}
787
788fn print_operation(cli: &Cli, op: &Operation) -> Result<()> {
789 if cli.json {
790 return print_json(&operation_json(op));
791 }
792 let mut out = io::stdout().lock();
793 write_operation(&mut out, op)?;
794 Ok(())
795}
796
797fn write_operation(out: &mut impl Write, op: &Operation) -> io::Result<()> {
798 writeln!(
799 out,
800 "#{} {} {} {}",
801 op.seq,
802 format_time(op.time_ms),
803 op.agent,
804 op.description
805 )?;
806 for update in &op.updates {
807 writeln!(
808 out,
809 " {}: {} -> {}",
810 update.name,
811 short(update.old),
812 short(update.new)
813 )?;
814 }
815 Ok(())
816}
817
818fn short(id: Option<ObjectId>) -> String {
819 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
820}
821
822fn op_log(cli: &Cli, limit: usize) -> Result<ExitCode> {
823 let repo = open_repo(cli)?;
824 let ops = repo.store().log(limit)?;
825 if cli.json {
826 print_json(&Value::Array(ops.iter().map(operation_json).collect()))?;
827 } else {
828 let mut out = io::stdout().lock();
829 for op in &ops {
830 write_operation(&mut out, op)?;
831 }
832 }
833 Ok(ExitCode::SUCCESS)
834}
835
836fn undo(cli: &Cli) -> Result<ExitCode> {
837 let repo = open_repo(cli)?;
838 let op = repo.store().undo_last(&cli.agent)?;
839 print_operation(cli, &op)?;
840 Ok(ExitCode::SUCCESS)
841}
842
843fn fsck(cli: &Cli) -> Result<ExitCode> {
844 let repo = open_repo(cli)?;
845 let report: FsckReport = repo.store().fsck()?;
846 let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
847 if cli.json {
848 print_json(&json!({
849 "clean": report.is_clean(),
850 "segments": report.segments,
851 "sealed_segments": report.sealed_segments,
852 "records": report.records,
853 "delta_records": report.delta_records,
854 "chunked_records": report.chunked_records,
855 "objects": report.objects,
856 "operations": report.operations,
857 "refs": report.refs,
858 "problems": problems,
859 }))?;
860 } else {
861 println!(
862 "{} objects in {} segments, {} operations, {} refs",
863 report.objects, report.segments, report.operations, report.refs
864 );
865 println!(
866 "{} records: {} deltas, {} chunked blobs",
867 report.records, report.delta_records, report.chunked_records
868 );
869 for problem in &problems {
870 println!("problem: {problem}");
871 }
872 println!(
873 "{}",
874 if report.is_clean() {
875 "clean"
876 } else {
877 "NOT clean"
878 }
879 );
880 }
881 Ok(if report.is_clean() {
882 ExitCode::SUCCESS
883 } else {
884 ExitCode::FAILURE
885 })
886}
887
888/// The long help of `stats`.
889const STATS_HELP: &str = "Show what the store holds: objects by kind and by codec, with their
890sizes as stored and decoded, and the size of the files that hold them. It
891reads the indexes and journals only, never a payload.
892
893Codecs: raw (as it is), zstd (compressed on its own), delta (compressed
894against a similar object, its base: the same path one change earlier),
895chunked (a blob of 4 MiB or more, stored as the list of its chunks; the
896chunks are blobs of their own, so content shared by several versions of a
897file is stored once).
898
899With --json, stats prints objects, stored_bytes (payloads as stored),
900raw_bytes (distinct content: chunked blobs count through their chunks),
901record_bytes (with record headers and padding), segment_bytes and
902index_bytes (the files), kinds (objects, stored_bytes and raw_bytes for
903each of blob, tree, changeset, chunklist and derived) and codecs (the same
904for each of raw, zstd, dictionary, delta and chunked).";
905
906fn stats(cli: &Cli) -> Result<ExitCode> {
907 let repo = open_repo(cli)?;
908 let stats = repo.store().stats()?;
909 let sizes = |objects: u64, stored: u64, raw: u64| json!({ "objects": objects, "stored_bytes": stored, "raw_bytes": raw });
910 if cli.json {
911 let kinds: serde_json::Map<String, Value> = stats
912 .kinds
913 .iter()
914 .map(|k| {
915 (
916 k.kind.name().to_owned(),
917 sizes(k.objects, k.stored_bytes, k.raw_bytes),
918 )
919 })
920 .collect();
921 let codecs: serde_json::Map<String, Value> = stats
922 .codecs
923 .iter()
924 .map(|c| {
925 (
926 c.codec.name().to_owned(),
927 sizes(c.objects, c.stored_bytes, c.raw_bytes),
928 )
929 })
930 .collect();
931 print_json(&json!({
932 "objects": stats.objects,
933 "stored_bytes": stats.stored_bytes,
934 "raw_bytes": stats.raw_bytes,
935 "record_bytes": stats.record_bytes,
936 "segment_bytes": stats.segment_bytes,
937 "index_bytes": stats.index_bytes,
938 "kinds": kinds,
939 "codecs": codecs,
940 }))?;
941 return Ok(ExitCode::SUCCESS);
942 }
943 let mut out = io::stdout().lock();
944 writeln!(
945 out,
946 "{:<12} {:>10} {:>14} {:>14}",
947 "", "objects", "stored", "raw"
948 )?;
949 for k in stats.kinds.iter().filter(|k| k.objects > 0) {
950 writeln!(
951 out,
952 "{:<12} {:>10} {:>14} {:>14}",
953 k.kind.name(),
954 k.objects,
955 k.stored_bytes,
956 k.raw_bytes
957 )?;
958 }
959 writeln!(out)?;
960 for c in stats.codecs.iter().filter(|c| c.objects > 0) {
961 writeln!(
962 out,
963 "{:<12} {:>10} {:>14} {:>14}",
964 c.codec.name(),
965 c.objects,
966 c.stored_bytes,
967 c.raw_bytes
968 )?;
969 }
970 writeln!(out)?;
971 writeln!(
972 out,
973 "{} objects: {} bytes stored for {} bytes of distinct content",
974 stats.objects, stats.stored_bytes, stats.raw_bytes
975 )?;
976 writeln!(
977 out,
978 "files: {} bytes of segments, {} bytes of indexes and journals",
979 stats.segment_bytes, stats.index_bytes
980 )?;
981 Ok(ExitCode::SUCCESS)
982}
983
984/// A changeset named by a ref, its id or a short id.
985pub(crate) fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
986 Ok(repo.resolve_kind(revision, Kind::Changeset)?)
987}
988
989fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> {
990 match repo.store().get(id)? {
991 Some((Kind::Changeset, bytes)) => {
992 Ok(Changeset::decode(&bytes)
993 .with_context(|| format!("changeset {id} does not decode"))?)
994 }
995 Some((kind, _)) => bail!("{id} is a {kind}, not a changeset"),
996 None => bail!("changeset {id} is not in the store"),
997 }
998}
999
1000fn read_changes(repo: &Repo, changeset: &Changeset) -> Result<Vec<Change>> {
1001 match &changeset.changes {
1002 Changes::Inline(changes) => Ok(changes.clone()),
1003 Changes::External { list, .. } => {
1004 let Some((_, bytes)) = repo.store().get(list)? else {
1005 bail!("change list {list} is not in the store");
1006 };
1007 Ok(decode_change_list(&bytes)
1008 .with_context(|| format!("change list {list} does not decode"))?)
1009 }
1010 }
1011}
1012
1013fn signature_json(signature: &Signature) -> Value {
1014 json!({
1015 "name": String::from_utf8_lossy(&signature.name),
1016 "email": String::from_utf8_lossy(&signature.email),
1017 "seconds": signature.seconds,
1018 "offset_minutes": signature.offset_minutes,
1019 "time": format_signature_time(signature),
1020 })
1021}
1022
1023/// The agent a changeset names in its `agent` field, if it names one.
1024fn agent_of(changeset: &Changeset) -> Option<String> {
1025 changeset
1026 .extras
1027 .iter()
1028 .find(|(key, _)| key.as_slice() == braid_engine::AGENT)
1029 .map(|(_, value)| String::from_utf8_lossy(value).into_owned())
1030}
1031
1032fn changeset_json(id: &ObjectId, changeset: &Changeset) -> Value {
1033 json!({
1034 "id": id.to_hex(),
1035 "parents": changeset.parents.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
1036 "root": changeset.root.to_hex(),
1037 "author": signature_json(&changeset.author),
1038 "committer": signature_json(&changeset.committer),
1039 "agent": agent_of(changeset),
1040 "message": String::from_utf8_lossy(&changeset.message),
1041 "extras": changeset.extras.iter().map(|(k, v)| json!([
1042 String::from_utf8_lossy(k), String::from_utf8_lossy(v)
1043 ])).collect::<Vec<_>>(),
1044 "git_origin": changeset.git_origin.map(|id| id.to_hex()),
1045 })
1046}
1047
1048fn subject(message: &[u8]) -> String {
1049 let text = String::from_utf8_lossy(message);
1050 text.lines()
1051 .find(|line| !line.trim().is_empty())
1052 .unwrap_or("")
1053 .trim()
1054 .to_owned()
1055}
1056
1057/// The long help of `log`.
1058const LOG_HELP: &str = "Show history from a revision, following first parents, newest first: the
1059short id, the author's date, the author with the agent, and the subject.
1060
1061With paths after `--` (log main -- src/lib.rs docs), only the changesets
1062whose changes, against their first parent, touch one of the paths or
1063anything below them, as `git log --first-parent -- <path>` lists them.
1064Paths are given from the repository's root and renames are not followed.
1065Changed-path filters, derived data kept in the store, let the walk skip the
1066other changesets without reading them.
1067
1068With --json, log prints each changeset as show does, without its changes.";
1069
1070fn log(cli: &Cli, revision: &str, limit: usize, paths: &[String]) -> Result<ExitCode> {
1071 let repo = open_repo(cli)?;
1072 let head = resolve_changeset(&repo, revision)?;
1073 let mut entries = Vec::new();
1074 if paths.is_empty() {
1075 let mut next = Some(head);
1076 while let Some(id) = next {
1077 if entries.len() == limit {
1078 break;
1079 }
1080 let changeset = read_changeset(&repo, &id)?;
1081 next = changeset.parents.first().copied();
1082 entries.push((id, changeset));
1083 }
1084 } else {
1085 for id in history::path_log(&repo, head, paths, limit)? {
1086 entries.push((id, read_changeset(&repo, &id)?));
1087 }
1088 }
1089 if cli.json {
1090 print_json(&Value::Array(
1091 entries
1092 .iter()
1093 .map(|(id, changeset)| changeset_json(id, changeset))
1094 .collect(),
1095 ))?;
1096 } else {
1097 let mut out = io::stdout().lock();
1098 for (id, changeset) in &entries {
1099 let agent = agent_of(changeset).map_or_else(String::new, |agent| format!(" ({agent})"));
1100 writeln!(
1101 out,
1102 "{} {} {}{agent} {}",
1103 id.short(),
1104 format_signature_time(&changeset.author),
1105 String::from_utf8_lossy(&changeset.author.name),
1106 subject(&changeset.message)
1107 )?;
1108 }
1109 }
1110 Ok(ExitCode::SUCCESS)
1111}
1112
1113fn change_json(change: &Change) -> Value {
1114 let path = String::from_utf8_lossy(&change.path);
1115 match &change.op {
1116 ChangeOp::Delete => json!({ "path": path, "op": "delete" }),
1117 ChangeOp::File { blob, size } => {
1118 json!({ "path": path, "op": "file", "blob": blob.to_hex(), "size": size })
1119 }
1120 ChangeOp::Executable { blob, size } => {
1121 json!({ "path": path, "op": "executable", "blob": blob.to_hex(), "size": size })
1122 }
1123 ChangeOp::Symlink { blob, size } => {
1124 json!({ "path": path, "op": "symlink", "blob": blob.to_hex(), "size": size })
1125 }
1126 ChangeOp::Gitlink { commit } => json!({
1127 "path": path,
1128 "op": "gitlink",
1129 "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
1130 }),
1131 }
1132}
1133
1134/// How a path changed, as `git diff --name-status` says it: `A` added, `M`
1135/// modified (content or executable bit), `D` deleted, or `T` for a change
1136/// between a regular file, a symlink and a gitlink. `old` is what was there
1137/// before, if a file was.
1138fn change_status(old: Option<&ChangeOp>, new: &ChangeOp) -> &'static str {
1139 let class = |op: &ChangeOp| match op {
1140 ChangeOp::File { .. } | ChangeOp::Executable { .. } => 0,
1141 ChangeOp::Symlink { .. } => 1,
1142 ChangeOp::Gitlink { .. } => 2,
1143 ChangeOp::Delete => 3,
1144 };
1145 match (old, new) {
1146 (_, ChangeOp::Delete) => "D",
1147 (None, _) => "A",
1148 (Some(old), new) if class(old) == class(new) => "M",
1149 (Some(_), _) => "T",
1150 }
1151}
1152
1153/// What the tree `old` has at each path where the tree `new` differs from
1154/// it: the change list of the diff back from `new` to `old`, one walk over
1155/// the difference.
1156fn old_entries(repo: &Repo, old: ObjectId, new: ObjectId) -> Result<HashMap<Vec<u8>, ChangeOp>> {
1157 Ok(braid_engine::diff(repo.store(), new, old)?
1158 .into_iter()
1159 .filter(|change| !matches!(change.op, ChangeOp::Delete))
1160 .map(|change| (change.path, change.op))
1161 .collect())
1162}
1163
1164/// A change as JSON, with its status and the file it replaced.
1165fn change_with_status_json(change: &Change, old: Option<&ChangeOp>) -> Value {
1166 let mut value = change_json(change);
1167 value["status"] = Value::String(change_status(old, &change.op).to_owned());
1168 value["old"] = match old {
1169 Some(op) => {
1170 let mut old = change_json(&Change {
1171 path: change.path.clone(),
1172 op: op.clone(),
1173 });
1174 if let Some(fields) = old.as_object_mut() {
1175 fields.remove("path");
1176 }
1177 old
1178 }
1179 None => Value::Null,
1180 };
1181 value
1182}
1183
1184/// Prints changes as `git diff --name-status` does: the status, a tab and
1185/// the path.
1186fn write_name_status(
1187 out: &mut impl Write,
1188 changes: &[Change],
1189 olds: &HashMap<Vec<u8>, ChangeOp>,
1190) -> io::Result<()> {
1191 for change in changes {
1192 let status = change_status(olds.get(&change.path), &change.op);
1193 writeln!(out, "{status}\t{}", String::from_utf8_lossy(&change.path))?;
1194 }
1195 Ok(())
1196}
1197
1198/// The long help of `diff`.
1199const DIFF_HELP: &str = "Show the files that differ between two changesets, one line each: a
1200status, a tab and the path, as `git diff --name-status` prints them. The
1201status is A (added), M (modified: content or executable bit), D (deleted)
1202or T (type changed: between a regular file, a symlink and a gitlink). A
1203directory that became a file, or the other way round, is a D for every
1204file it had and an A for every file it has.
1205
1206With --json, diff prints from and to, the two changesets' full ids, and
1207changes: one per path, sorted by path bytes, with path, status, op (file,
1208executable, symlink, gitlink or delete) with blob and size, and old, what
1209the path held before, or null.";
1210
1211fn diff(cli: &Cli, from: &str, to: &str) -> Result<ExitCode> {
1212 let repo = open_repo(cli)?;
1213 let from = resolve_changeset(&repo, from)?;
1214 let to = resolve_changeset(&repo, to)?;
1215 let (from_root, to_root) = (
1216 read_changeset(&repo, &from)?.root,
1217 read_changeset(&repo, &to)?.root,
1218 );
1219 let changes = braid_engine::diff(repo.store(), from_root, to_root)?;
1220 let olds = old_entries(&repo, from_root, to_root)?;
1221 if cli.json {
1222 print_json(&json!({
1223 "from": from.to_hex(),
1224 "to": to.to_hex(),
1225 "changes": changes
1226 .iter()
1227 .map(|change| change_with_status_json(change, olds.get(&change.path)))
1228 .collect::<Vec<_>>(),
1229 }))?;
1230 } else {
1231 write_name_status(&mut io::stdout().lock(), &changes, &olds)?;
1232 }
1233 Ok(ExitCode::SUCCESS)
1234}
1235
1236fn show(cli: &Cli, revision: &str) -> Result<ExitCode> {
1237 let repo = open_repo(cli)?;
1238 let id = resolve_changeset(&repo, revision)?;
1239 let changeset = read_changeset(&repo, &id)?;
1240 let changes = read_changes(&repo, &changeset)?;
1241 // The change list is against the first parent: what that has at each
1242 // path tells added from modified.
1243 let parent_root = match changeset.parents.first() {
1244 Some(parent) => read_changeset(&repo, parent)?.root,
1245 None => braid_engine::EMPTY_TREE,
1246 };
1247 let olds = old_entries(&repo, parent_root, changeset.root)?;
1248 if cli.json {
1249 let mut value = changeset_json(&id, &changeset);
1250 value["changes"] = changes
1251 .iter()
1252 .map(|change| change_with_status_json(change, olds.get(&change.path)))
1253 .collect();
1254 print_json(&value)?;
1255 return Ok(ExitCode::SUCCESS);
1256 }
1257 let mut out = io::stdout().lock();
1258 writeln!(out, "changeset {id}")?;
1259 for parent in &changeset.parents {
1260 writeln!(out, "parent {parent}")?;
1261 }
1262 writeln!(out, "root {}", changeset.root)?;
1263 for (label, signature) in [
1264 ("author", &changeset.author),
1265 ("committer", &changeset.committer),
1266 ] {
1267 writeln!(
1268 out,
1269 "{label:<9} {} <{}> {}",
1270 String::from_utf8_lossy(&signature.name),
1271 String::from_utf8_lossy(&signature.email),
1272 format_signature_time(signature)
1273 )?;
1274 }
1275 if let Some(agent) = agent_of(&changeset) {
1276 writeln!(out, "agent {agent}")?;
1277 }
1278 writeln!(out)?;
1279 for line in String::from_utf8_lossy(&changeset.message).lines() {
1280 writeln!(out, " {line}")?;
1281 }
1282 writeln!(out)?;
1283 write_name_status(&mut out, &changes, &olds)?;
1284 Ok(ExitCode::SUCCESS)
1285}
1286
1287fn git_import(cli: &Cli, path: &Path) -> Result<ExitCode> {
1288 let repo = open_repo(cli)?;
1289 let import = repo.git_import(path, &cli.agent)?;
1290 let report = &import.report;
1291 let refs: Vec<Value> = report
1292 .refs
1293 .iter()
1294 .map(|r| {
1295 json!({
1296 "git": String::from_utf8_lossy(&r.name),
1297 "braid": braid_repo::braid_ref_for_git(&r.name),
1298 "id": r.braid.to_hex(),
1299 })
1300 })
1301 .collect();
1302 if cli.json {
1303 print_json(&json!({
1304 "commits": report.commits,
1305 "trees": report.trees,
1306 "raw_trees": report.raw_trees,
1307 "blobs": report.blobs,
1308 "tags": report.tags,
1309 "refs": refs,
1310 "kept": import.kept.iter().map(|k| json!({
1311 "name": k.name,
1312 "braid": k.braid.to_hex(),
1313 "git": k.git.to_hex(),
1314 "reason": k.reason.code(),
1315 })).collect::<Vec<_>>(),
1316 "operation": import.operation.as_ref().map(|op| op.seq),
1317 }))?;
1318 } else {
1319 println!(
1320 "Imported {} commits, {} trees, {} blobs, {} tags; {} refs",
1321 report.commits,
1322 report.trees,
1323 report.blobs,
1324 report.tags,
1325 report.refs.len()
1326 );
1327 for kept in &import.kept {
1328 let why = match kept.reason {
1329 braid_repo::KeptReason::Ahead => "braid has work git does not have",
1330 braid_repo::KeptReason::Diverged => "braid and git have each moved on",
1331 braid_repo::KeptReason::NotAChangeset => "one side is not a changeset",
1332 braid_repo::KeptReason::Moved => "it moved while the import ran",
1333 };
1334 println!(
1335 "Kept {} at {}: {why} (git is at {}).",
1336 kept.name,
1337 kept.braid.short(),
1338 kept.git.short()
1339 );
1340 }
1341 if import.operation.is_none() {
1342 println!("Nothing changed.");
1343 }
1344 }
1345 Ok(ExitCode::SUCCESS)
1346}
1347
1348fn git_export(cli: &Cli, path: &Path, names: &[String]) -> Result<ExitCode> {
1349 let repo = open_repo(cli)?;
1350 let report = repo.git_export_as(path, names, &cli.agent)?;
1351 if cli.json {
1352 print_json(&json!({
1353 "commits": report.commits,
1354 "trees": report.trees,
1355 "blobs": report.blobs,
1356 "tags": report.tags,
1357 "refs": report.refs.iter().map(|(name, oid)| json!({
1358 "name": String::from_utf8_lossy(name),
1359 "id": oid.to_string(),
1360 })).collect::<Vec<_>>(),
1361 }))?;
1362 } else {
1363 println!(
1364 "Wrote {} commits, {} trees, {} blobs, {} tags; {} refs",
1365 report.commits,
1366 report.trees,
1367 report.blobs,
1368 report.tags,
1369 report.refs.len()
1370 );
1371 }
1372 Ok(ExitCode::SUCCESS)
1373}
1374
1375/// Formats a signature's time in its own offset: `YYYY-MM-DD HH:MM ±HHMM`.
1376fn format_signature_time(signature: &Signature) -> String {
1377 let local = signature
1378 .seconds
1379 .saturating_add(signature.offset_minutes.saturating_mul(60));
1380 let days = local.div_euclid(86_400);
1381 let of_day = local.rem_euclid(86_400);
1382 let (year, month, day) = civil_from_days(days);
1383 let sign = if signature.offset_minutes < 0 {
1384 '-'
1385 } else {
1386 '+'
1387 };
1388 let offset = signature.offset_minutes.unsigned_abs();
1389 format!(
1390 "{year:04}-{month:02}-{day:02} {:02}:{:02} {sign}{:02}{:02}",
1391 of_day / 3600,
1392 of_day % 3600 / 60,
1393 offset / 60,
1394 offset % 60
1395 )
1396}
1397
1398/// Formats milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SS UTC`.
1399fn format_time(time_ms: i64) -> String {
1400 let seconds = time_ms.div_euclid(1000);
1401 let days = seconds.div_euclid(86_400);
1402 let of_day = seconds.rem_euclid(86_400);
1403 let (year, month, day) = civil_from_days(days);
1404 format!(
1405 "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02} UTC",
1406 of_day / 3600,
1407 of_day % 3600 / 60,
1408 of_day % 60
1409 )
1410}
1411
1412/// Days since 1970-01-01 to a proleptic Gregorian date.
1413fn civil_from_days(days: i64) -> (i64, u32, u32) {
1414 let z = days + 719_468;
1415 let era = z.div_euclid(146_097);
1416 let doe = z.rem_euclid(146_097);
1417 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1418 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1419 let mp = (5 * doy + 2) / 153;
1420 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1421 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1422 let year = yoe + era * 400 + i64::from(month <= 2);
1423 (year, month, day)
1424}
1425
1426#[cfg(test)]
1427mod tests {
1428 use super::*;
1429
1430 #[test]
1431 fn the_status_help_states_the_walk_limit() {
1432 let limit = format!("more than {}", braid_wc::BEHIND_LIMIT);
1433 assert!(work::STATUS_HELP.contains(&limit));
1434 }
1435
1436 fn parse(args: &[&str]) -> Cli {
1437 Cli::try_parse_from(args).unwrap_or_else(|err| panic!("{args:?}: {err}"))
1438 }
1439
1440 /// The long help of the subcommand at `path`.
1441 fn long_help(path: &[&str]) -> String {
1442 let mut command = Cli::command();
1443 command.build();
1444 let mut current = &mut command;
1445 for name in path {
1446 current = current
1447 .find_subcommand_mut(name)
1448 .unwrap_or_else(|| panic!("no subcommand {name}"));
1449 }
1450 current.render_long_help().to_string()
1451 }
1452
1453 #[test]
1454 fn the_command_line_is_consistent() {
1455 Cli::command().debug_assert();
1456 }
1457
1458 #[test]
1459 fn hub_commands_parse() {
1460 match parse(&[
1461 "braid", "hub", "clone", "ada/demo", "dir", "--paths", "src", "docs",
1462 ])
1463 .command
1464 {
1465 Command::Hub {
1466 action: hub::HubAction::Clone(args),
1467 } => {
1468 assert_eq!(args.source, "ada/demo");
1469 assert_eq!(args.dir, Some(PathBuf::from("dir")));
1470 assert_eq!(args.paths, ["src", "docs"]);
1471 }
1472 other => panic!("{other:?}"),
1473 }
1474 match parse(&[
1475 "braid",
1476 "hub",
1477 "publish",
1478 "demo",
1479 "--public",
1480 "--description",
1481 "A demo",
1482 "--mirror",
1483 "https://github.com/ada/demo.git",
1484 ])
1485 .command
1486 {
1487 Command::Hub {
1488 action: hub::HubAction::Publish(args),
1489 } => {
1490 assert_eq!(args.name.as_deref(), Some("demo"));
1491 assert!(args.public);
1492 assert_eq!(args.description.as_deref(), Some("A demo"));
1493 assert_eq!(
1494 args.mirror.as_deref(),
1495 Some("https://github.com/ada/demo.git")
1496 );
1497 }
1498 other => panic!("{other:?}"),
1499 }
1500 match parse(&["braid", "login", "--hub", "https://hub.example.org"]).command {
1501 Command::Login(args) => {
1502 assert_eq!(args.hub.as_deref(), Some("https://hub.example.org"))
1503 }
1504 other => panic!("{other:?}"),
1505 }
1506 assert!(matches!(
1507 parse(&["braid", "logout"]).command,
1508 Command::Logout(hub::LoginArgs { hub: None })
1509 ));
1510 assert!(matches!(
1511 parse(&["braid", "--json", "hub", "fetch"]).command,
1512 Command::Hub {
1513 action: hub::HubAction::Fetch
1514 }
1515 ));
1516 assert!(parse(&["braid", "hub", "status", "--json"]).json);
1517 match parse(&["braid", "land", "--local", "--onto", "main"]).command {
1518 Command::Land(args) => assert!(args.local),
1519 other => panic!("{other:?}"),
1520 }
1521 match parse(&["braid", "update", "--local"]).command {
1522 Command::Update(args) => assert!(args.local),
1523 other => panic!("{other:?}"),
1524 }
1525 match parse(&["braid", "update"]).command {
1526 Command::Update(args) => assert!(!args.local),
1527 other => panic!("{other:?}"),
1528 }
1529 match parse(&[
1530 "braid", "change", "create", "--base", "main", "-m", "x", "--land", "main", "--local",
1531 ])
1532 .command
1533 {
1534 Command::Change {
1535 action: work::ChangeAction::Create(args),
1536 } => {
1537 assert_eq!(args.land.as_deref(), Some("main"));
1538 assert!(args.local);
1539 }
1540 other => panic!("{other:?}"),
1541 }
1542 for bad in [
1543 &["braid", "hub", "clone"][..],
1544 &["braid", "hub", "clone", "a/b", "--paths"],
1545 &["braid", "hub", "publish", "a", "b"],
1546 &["braid", "login", "--hub"],
1547 &["braid", "hub"],
1548 ] {
1549 assert!(Cli::try_parse_from(bad).is_err(), "{bad:?}");
1550 }
1551 }
1552
1553 #[test]
1554 fn help_texts_cover_the_hub() {
1555 let top = Cli::command().render_help().to_string();
1556 for name in ["login", "logout", "hub"] {
1557 assert!(top.contains(&format!(" {name} ")), "{name}: {top}");
1558 }
1559 for path in [&["land"][..], &["update"], &["change", "create"]] {
1560 let text = long_help(path);
1561 assert!(text.contains("linked to a hub"), "{path:?}: {text}");
1562 assert!(text.contains("BRAID_HUB=off"), "{path:?}: {text}");
1563 assert!(text.contains("--local"), "{path:?}: {text}");
1564 }
1565 assert!(long_help(&["land"]).contains("the hub's)"));
1566 let login = long_help(&["login"]);
1567 for needed in [
1568 "device flow",
1569 "BRAID_TOKEN",
1570 "BRAID_HUB_URL",
1571 "hub.json",
1572 "--hub",
1573 ] {
1574 assert!(login.contains(needed), "{needed}: {login}");
1575 }
1576 assert!(long_help(&["logout"]).contains("revoke"));
1577 let publish = long_help(&["hub", "publish"]);
1578 for needed in [
1579 "NAME",
1580 "--public",
1581 "--mirror",
1582 "256 MiB",
1583 "annotated tag",
1584 ".braid/hub",
1585 ] {
1586 assert!(publish.contains(needed), "{needed}: {publish}");
1587 }
1588 let clone = long_help(&["hub", "clone"]);
1589 for needed in ["OWNER/NAME", "--paths", ".braid/work", "--workspace"] {
1590 assert!(clone.contains(needed), "{needed}: {clone}");
1591 }
1592 let fetch = long_help(&["hub", "fetch"]);
1593 for needed in ["first-parent chain", "remote/hub/", "ahead or diverged"] {
1594 assert!(fetch.contains(needed), "{needed}: {fetch}");
1595 }
1596 let status = long_help(&["hub", "status"]);
1597 for needed in ["same", "behind", "ahead", "diverged"] {
1598 assert!(status.contains(needed), "{needed}: {status}");
1599 }
1600 }
1601
1602 #[test]
1603 fn time_formatting() {
1604 assert_eq!(format_time(0), "1970-01-01 00:00:00 UTC");
1605 assert_eq!(format_time(1_700_000_000_000), "2023-11-14 22:13:20 UTC");
1606 assert_eq!(format_time(951_782_400_000), "2000-02-29 00:00:00 UTC");
1607 assert_eq!(format_time(-1000), "1969-12-31 23:59:59 UTC");
1608 }
1609}