Elffuss BraidHub

utopia-ia/elffuss-braid public

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