Elffuss BraidHub

utopia-ia/elffuss-braid public

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