Elffuss BraidHub

utopia-ia/elffuss-braid public

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