Elffuss BraidHub

utopia-ia/elffuss-braid public

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