Elffuss BraidHub

utopia-ia/elffuss-braid public

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