Elffuss BraidHub

utopia-ia/elffuss-braid public

c03d76685fb3 · 27.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid`, the command-line tool.
5
6mod sync;
7mod work;
8
9use std::fs::File;
10use std::io::{self, Read, Write};
11use std::path::{Path, PathBuf};
12use std::process::ExitCode;
13
14use anyhow::{Context, Result, bail};
15use braid_format::changeset::decode_change_list;
16use braid_format::{
17 Change, ChangeOp, Changes, Changeset, IdHasher, Kind, ObjectId, Objects, Signature,
18};
19use braid_repo::Repo;
20use braid_store::{FsckReport, Operation, RefUpdate};
21use clap::{Parser, Subcommand};
22use serde_json::{Value, json};
23
24/// Version control for many agents landing changes at once.
25#[derive(Debug, Parser)]
26#[command(name = "braid", version, about, long_about = None)]
27struct Cli {
28 /// Print machine-readable JSON instead of text.
29 #[arg(long, global = true)]
30 json: bool,
31
32 /// Repository root (default: the current directory or its nearest parent
33 /// holding a `.braid` directory).
34 #[arg(long, global = true, value_name = "DIR")]
35 repo: Option<PathBuf>,
36
37 /// Label recorded in the op log for operations made by this command.
38 #[arg(long, global = true, env = "BRAID_AGENT", default_value = "cli")]
39 agent: String,
40
41 /// Workspace to act on (default: the one containing the current
42 /// directory).
43 #[arg(long, global = true, value_name = "NAME")]
44 workspace: Option<String>,
45
46 #[command(subcommand)]
47 command: Command,
48}
49
50#[derive(Debug, Subcommand)]
51enum Command {
52 /// Create a repository.
53 Init {
54 /// Directory to create it in (default: the current directory).
55 dir: Option<PathBuf>,
56 },
57 /// Print the braid blob id of each file ("-" reads standard input).
58 HashObject {
59 /// Also store each file in the repository.
60 #[arg(short, long)]
61 write: bool,
62 /// Files to hash.
63 #[arg(required = true)]
64 paths: Vec<PathBuf>,
65 },
66 /// Write an object's raw payload to standard output.
67 CatObject {
68 /// A ref, an object id, or a short id (6 hex digits or more).
69 revision: String,
70 },
71 /// List refs and the objects they point at.
72 Refs,
73 /// Move or delete a ref in one op log transaction.
74 Ref {
75 #[command(subcommand)]
76 action: RefAction,
77 },
78 /// Inspect and rewind the op log.
79 Op {
80 #[command(subcommand)]
81 action: OpAction,
82 },
83 /// Revert the newest operation that is not already undone.
84 Undo,
85 /// Show history, following first parents.
86 Log {
87 /// Where to start: a ref, a changeset id, or a short id (6 hex
88 /// digits or more).
89 #[arg(default_value = "main")]
90 revision: String,
91 /// How many changesets to show.
92 #[arg(short = 'n', long, default_value_t = 20)]
93 limit: usize,
94 },
95 /// Show one changeset: parents, root, signatures, message, changed paths.
96 Show {
97 /// A ref, a changeset id, or a short id (6 hex digits or more).
98 #[arg(default_value = "main")]
99 revision: String,
100 },
101 /// Import from and export to git repositories.
102 Git {
103 #[command(subcommand)]
104 action: GitAction,
105 },
106 /// Check every record, index, op log entry and ref of the store.
107 Fsck,
108 /// Create, list and remove workspaces.
109 Workspace {
110 #[command(subcommand)]
111 action: work::WorkspaceAction,
112 },
113 /// Show how the workspace differs from its base and its branch.
114 Status,
115 /// Record the workspace's changes as a changeset on its base.
116 Commit(work::CommitArgs),
117 /// Land the workspace's changesets on its branch (exit status 2 on
118 /// conflicts).
119 Land(work::LandArgs),
120 /// Bring the workspace onto its branch's head, rebasing its own
121 /// changesets (exit status 2 on conflicts).
122 Update(work::IdentityArgs),
123 /// Mark conflicts of a rebase in progress resolved.
124 Resolve {
125 /// Paths whose conflicts are settled.
126 #[arg(required = true)]
127 paths: Vec<PathBuf>,
128 },
129 /// Let new files that look like secrets or are large be committed.
130 Track {
131 /// Files, or directories whose new files may be committed.
132 #[arg(required = true)]
133 paths: Vec<PathBuf>,
134 },
135 /// Make changesets without a working copy.
136 Change {
137 #[command(subcommand)]
138 action: work::ChangeAction,
139 },
140}
141
142#[derive(Debug, Subcommand)]
143enum RefAction {
144 /// Point a ref at an object.
145 Set {
146 /// Ref name.
147 name: String,
148 /// What to point at: a ref, an object id, or a short id (6 hex
149 /// digits or more).
150 target: String,
151 /// Only move the ref if it currently points at this id ("none" if it
152 /// must not exist yet).
153 #[arg(long, value_name = "ID")]
154 expect: Option<String>,
155 },
156 /// Delete a ref.
157 Delete {
158 /// Ref name.
159 name: String,
160 },
161}
162
163#[derive(Debug, Subcommand)]
164enum GitAction {
165 /// Import every branch and tag of a git repository. Running it again
166 /// imports only what is new.
167 Import {
168 /// The git repository (a working tree or a bare repository).
169 path: PathBuf,
170 },
171 /// Write braid refs, and everything they reach, into an existing git
172 /// repository. Git refs of the same names are overwritten.
173 Export {
174 /// The git repository.
175 path: PathBuf,
176 /// A braid ref to export; repeat for several (default: all).
177 #[arg(long = "ref", value_name = "NAME")]
178 refs: Vec<String>,
179 },
180 /// Keep a braid branch and a branch of a git remote in step: fetch and
181 /// import the remote branch, then fast-forward the braid branch, or push
182 /// it (merging first when both moved) as a fast-forward with a lease.
183 /// Never force-pushes. Exits with 2 on conflicts and 1 when the push is
184 /// refused.
185 Sync {
186 /// The git remote: a URL or a path.
187 remote: String,
188 /// The braid branch.
189 #[arg(long, default_value = "main")]
190 branch: String,
191 /// The branch of the remote (default: the braid branch's name).
192 #[arg(long, value_name = "NAME")]
193 remote_branch: Option<String>,
194 /// Report what would happen without writing anything.
195 #[arg(long)]
196 dry_run: bool,
197 },
198}
199
200#[derive(Debug, Subcommand)]
201enum OpAction {
202 /// Show the newest operations, newest first.
203 Log {
204 /// How many to show.
205 #[arg(short = 'n', long, default_value_t = 20)]
206 limit: usize,
207 },
208}
209
210fn main() -> ExitCode {
211 let cli = Cli::parse();
212 match run(&cli) {
213 Ok(code) => code,
214 Err(err) => {
215 eprintln!("braid: error: {err:#}");
216 ExitCode::FAILURE
217 }
218 }
219}
220
221fn run(cli: &Cli) -> Result<ExitCode> {
222 match &cli.command {
223 Command::Init { dir } => init(cli, dir.as_deref()),
224 Command::HashObject { write, paths } => hash_object(cli, paths, *write),
225 Command::CatObject { revision } => cat_object(cli, revision),
226 Command::Refs => refs(cli),
227 Command::Ref { action } => ref_action(cli, action),
228 Command::Op {
229 action: OpAction::Log { limit },
230 } => op_log(cli, *limit),
231 Command::Undo => undo(cli),
232 Command::Log { revision, limit } => log(cli, revision, *limit),
233 Command::Show { revision } => show(cli, revision),
234 Command::Git {
235 action: GitAction::Import { path },
236 } => git_import(cli, path),
237 Command::Git {
238 action: GitAction::Export { path, refs },
239 } => git_export(cli, path, refs),
240 Command::Git {
241 action:
242 GitAction::Sync {
243 remote,
244 branch,
245 remote_branch,
246 dry_run,
247 },
248 } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run),
249 Command::Fsck => fsck(cli),
250 Command::Workspace { action } => work::workspace(cli, action),
251 Command::Status => work::status(cli),
252 Command::Commit(args) => work::commit(cli, args),
253 Command::Land(args) => work::land(cli, args),
254 Command::Update(args) => work::update(cli, args),
255 Command::Resolve { paths } => work::resolve(cli, paths),
256 Command::Track { paths } => work::track(cli, paths),
257 Command::Change { action } => work::change(cli, action),
258 }
259}
260
261fn open_repo(cli: &Cli) -> Result<Repo> {
262 let repo = match &cli.repo {
263 Some(dir) => Repo::open(dir),
264 None => Repo::discover(&std::env::current_dir()?),
265 };
266 Ok(repo?)
267}
268
269fn print_json(value: &Value) -> Result<()> {
270 let mut out = io::stdout().lock();
271 serde_json::to_writer(&mut out, value)?;
272 writeln!(out)?;
273 Ok(())
274}
275
276fn init(cli: &Cli, dir: Option<&Path>) -> Result<ExitCode> {
277 let dir = match dir {
278 Some(dir) => dir.to_path_buf(),
279 None => std::env::current_dir()?,
280 };
281 let repo = Repo::init(&dir)?;
282 if cli.json {
283 print_json(&json!({ "root": repo.root().to_string_lossy() }))?;
284 } else {
285 println!(
286 "Created an empty braid repository in {}",
287 repo.root().join(braid_repo::DIR).display()
288 );
289 }
290 Ok(ExitCode::SUCCESS)
291}
292
293struct Hashed<'a> {
294 path: &'a Path,
295 id: ObjectId,
296 size: u64,
297}
298
299fn hash_object(cli: &Cli, paths: &[PathBuf], write: bool) -> Result<ExitCode> {
300 let repo = if write { Some(open_repo(cli)?) } else { None };
301 let mut hashed = Vec::with_capacity(paths.len());
302 for path in paths {
303 let (id, size) = match &repo {
304 // Storing needs the whole payload; the store compresses it.
305 Some(repo) => {
306 let bytes = read_input(path)?;
307 let id = repo.store().put(Kind::Blob, &bytes)?;
308 (id, bytes.len() as u64)
309 }
310 None if path.as_os_str() == "-" => {
311 hash_blob(io::stdin().lock()).context("cannot read standard input")?
312 }
313 None => {
314 let file =
315 File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
316 hash_blob(file).with_context(|| format!("cannot read {}", path.display()))?
317 }
318 };
319 hashed.push(Hashed { path, id, size });
320 }
321 if let Some(repo) = &repo {
322 repo.store().sync()?;
323 }
324
325 if cli.json {
326 let items: Vec<Value> = hashed
327 .iter()
328 .map(|h| {
329 json!({
330 "path": h.path.to_string_lossy(),
331 "kind": Kind::Blob.name(),
332 "id": h.id.to_hex(),
333 "size": h.size,
334 })
335 })
336 .collect();
337 print_json(&Value::Array(items))?;
338 } else {
339 let mut out = io::stdout().lock();
340 for h in &hashed {
341 writeln!(out, "{} {}", h.id, h.path.display())?;
342 }
343 }
344 Ok(ExitCode::SUCCESS)
345}
346
347fn read_input(path: &Path) -> Result<Vec<u8>> {
348 let mut bytes = Vec::new();
349 if path.as_os_str() == "-" {
350 io::stdin()
351 .lock()
352 .read_to_end(&mut bytes)
353 .context("cannot read standard input")?;
354 } else {
355 File::open(path)
356 .with_context(|| format!("cannot open {}", path.display()))?
357 .read_to_end(&mut bytes)
358 .with_context(|| format!("cannot read {}", path.display()))?;
359 }
360 Ok(bytes)
361}
362
363/// Hashes a stream as a blob without holding it in memory.
364fn hash_blob(mut reader: impl Read) -> io::Result<(ObjectId, u64)> {
365 let mut hasher = IdHasher::new(Kind::Blob);
366 let mut buf = vec![0u8; 256 * 1024];
367 let mut size = 0u64;
368 loop {
369 let n = match reader.read(&mut buf) {
370 Ok(0) => break,
371 Ok(n) => n,
372 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
373 Err(err) => return Err(err),
374 };
375 hasher.update(&buf[..n]);
376 size += n as u64;
377 }
378 Ok((hasher.finalize(), size))
379}
380
381fn cat_object(cli: &Cli, revision: &str) -> Result<ExitCode> {
382 let repo = open_repo(cli)?;
383 let id = repo.resolve(revision)?;
384 let Some((kind, payload)) = repo.store().get(&id)? else {
385 bail!("object {id} is not in the store");
386 };
387 if cli.json {
388 print_json(&json!({
389 "id": id.to_hex(),
390 "kind": kind.name(),
391 "size": payload.len(),
392 }))?;
393 } else {
394 io::stdout().lock().write_all(&payload)?;
395 }
396 Ok(ExitCode::SUCCESS)
397}
398
399fn refs(cli: &Cli) -> Result<ExitCode> {
400 let repo = open_repo(cli)?;
401 let refs = repo.store().refs()?;
402 if cli.json {
403 let map: serde_json::Map<String, Value> = refs
404 .iter()
405 .map(|(name, id)| (name.to_owned(), Value::String(id.to_hex())))
406 .collect();
407 print_json(&json!({ "seq": refs.seq(), "refs": map }))?;
408 } else {
409 for (name, id) in refs.iter() {
410 println!("{id} {name}");
411 }
412 }
413 Ok(ExitCode::SUCCESS)
414}
415
416fn parse_expect(text: &str) -> Result<Option<ObjectId>> {
417 if text == "none" {
418 Ok(None)
419 } else {
420 Ok(Some(text.parse().with_context(|| {
421 format!("--expect takes a full object id or \"none\", not {text:?}")
422 })?))
423 }
424}
425
426fn ref_action(cli: &Cli, action: &RefAction) -> Result<ExitCode> {
427 let repo = open_repo(cli)?;
428 let (name, new, expect, description) = match action {
429 RefAction::Set {
430 name,
431 target,
432 expect,
433 } => (
434 name,
435 Some(repo.resolve(target)?),
436 expect.as_deref().map(parse_expect).transpose()?,
437 format!("ref set {name}"),
438 ),
439 RefAction::Delete { name } => (name, None, None, format!("ref delete {name}")),
440 };
441 let op = repo
442 .store()
443 .transact(&cli.agent, &description, |refs| {
444 let current = refs.get(name);
445 if let Some(expected) = expect
446 && expected != current
447 {
448 return Err(format!(
449 "ref {name} points at {}, not the expected {}",
450 show_id(current),
451 show_id(expected)
452 ));
453 }
454 if new.is_none() && current.is_none() {
455 return Err(format!("ref {name} does not exist"));
456 }
457 Ok(vec![RefUpdate::new(name.clone(), current, new)])
458 })
459 .map_err(|err| anyhow::anyhow!("{err}"))?;
460 print_operation(cli, &op)?;
461 Ok(ExitCode::SUCCESS)
462}
463
464fn show_id(id: Option<ObjectId>) -> String {
465 id.map_or_else(|| "nothing".to_owned(), |id| id.to_hex())
466}
467
468fn operation_json(op: &Operation) -> Value {
469 json!({
470 "seq": op.seq,
471 "time": format_time(op.time_ms),
472 "time_ms": op.time_ms,
473 "agent": op.agent,
474 "description": op.description,
475 "undoes": op.undoes,
476 "updates": op.updates.iter().map(|u| json!({
477 "name": u.name,
478 "old": u.old.map(|id| id.to_hex()),
479 "new": u.new.map(|id| id.to_hex()),
480 })).collect::<Vec<_>>(),
481 })
482}
483
484fn print_operation(cli: &Cli, op: &Operation) -> Result<()> {
485 if cli.json {
486 return print_json(&operation_json(op));
487 }
488 let mut out = io::stdout().lock();
489 write_operation(&mut out, op)?;
490 Ok(())
491}
492
493fn write_operation(out: &mut impl Write, op: &Operation) -> io::Result<()> {
494 writeln!(
495 out,
496 "#{} {} {} {}",
497 op.seq,
498 format_time(op.time_ms),
499 op.agent,
500 op.description
501 )?;
502 for update in &op.updates {
503 writeln!(
504 out,
505 " {}: {} -> {}",
506 update.name,
507 short(update.old),
508 short(update.new)
509 )?;
510 }
511 Ok(())
512}
513
514fn short(id: Option<ObjectId>) -> String {
515 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
516}
517
518fn op_log(cli: &Cli, limit: usize) -> Result<ExitCode> {
519 let repo = open_repo(cli)?;
520 let ops = repo.store().log(limit)?;
521 if cli.json {
522 print_json(&Value::Array(ops.iter().map(operation_json).collect()))?;
523 } else {
524 let mut out = io::stdout().lock();
525 for op in &ops {
526 write_operation(&mut out, op)?;
527 }
528 }
529 Ok(ExitCode::SUCCESS)
530}
531
532fn undo(cli: &Cli) -> Result<ExitCode> {
533 let repo = open_repo(cli)?;
534 let op = repo.store().undo_last(&cli.agent)?;
535 print_operation(cli, &op)?;
536 Ok(ExitCode::SUCCESS)
537}
538
539fn fsck(cli: &Cli) -> Result<ExitCode> {
540 let repo = open_repo(cli)?;
541 let report: FsckReport = repo.store().fsck()?;
542 let problems: Vec<String> = report.problems.iter().map(ToString::to_string).collect();
543 if cli.json {
544 print_json(&json!({
545 "clean": report.is_clean(),
546 "segments": report.segments,
547 "sealed_segments": report.sealed_segments,
548 "records": report.records,
549 "objects": report.objects,
550 "operations": report.operations,
551 "refs": report.refs,
552 "problems": problems,
553 }))?;
554 } else {
555 println!(
556 "{} objects in {} segments, {} operations, {} refs",
557 report.objects, report.segments, report.operations, report.refs
558 );
559 for problem in &problems {
560 println!("problem: {problem}");
561 }
562 println!(
563 "{}",
564 if report.is_clean() {
565 "clean"
566 } else {
567 "NOT clean"
568 }
569 );
570 }
571 Ok(if report.is_clean() {
572 ExitCode::SUCCESS
573 } else {
574 ExitCode::FAILURE
575 })
576}
577
578/// A changeset named by a ref, its id or a short id.
579pub(crate) fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
580 Ok(repo.resolve_kind(revision, Kind::Changeset)?)
581}
582
583fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> {
584 match repo.store().get(id)? {
585 Some((Kind::Changeset, bytes)) => {
586 Ok(Changeset::decode(&bytes)
587 .with_context(|| format!("changeset {id} does not decode"))?)
588 }
589 Some((kind, _)) => bail!("{id} is a {kind}, not a changeset"),
590 None => bail!("changeset {id} is not in the store"),
591 }
592}
593
594fn read_changes(repo: &Repo, changeset: &Changeset) -> Result<Vec<Change>> {
595 match &changeset.changes {
596 Changes::Inline(changes) => Ok(changes.clone()),
597 Changes::External { list, .. } => {
598 let Some((_, bytes)) = repo.store().get(list)? else {
599 bail!("change list {list} is not in the store");
600 };
601 Ok(decode_change_list(&bytes)
602 .with_context(|| format!("change list {list} does not decode"))?)
603 }
604 }
605}
606
607fn signature_json(signature: &Signature) -> Value {
608 json!({
609 "name": String::from_utf8_lossy(&signature.name),
610 "email": String::from_utf8_lossy(&signature.email),
611 "seconds": signature.seconds,
612 "offset_minutes": signature.offset_minutes,
613 "time": format_signature_time(signature),
614 })
615}
616
617fn changeset_json(id: &ObjectId, changeset: &Changeset) -> Value {
618 json!({
619 "id": id.to_hex(),
620 "parents": changeset.parents.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
621 "root": changeset.root.to_hex(),
622 "author": signature_json(&changeset.author),
623 "committer": signature_json(&changeset.committer),
624 "message": String::from_utf8_lossy(&changeset.message),
625 "extras": changeset.extras.iter().map(|(k, v)| json!([
626 String::from_utf8_lossy(k), String::from_utf8_lossy(v)
627 ])).collect::<Vec<_>>(),
628 "git_origin": changeset.git_origin.map(|id| id.to_hex()),
629 })
630}
631
632fn subject(message: &[u8]) -> String {
633 let text = String::from_utf8_lossy(message);
634 text.lines()
635 .find(|line| !line.trim().is_empty())
636 .unwrap_or("")
637 .trim()
638 .to_owned()
639}
640
641fn log(cli: &Cli, revision: &str, limit: usize) -> Result<ExitCode> {
642 let repo = open_repo(cli)?;
643 let mut next = Some(resolve_changeset(&repo, revision)?);
644 let mut entries = Vec::new();
645 while let Some(id) = next {
646 if entries.len() == limit {
647 break;
648 }
649 let changeset = read_changeset(&repo, &id)?;
650 next = changeset.parents.first().copied();
651 entries.push((id, changeset));
652 }
653 if cli.json {
654 print_json(&Value::Array(
655 entries
656 .iter()
657 .map(|(id, changeset)| changeset_json(id, changeset))
658 .collect(),
659 ))?;
660 } else {
661 let mut out = io::stdout().lock();
662 for (id, changeset) in &entries {
663 writeln!(
664 out,
665 "{} {} {} {}",
666 id.short(),
667 format_signature_time(&changeset.author),
668 String::from_utf8_lossy(&changeset.author.name),
669 subject(&changeset.message)
670 )?;
671 }
672 }
673 Ok(ExitCode::SUCCESS)
674}
675
676fn change_json(change: &Change) -> Value {
677 let path = String::from_utf8_lossy(&change.path);
678 match &change.op {
679 ChangeOp::Delete => json!({ "path": path, "op": "delete" }),
680 ChangeOp::File { blob, size } => {
681 json!({ "path": path, "op": "file", "blob": blob.to_hex(), "size": size })
682 }
683 ChangeOp::Executable { blob, size } => {
684 json!({ "path": path, "op": "executable", "blob": blob.to_hex(), "size": size })
685 }
686 ChangeOp::Symlink { blob, size } => {
687 json!({ "path": path, "op": "symlink", "blob": blob.to_hex(), "size": size })
688 }
689 ChangeOp::Gitlink { commit } => json!({
690 "path": path,
691 "op": "gitlink",
692 "commit": commit.as_bytes().iter().map(|b| format!("{b:02x}")).collect::<String>(),
693 }),
694 }
695}
696
697fn show(cli: &Cli, revision: &str) -> Result<ExitCode> {
698 let repo = open_repo(cli)?;
699 let id = resolve_changeset(&repo, revision)?;
700 let changeset = read_changeset(&repo, &id)?;
701 let changes = read_changes(&repo, &changeset)?;
702 if cli.json {
703 let mut value = changeset_json(&id, &changeset);
704 value["changes"] = Value::Array(changes.iter().map(change_json).collect());
705 print_json(&value)?;
706 return Ok(ExitCode::SUCCESS);
707 }
708 let mut out = io::stdout().lock();
709 writeln!(out, "changeset {id}")?;
710 for parent in &changeset.parents {
711 writeln!(out, "parent {parent}")?;
712 }
713 writeln!(out, "root {}", changeset.root)?;
714 for (label, signature) in [
715 ("author", &changeset.author),
716 ("committer", &changeset.committer),
717 ] {
718 writeln!(
719 out,
720 "{label:<9} {} <{}> {}",
721 String::from_utf8_lossy(&signature.name),
722 String::from_utf8_lossy(&signature.email),
723 format_signature_time(signature)
724 )?;
725 }
726 writeln!(out)?;
727 for line in String::from_utf8_lossy(&changeset.message).lines() {
728 writeln!(out, " {line}")?;
729 }
730 writeln!(out)?;
731 for change in &changes {
732 let op = match change.op {
733 ChangeOp::Delete => "delete",
734 ChangeOp::File { .. } => "file",
735 ChangeOp::Executable { .. } => "exec",
736 ChangeOp::Symlink { .. } => "link",
737 ChangeOp::Gitlink { .. } => "gitlink",
738 };
739 writeln!(out, "{op:<8} {}", String::from_utf8_lossy(&change.path))?;
740 }
741 Ok(ExitCode::SUCCESS)
742}
743
744fn git_import(cli: &Cli, path: &Path) -> Result<ExitCode> {
745 let repo = open_repo(cli)?;
746 let import = repo.git_import(path, &cli.agent)?;
747 let report = &import.report;
748 let refs: Vec<Value> = report
749 .refs
750 .iter()
751 .map(|r| {
752 json!({
753 "git": String::from_utf8_lossy(&r.name),
754 "braid": braid_repo::braid_ref_for_git(&r.name),
755 "id": r.braid.to_hex(),
756 })
757 })
758 .collect();
759 if cli.json {
760 print_json(&json!({
761 "commits": report.commits,
762 "trees": report.trees,
763 "raw_trees": report.raw_trees,
764 "blobs": report.blobs,
765 "tags": report.tags,
766 "refs": refs,
767 "operation": import.operation.as_ref().map(|op| op.seq),
768 }))?;
769 } else {
770 println!(
771 "Imported {} commits, {} trees, {} blobs, {} tags; {} refs",
772 report.commits,
773 report.trees,
774 report.blobs,
775 report.tags,
776 report.refs.len()
777 );
778 if import.operation.is_none() {
779 println!("Nothing changed.");
780 }
781 }
782 Ok(ExitCode::SUCCESS)
783}
784
785fn git_export(cli: &Cli, path: &Path, names: &[String]) -> Result<ExitCode> {
786 let repo = open_repo(cli)?;
787 let report = repo.git_export_as(path, names, &cli.agent)?;
788 if cli.json {
789 print_json(&json!({
790 "commits": report.commits,
791 "trees": report.trees,
792 "blobs": report.blobs,
793 "tags": report.tags,
794 "refs": report.refs.iter().map(|(name, oid)| json!({
795 "name": String::from_utf8_lossy(name),
796 "id": oid.to_string(),
797 })).collect::<Vec<_>>(),
798 }))?;
799 } else {
800 println!(
801 "Wrote {} commits, {} trees, {} blobs, {} tags; {} refs",
802 report.commits,
803 report.trees,
804 report.blobs,
805 report.tags,
806 report.refs.len()
807 );
808 }
809 Ok(ExitCode::SUCCESS)
810}
811
812/// Formats a signature's time in its own offset: `YYYY-MM-DD HH:MM ±HHMM`.
813fn format_signature_time(signature: &Signature) -> String {
814 let local = signature
815 .seconds
816 .saturating_add(signature.offset_minutes.saturating_mul(60));
817 let days = local.div_euclid(86_400);
818 let of_day = local.rem_euclid(86_400);
819 let (year, month, day) = civil_from_days(days);
820 let sign = if signature.offset_minutes < 0 {
821 '-'
822 } else {
823 '+'
824 };
825 let offset = signature.offset_minutes.unsigned_abs();
826 format!(
827 "{year:04}-{month:02}-{day:02} {:02}:{:02} {sign}{:02}{:02}",
828 of_day / 3600,
829 of_day % 3600 / 60,
830 offset / 60,
831 offset % 60
832 )
833}
834
835/// Formats milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SS UTC`.
836fn format_time(time_ms: i64) -> String {
837 let seconds = time_ms.div_euclid(1000);
838 let days = seconds.div_euclid(86_400);
839 let of_day = seconds.rem_euclid(86_400);
840 let (year, month, day) = civil_from_days(days);
841 format!(
842 "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02} UTC",
843 of_day / 3600,
844 of_day % 3600 / 60,
845 of_day % 60
846 )
847}
848
849/// Days since 1970-01-01 to a proleptic Gregorian date.
850fn civil_from_days(days: i64) -> (i64, u32, u32) {
851 let z = days + 719_468;
852 let era = z.div_euclid(146_097);
853 let doe = z.rem_euclid(146_097);
854 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
855 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
856 let mp = (5 * doy + 2) / 153;
857 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
858 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
859 let year = yoe + era * 400 + i64::from(month <= 2);
860 (year, month, day)
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866
867 #[test]
868 fn time_formatting() {
869 assert_eq!(format_time(0), "1970-01-01 00:00:00 UTC");
870 assert_eq!(format_time(1_700_000_000_000), "2023-11-14 22:13:20 UTC");
871 assert_eq!(format_time(951_782_400_000), "2000-02-29 00:00:00 UTC");
872 assert_eq!(format_time(-1000), "1969-12-31 23:59:59 UTC");
873 }
874}