Elffuss BraidHub

utopia-ia/elffuss-braid public

f8f43175152e · 34.7 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 /// Create, list and remove workspaces.
150 Workspace {
151 #[command(subcommand)]
152 action: work::WorkspaceAction,
153 },
154 /// Show how the workspace differs from its base and its branch.
155 #[command(long_about = work::STATUS_HELP)]
156 Status,
157 /// Record the workspace's changes as a changeset on its base.
158 Commit(work::CommitArgs),
159 /// Land the workspace's changesets on its branch (exit status 2 on
160 /// conflicts).
161 #[command(long_about = work::LAND_HELP)]
162 Land(work::LandArgs),
163 /// Bring the workspace onto its branch's head, rebasing its own
164 /// changesets (exit status 2 on conflicts).
165 #[command(long_about = work::UPDATE_HELP)]
166 Update(work::IdentityArgs),
167 /// Mark conflicts of a rebase in progress resolved.
168 Resolve {
169 /// Paths whose conflicts are settled.
170 #[arg(required = true)]
171 paths: Vec<PathBuf>,
172 },
173 /// Let new files that look like secrets or are large be committed.
174 Track {
175 /// Files, or directories whose new files may be committed.
176 #[arg(required = true)]
177 paths: Vec<PathBuf>,
178 },
179 /// Make changesets without a working copy.
180 Change {
181 #[command(subcommand)]
182 action: work::ChangeAction,
183 },
184}
185
186#[derive(Debug, Subcommand)]
187enum RefAction {
188 /// Point a ref at an object.
189 Set {
190 /// Ref name.
191 name: String,
192 /// What to point at: a ref, an object id, or a short id (6 hex
193 /// digits or more).
194 target: String,
195 /// Only move the ref if it currently points at this id ("none" if it
196 /// must not exist yet).
197 #[arg(long, value_name = "ID")]
198 expect: Option<String>,
199 },
200 /// Delete a ref.
201 Delete {
202 /// Ref name.
203 name: String,
204 },
205}
206
207#[derive(Debug, Subcommand)]
208enum GitAction {
209 /// Import every branch and tag of a git repository. Running it again
210 /// imports only what is new.
211 Import {
212 /// The git repository (a working tree or a bare repository).
213 path: PathBuf,
214 },
215 /// Write braid refs, and everything they reach, into an existing git
216 /// repository. Git refs of the same names are overwritten.
217 Export {
218 /// The git repository.
219 path: PathBuf,
220 /// A braid ref to export; repeat for several (default: all).
221 #[arg(long = "ref", value_name = "NAME")]
222 refs: Vec<String>,
223 },
224 /// Keep a braid branch and a branch of a git remote in step: fetch and
225 /// import the remote branch, then fast-forward the braid branch, or push
226 /// it (merging first when both moved) as a fast-forward with a lease.
227 /// Never force-pushes. Exits with 2 on conflicts and 1 when the push is
228 /// refused.
229 Sync {
230 /// The git remote: a URL or a path.
231 remote: String,
232 /// The braid branch.
233 #[arg(long, default_value = "main")]
234 branch: String,
235 /// The branch of the remote (default: the braid branch's name).
236 #[arg(long, value_name = "NAME")]
237 remote_branch: Option<String>,
238 /// Report what would happen without writing anything.
239 #[arg(long)]
240 dry_run: bool,
241 },
242}
243
244#[derive(Debug, Subcommand)]
245enum OpAction {
246 /// Show the newest operations, newest first.
247 Log {
248 /// How many to show.
249 #[arg(short = 'n', long, default_value_t = 20)]
250 limit: usize,
251 },
252}
253
254fn main() -> ExitCode {
255 let cli = Cli::parse();
256 match run(&cli) {
257 Ok(code) => code,
258 Err(err) => {
259 eprintln!("braid: error: {err:#}");
260 ExitCode::FAILURE
261 }
262 }
263}
264
265fn run(cli: &Cli) -> Result<ExitCode> {
266 match &cli.command {
267 Command::Init { dir } => init(cli, dir.as_deref()),
268 Command::HashObject { write, paths } => hash_object(cli, paths, *write),
269 Command::CatObject { revision } => cat_object(cli, revision),
270 Command::Refs => refs(cli),
271 Command::Ref { action } => ref_action(cli, action),
272 Command::Op {
273 action: OpAction::Log { limit },
274 } => op_log(cli, *limit),
275 Command::Undo => undo(cli),
276 Command::Log {
277 revision,
278 limit,
279 paths,
280 } => log(cli, revision, *limit, paths),
281 Command::Blame { revision, path } => history::blame(cli, revision, path),
282 Command::Derive { all, revisions } => history::derive(cli, *all, revisions),
283 Command::Show { revision } => show(cli, revision),
284 Command::Diff { from, to } => diff(cli, from, to),
285 Command::Git {
286 action: GitAction::Import { path },
287 } => git_import(cli, path),
288 Command::Git {
289 action: GitAction::Export { path, refs },
290 } => git_export(cli, path, refs),
291 Command::Git {
292 action:
293 GitAction::Sync {
294 remote,
295 branch,
296 remote_branch,
297 dry_run,
298 },
299 } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run),
300 Command::Fsck => fsck(cli),
301 Command::Workspace { action } => work::workspace(cli, action),
302 Command::Status => work::status(cli),
303 Command::Commit(args) => work::commit(cli, args),
304 Command::Land(args) => work::land(cli, args),
305 Command::Update(args) => work::update(cli, args),
306 Command::Resolve { paths } => work::resolve(cli, paths),
307 Command::Track { paths } => work::track(cli, paths),
308 Command::Change { action } => work::change(cli, action),
309 }
310}
311
312fn open_repo(cli: &Cli) -> Result<Repo> {
313 let repo = match &cli.repo {
314 Some(dir) => Repo::open(dir),
315 None => Repo::discover(&std::env::current_dir()?),
316 };
317 Ok(repo?)
318}
319
320fn print_json(value: &Value) -> Result<()> {
321 let mut out = io::stdout().lock();
322 serde_json::to_writer(&mut out, value)?;
323 writeln!(out)?;
324 Ok(())
325}
326
327fn init(cli: &Cli, dir: Option<&Path>) -> Result<ExitCode> {
328 let dir = match dir {
329 Some(dir) => dir.to_path_buf(),
330 None => std::env::current_dir()?,
331 };
332 let repo = Repo::init(&dir)?;
333 if cli.json {
334 print_json(&json!({ "root": repo.root().to_string_lossy() }))?;
335 } else {
336 println!(
337 "Created an empty braid repository in {}",
338 repo.root().join(braid_repo::DIR).display()
339 );
340 }
341 Ok(ExitCode::SUCCESS)
342}
343
344struct Hashed<'a> {
345 path: &'a Path,
346 id: ObjectId,
347 size: u64,
348}
349
350fn hash_object(cli: &Cli, paths: &[PathBuf], write: bool) -> Result<ExitCode> {
351 let repo = if write { Some(open_repo(cli)?) } else { None };
352 let mut hashed = Vec::with_capacity(paths.len());
353 for path in paths {
354 let (id, size) = match &repo {
355 // Storing needs the whole payload; the store compresses it.
356 Some(repo) => {
357 let bytes = read_input(path)?;
358 let id = repo.store().put(Kind::Blob, &bytes)?;
359 (id, bytes.len() as u64)
360 }
361 None if path.as_os_str() == "-" => {
362 hash_blob(io::stdin().lock()).context("cannot read standard input")?
363 }
364 None => {
365 let file =
366 File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
367 hash_blob(file).with_context(|| format!("cannot read {}", path.display()))?
368 }
369 };
370 hashed.push(Hashed { path, id, size });
371 }
372 if let Some(repo) = &repo {
373 repo.store().sync()?;
374 }
375
376 if cli.json {
377 let items: Vec<Value> = hashed
378 .iter()
379 .map(|h| {
380 json!({
381 "path": h.path.to_string_lossy(),
382 "kind": Kind::Blob.name(),
383 "id": h.id.to_hex(),
384 "size": h.size,
385 })
386 })
387 .collect();
388 print_json(&Value::Array(items))?;
389 } else {
390 let mut out = io::stdout().lock();
391 for h in &hashed {
392 writeln!(out, "{} {}", h.id, h.path.display())?;
393 }
394 }
395 Ok(ExitCode::SUCCESS)
396}
397
398fn read_input(path: &Path) -> Result<Vec<u8>> {
399 let mut bytes = Vec::new();
400 if path.as_os_str() == "-" {
401 io::stdin()
402 .lock()
403 .read_to_end(&mut bytes)
404 .context("cannot read standard input")?;
405 } else {
406 File::open(path)
407 .with_context(|| format!("cannot open {}", path.display()))?
408 .read_to_end(&mut bytes)
409 .with_context(|| format!("cannot read {}", path.display()))?;
410 }
411 Ok(bytes)
412}
413
414/// Hashes a stream as a blob without holding it in memory.
415fn hash_blob(mut reader: impl Read) -> io::Result<(ObjectId, u64)> {
416 let mut hasher = IdHasher::new(Kind::Blob);
417 let mut buf = vec![0u8; 256 * 1024];
418 let mut size = 0u64;
419 loop {
420 let n = match reader.read(&mut buf) {
421 Ok(0) => break,
422 Ok(n) => n,
423 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
424 Err(err) => return Err(err),
425 };
426 hasher.update(&buf[..n]);
427 size += n as u64;
428 }
429 Ok((hasher.finalize(), size))
430}
431
432fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> {
433 let repo = open_repo(cli)?;
434 let id = repo.resolve(revision)?;
435 let Some((kind, payload)) = repo.store().get(&id)? else {
436 bail!("object {id} is not in the store");
437 };
438 if cli.json {
439 print_json(&json!({
440 "id": id.to_hex(),
441 "kind": kind.name(),
442 "size": payload.len(),
443 }))?;
444 } else {
445 io::stdout().lock().write_all(&payload)?;
446 }
447 Ok(ExitCode::SUCCESS)
448}
449
450fn refs(cli: &Cli) -> Result<ExitCode> {
451 let repo = open_repo(cli)?;
452 let refs = repo.store().refs()?;
453 if cli.json {
454 let map: serde_json::Map<String, Value> = refs
455 .iter()
456 .map(|(name, id)| (name.to_owned(), Value::String(id.to_hex())))
457 .collect();
458 print_json(&json!({ "seq": refs.seq(), "refs": map }))?;
459 } else {
460 for (name, id) in refs.iter() {
461 println!("{id} {name}");
462 }
463 }
464 Ok(ExitCode::SUCCESS)
465}
466
467fn parse_expect(text: &str) -> Result<Option<ObjectId>> {
468 if text == "none" {
469 Ok(None)
470 } else {
471 Ok(Some(text.parse().with_context(|| {
472 format!("--expect takes a full object id or \"none\", not {text:?}")
473 })?))
474 }
475}
476
477fn ref_action(cli: &Cli, action: &RefAction) -> Result<ExitCode> {
478 let repo = open_repo(cli)?;
479 let (name, new, expect, description) = match action {
480 RefAction::Set {
481 name,
482 target,
483 expect,
484 } => (
485 name,
486 Some(repo.resolve(target)?),
487 expect.as_deref().map(parse_expect).transpose()?,
488 format!("ref set {name}"),
489 ),
490 RefAction::Delete { name } => (name, None, None, format!("ref delete {name}")),
491 };
492 let op = repo
493 .store()
494 .transact(&cli.agent, &description, |refs| {
495 let current = refs.get(name);
496 if let Some(expected) = expect
497 && expected != current
498 {
499 return Err(format!(
500 "ref {name} points at {}, not the expected {}",
501 show_id(current),
502 show_id(expected)
503 ));
504 }
505 if new.is_none() && current.is_none() {
506 return Err(format!("ref {name} does not exist"));
507 }
508 Ok(vec![RefUpdate::new(name.clone(), current, new)])
509 })
510 .map_err(|err| anyhow::anyhow!("{err}"))?;
511 print_operation(cli, &op)?;
512 Ok(ExitCode::SUCCESS)
513}
514
515fn show_id(id: Option<ObjectId>) -> String {
516 id.map_or_else(|| "nothing".to_owned(), |id| id.to_hex())
517}
518
519fn operation_json(op: &Operation) -> Value {
520 json!({
521 "seq": op.seq,
522 "time": format_time(op.time_ms),
523 "time_ms": op.time_ms,
524 "agent": op.agent,
525 "description": op.description,
526 "undoes": op.undoes,
527 "updates": op.updates.iter().map(|u| json!({
528 "name": u.name,
529 "old": u.old.map(|id| id.to_hex()),
530 "new": u.new.map(|id| id.to_hex()),
531 })).collect::<Vec<_>>(),
532 })
533}
534
535fn print_operation(cli: &Cli, op: &Operation) -> Result<()> {
536 if cli.json {
537 return print_json(&operation_json(op));
538 }
539 let mut out = io::stdout().lock();
540 write_operation(&mut out, op)?;
541 Ok(())
542}
543
544fn write_operation(out: &mut impl Write, op: &Operation) -> io::Result<()> {
545 writeln!(
546 out,
547 "#{} {} {} {}",
548 op.seq,
549 format_time(op.time_ms),
550 op.agent,
551 op.description
552 )?;
553 for update in &op.updates {
554 writeln!(
555 out,
556 " {}: {} -> {}",
557 update.name,
558 short(update.old),
559 short(update.new)
560 )?;
561 }
562 Ok(())
563}
564
565fn short(id: Option<ObjectId>) -> String {
566 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
567}
568
569fn op_log(cli: &Cli, limit: usize) -> Result<ExitCode> {
570 let repo = open_repo(cli)?;
571 let ops = repo.store().log(limit)?;
572 if cli.json {
573 print_json(&Value::Array(ops.iter().map(operation_json).collect()))?;
574 } else {
575 let mut out = io::stdout().lock();
576 for op in &ops {
577 write_operation(&mut out, op)?;
578 }
579 }
580 Ok(ExitCode::SUCCESS)
581}
582
583fn undo(cli: &Cli) -> Result<ExitCode> {
584 let repo = open_repo(cli)?;
585 let op = repo.store().undo_last(&cli.agent)?;
586 print_operation(cli, &op)?;
587 Ok(ExitCode::SUCCESS)
588}
589
590fn fsck(cli: &Cli) -> Result<ExitCode> {
591 let repo = open_repo(cli)?;
592 let report: FsckReport = repo.store().fsck()?;
593 let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
594 if cli.json {
595 print_json(&json!({
596 "clean": report.is_clean(),
597 "segments": report.segments,
598 "sealed_segments": report.sealed_segments,
599 "records": report.records,
600 "objects": report.objects,
601 "operations": report.operations,
602 "refs": report.refs,
603 "problems": problems,
604 }))?;
605 } else {
606 println!(
607 "{} objects in {} segments, {} operations, {} refs",
608 report.objects, report.segments, report.operations, report.refs
609 );
610 for problem in &problems {
611 println!("problem: {problem}");
612 }
613 println!(
614 "{}",
615 if report.is_clean() {
616 "clean"
617 } else {
618 "NOT clean"
619 }
620 );
621 }
622 Ok(if report.is_clean() {
623 ExitCode::SUCCESS
624 } else {
625 ExitCode::FAILURE
626 })
627}
628
629/// A changeset named by a ref, its id or a short id.
630pub(crate) fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
631 Ok(repo.resolve_kind(revision, Kind::Changeset)?)
632}
633
634fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> {
635 match repo.store().get(id)? {
636 Some((Kind::Changeset, bytes)) => {
637 Ok(Changeset::decode(&bytes)
638 .with_context(|| format!("changeset {id} does not decode"))?)
639 }
640 Some((kind, _)) => bail!("{id} is a {kind}, not a changeset"),
641 None => bail!("changeset {id} is not in the store"),
642 }
643}
644
645fn read_changes(repo: &Repo, changeset: &Changeset) -> Result<Vec<Change>> {
646 match &changeset.changes {
647 Changes::Inline(changes) => Ok(changes.clone()),
648 Changes::External { list, .. } => {
649 let Some((_, bytes)) = repo.store().get(list)? else {
650 bail!("change list {list} is not in the store");
651 };
652 Ok(decode_change_list(&bytes)
653 .with_context(|| format!("change list {list} does not decode"))?)
654 }
655 }
656}
657
658fn signature_json(signature: &Signature) -> Value {
659 json!({
660 "name": String::from_utf8_lossy(&signature.name),
661 "email": String::from_utf8_lossy(&signature.email),
662 "seconds": signature.seconds,
663 "offset_minutes": signature.offset_minutes,
664 "time": format_signature_time(signature),
665 })
666}
667
668/// The agent a changeset names in its `agent` field, if it names one.
669fn agent_of(changeset: &Changeset) -> Option<String> {
670 changeset
671 .extras
672 .iter()
673 .find(|(key, _)| key.as_slice() == braid_engine::AGENT)
674 .map(|(_, value)| String::from_utf8_lossy(value).into_owned())
675}
676
677fn changeset_json(id: &ObjectId, changeset: &Changeset) -> Value {
678 json!({
679 "id": id.to_hex(),
680 "parents": changeset.parents.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
681 "root": changeset.root.to_hex(),
682 "author": signature_json(&changeset.author),
683 "committer": signature_json(&changeset.committer),
684 "agent": agent_of(changeset),
685 "message": String::from_utf8_lossy(&changeset.message),
686 "extras": changeset.extras.iter().map(|(k, v)| json!([
687 String::from_utf8_lossy(k), String::from_utf8_lossy(v)
688 ])).collect::<Vec<_>>(),
689 "git_origin": changeset.git_origin.map(|id| id.to_hex()),
690 })
691}
692
693fn subject(message: &[u8]) -> String {
694 let text = String::from_utf8_lossy(message);
695 text.lines()
696 .find(|line| !line.trim().is_empty())
697 .unwrap_or("")
698 .trim()
699 .to_owned()
700}
701
702/// The long help of `log`.
703const LOG_HELP: &str = "Show history from a revision, following first parents, newest first: the
704short id, the author's date, the author with the agent, and the subject.
705
706With paths after `--` (log main -- src/lib.rs docs), only the changesets
707whose changes, against their first parent, touch one of the paths or
708anything below them, as `git log --first-parent -- <path>` lists them.
709Paths are given from the repository's root and renames are not followed.
710Changed-path filters, derived data kept in the store, let the walk skip the
711other changesets without reading them.
712
713With --json, log prints each changeset as show does, without its changes.";
714
715fn log(cli: &Cli, revision: &str, limit: usize, paths: &[String]) -> Result<ExitCode> {
716 let repo = open_repo(cli)?;
717 let head = resolve_changeset(&repo, revision)?;
718 let mut entries = Vec::new();
719 if paths.is_empty() {
720 let mut next = Some(head);
721 while let Some(id) = next {
722 if entries.len() == limit {
723 break;
724 }
725 let changeset = read_changeset(&repo, &id)?;
726 next = changeset.parents.first().copied();
727 entries.push((id, changeset));
728 }
729 } else {
730 for id in history::path_log(&repo, head, paths, limit)? {
731 entries.push((id, read_changeset(&repo, &id)?));
732 }
733 }
734 if cli.json {
735 print_json(&Value::Array(
736 entries
737 .iter()
738 .map(|(id, changeset)| changeset_json(id, changeset))
739 .collect(),
740 ))?;
741 } else {
742 let mut out = io::stdout().lock();
743 for (id, changeset) in &entries {
744 let agent = agent_of(changeset).map_or_else(String::new, |agent| format!(" ({agent})"));
745 writeln!(
746 out,
747 "{} {} {}{agent} {}",
748 id.short(),
749 format_signature_time(&changeset.author),
750 String::from_utf8_lossy(&changeset.author.name),
751 subject(&changeset.message)
752 )?;
753 }
754 }
755 Ok(ExitCode::SUCCESS)
756}
757
758fn change_json(change: &Change) -> Value {
759 let path = String::from_utf8_lossy(&change.path);
760 match &change.op {
761 ChangeOp::Delete => json!({ "path": path, "op": "delete" }),
762 ChangeOp::File { blob, size } => {
763 json!({ "path": path, "op": "file", "blob": blob.to_hex(), "size": size })
764 }
765 ChangeOp::Executable { blob, size } => {
766 json!({ "path": path, "op": "executable", "blob": blob.to_hex(), "size": size })
767 }
768 ChangeOp::Symlink { blob, size } => {
769 json!({ "path": path, "op": "symlink", "blob": blob.to_hex(), "size": size })
770 }
771 ChangeOp::Gitlink { commit } => json!({
772 "path": path,
773 "op": "gitlink",
774 "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
775 }),
776 }
777}
778
779/// How a path changed, as `git diff --name-status` says it: `A` added, `M`
780/// modified (content or executable bit), `D` deleted, or `T` for a change
781/// between a regular file, a symlink and a gitlink. `old` is what was there
782/// before, if a file was.
783fn change_status(old: Option<&ChangeOp>, new: &ChangeOp) -> &'static str {
784 let class = |op: &ChangeOp| match op {
785 ChangeOp::File { .. } | ChangeOp::Executable { .. } => 0,
786 ChangeOp::Symlink { .. } => 1,
787 ChangeOp::Gitlink { .. } => 2,
788 ChangeOp::Delete => 3,
789 };
790 match (old, new) {
791 (_, ChangeOp::Delete) => "D",
792 (None, _) => "A",
793 (Some(old), new) if class(old) == class(new) => "M",
794 (Some(_), _) => "T",
795 }
796}
797
798/// What the tree `old` has at each path where the tree `new` differs from
799/// it: the change list of the diff back from `new` to `old`, one walk over
800/// the difference.
801fn old_entries(repo: &Repo, old: ObjectId, new: ObjectId) -> Result<HashMap<Vec<u8>, ChangeOp>> {
802 Ok(braid_engine::diff(repo.store(), new, old)?
803 .into_iter()
804 .filter(|change| !matches!(change.op, ChangeOp::Delete))
805 .map(|change| (change.path, change.op))
806 .collect())
807}
808
809/// A change as JSON, with its status and the file it replaced.
810fn change_with_status_json(change: &Change, old: Option<&ChangeOp>) -> Value {
811 let mut value = change_json(change);
812 value["status"] = Value::String(change_status(old, &change.op).to_owned());
813 value["old"] = match old {
814 Some(op) => {
815 let mut old = change_json(&Change {
816 path: change.path.clone(),
817 op: op.clone(),
818 });
819 if let Some(fields) = old.as_object_mut() {
820 fields.remove("path");
821 }
822 old
823 }
824 None => Value::Null,
825 };
826 value
827}
828
829/// Prints changes as `git diff --name-status` does: the status, a tab and
830/// the path.
831fn write_name_status(
832 out: &mut impl Write,
833 changes: &[Change],
834 olds: &HashMap<Vec<u8>, ChangeOp>,
835) -> io::Result<()> {
836 for change in changes {
837 let status = change_status(olds.get(&change.path), &change.op);
838 writeln!(out, "{status}\t{}", String::from_utf8_lossy(&change.path))?;
839 }
840 Ok(())
841}
842
843/// The long help of `diff`.
844const DIFF_HELP: &str = "Show the files that differ between two changesets, one line each: a
845status, a tab and the path, as `git diff --name-status` prints them. The
846status is A (added), M (modified: content or executable bit), D (deleted)
847or T (type changed: between a regular file, a symlink and a gitlink). A
848directory that became a file, or the other way round, is a D for every
849file it had and an A for every file it has.
850
851With --json, diff prints from and to, the two changesets' full ids, and
852changes: one per path, sorted by path bytes, with path, status, op (file,
853executable, symlink, gitlink or delete) with blob and size, and old, what
854the path held before, or null.";
855
856fn diff(cli: &Cli, from: &str, to: &str) -> Result<ExitCode> {
857 let repo = open_repo(cli)?;
858 let from = resolve_changeset(&repo, from)?;
859 let to = resolve_changeset(&repo, to)?;
860 let (from_root, to_root) = (
861 read_changeset(&repo, &from)?.root,
862 read_changeset(&repo, &to)?.root,
863 );
864 let changes = braid_engine::diff(repo.store(), from_root, to_root)?;
865 let olds = old_entries(&repo, from_root, to_root)?;
866 if cli.json {
867 print_json(&json!({
868 "from": from.to_hex(),
869 "to": to.to_hex(),
870 "changes": changes
871 .iter()
872 .map(|change| change_with_status_json(change, olds.get(&change.path)))
873 .collect::<Vec<_>>(),
874 }))?;
875 } else {
876 write_name_status(&mut io::stdout().lock(), &changes, &olds)?;
877 }
878 Ok(ExitCode::SUCCESS)
879}
880
881fn show(cli: &Cli, revision: &str) -> Result<ExitCode> {
882 let repo = open_repo(cli)?;
883 let id = resolve_changeset(&repo, revision)?;
884 let changeset = read_changeset(&repo, &id)?;
885 let changes = read_changes(&repo, &changeset)?;
886 // The change list is against the first parent: what that has at each
887 // path tells added from modified.
888 let parent_root = match changeset.parents.first() {
889 Some(parent) => read_changeset(&repo, parent)?.root,
890 None => braid_engine::EMPTY_TREE,
891 };
892 let olds = old_entries(&repo, parent_root, changeset.root)?;
893 if cli.json {
894 let mut value = changeset_json(&id, &changeset);
895 value["changes"] = changes
896 .iter()
897 .map(|change| change_with_status_json(change, olds.get(&change.path)))
898 .collect();
899 print_json(&value)?;
900 return Ok(ExitCode::SUCCESS);
901 }
902 let mut out = io::stdout().lock();
903 writeln!(out, "changeset {id}")?;
904 for parent in &changeset.parents {
905 writeln!(out, "parent {parent}")?;
906 }
907 writeln!(out, "root {}", changeset.root)?;
908 for (label, signature) in [
909 ("author", &changeset.author),
910 ("committer", &changeset.committer),
911 ] {
912 writeln!(
913 out,
914 "{label:<9} {} <{}> {}",
915 String::from_utf8_lossy(&signature.name),
916 String::from_utf8_lossy(&signature.email),
917 format_signature_time(signature)
918 )?;
919 }
920 if let Some(agent) = agent_of(&changeset) {
921 writeln!(out, "agent {agent}")?;
922 }
923 writeln!(out)?;
924 for line in String::from_utf8_lossy(&changeset.message).lines() {
925 writeln!(out, " {line}")?;
926 }
927 writeln!(out)?;
928 write_name_status(&mut out, &changes, &olds)?;
929 Ok(ExitCode::SUCCESS)
930}
931
932fn git_import(cli: &Cli, path: &Path) -> Result<ExitCode> {
933 let repo = open_repo(cli)?;
934 let import = repo.git_import(path, &cli.agent)?;
935 let report = &import.report;
936 let refs: Vec<Value> = report
937 .refs
938 .iter()
939 .map(|r| {
940 json!({
941 "git": String::from_utf8_lossy(&r.name),
942 "braid": braid_repo::braid_ref_for_git(&r.name),
943 "id": r.braid.to_hex(),
944 })
945 })
946 .collect();
947 if cli.json {
948 print_json(&json!({
949 "commits": report.commits,
950 "trees": report.trees,
951 "raw_trees": report.raw_trees,
952 "blobs": report.blobs,
953 "tags": report.tags,
954 "refs": refs,
955 "operation": import.operation.as_ref().map(|op| op.seq),
956 }))?;
957 } else {
958 println!(
959 "Imported {} commits, {} trees, {} blobs, {} tags; {} refs",
960 report.commits,
961 report.trees,
962 report.blobs,
963 report.tags,
964 report.refs.len()
965 );
966 if import.operation.is_none() {
967 println!("Nothing changed.");
968 }
969 }
970 Ok(ExitCode::SUCCESS)
971}
972
973fn git_export(cli: &Cli, path: &Path, names: &[String]) -> Result<ExitCode> {
974 let repo = open_repo(cli)?;
975 let report = repo.git_export_as(path, names, &cli.agent)?;
976 if cli.json {
977 print_json(&json!({
978 "commits": report.commits,
979 "trees": report.trees,
980 "blobs": report.blobs,
981 "tags": report.tags,
982 "refs": report.refs.iter().map(|(name, oid)| json!({
983 "name": String::from_utf8_lossy(name),
984 "id": oid.to_string(),
985 })).collect::<Vec<_>>(),
986 }))?;
987 } else {
988 println!(
989 "Wrote {} commits, {} trees, {} blobs, {} tags; {} refs",
990 report.commits,
991 report.trees,
992 report.blobs,
993 report.tags,
994 report.refs.len()
995 );
996 }
997 Ok(ExitCode::SUCCESS)
998}
999
1000/// Formats a signature's time in its own offset: `YYYY-MM-DD HH:MM ±HHMM`.
1001fn format_signature_time(signature: &Signature) -> String {
1002 let local = signature
1003 .seconds
1004 .saturating_add(signature.offset_minutes.saturating_mul(60));
1005 let days = local.div_euclid(86_400);
1006 let of_day = local.rem_euclid(86_400);
1007 let (year, month, day) = civil_from_days(days);
1008 let sign = if signature.offset_minutes < 0 {
1009 '-'
1010 } else {
1011 '+'
1012 };
1013 let offset = signature.offset_minutes.unsigned_abs();
1014 format!(
1015 "{year:04}-{month:02}-{day:02} {:02}:{:02} {sign}{:02}{:02}",
1016 of_day / 3600,
1017 of_day % 3600 / 60,
1018 offset / 60,
1019 offset % 60
1020 )
1021}
1022
1023/// Formats milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SS UTC`.
1024fn format_time(time_ms: i64) -> String {
1025 let seconds = time_ms.div_euclid(1000);
1026 let days = seconds.div_euclid(86_400);
1027 let of_day = seconds.rem_euclid(86_400);
1028 let (year, month, day) = civil_from_days(days);
1029 format!(
1030 "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02} UTC",
1031 of_day / 3600,
1032 of_day % 3600 / 60,
1033 of_day % 60
1034 )
1035}
1036
1037/// Days since 1970-01-01 to a proleptic Gregorian date.
1038fn civil_from_days(days: i64) -> (i64, u32, u32) {
1039 let z = days + 719_468;
1040 let era = z.div_euclid(146_097);
1041 let doe = z.rem_euclid(146_097);
1042 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1043 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1044 let mp = (5 * doy + 2) / 153;
1045 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1046 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1047 let year = yoe + era * 400 + i64::from(month <= 2);
1048 (year, month, day)
1049}
1050
1051#[cfg(test)]
1052mod tests {
1053 use super::*;
1054
1055 #[test]
1056 fn the_status_help_states_the_walk_limit() {
1057 let limit = format!("more than {}", braid_wc::BEHIND_LIMIT);
1058 assert!(work::STATUS_HELP.contains(&limit));
1059 }
1060
1061 #[test]
1062 fn time_formatting() {
1063 assert_eq!(format_time(0), "1970-01-01 00:00:00 UTC");
1064 assert_eq!(format_time(1_700_000_000_000), "2023-11-14 22:13:20 UTC");
1065 assert_eq!(format_time(951_782_400_000), "2000-02-29 00:00:00 UTC");
1066 assert_eq!(format_time(-1000), "1969-12-31 23:59:59 UTC");
1067 }
1068}