Elffuss BraidHub

utopia-ia/elffuss-braid public

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