Elffuss BraidHub

utopia-ia/elffuss-braid public

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