Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

feat(cli): add --json output for every command - #214

Open
neurekadev wants to merge 3 commits into
borgbase:mainfrom
neurekadev:feat/35-json-output
Open

neurekadev wants to merge 3 commits into
borgbase:mainfrom
neurekadev:feat/35-json-output

Conversation

@neurekadev

@neurekadev neurekadev commented Nov 25, 2026 •

Copy link
Copy Markdown

Adds a global --json flag that makes every command print one structured JSON document on stdout, for scripts and third-party integrations.

Closes #35

Design

This follows the direction from the review of #128:

  • One global flag. vykar --json list and vykar list --json both work, and so does the bare vykar cycle.
  • Structured values, not formatted strings. snake_case keys, sizes and counts as raw integers, RFC 3339 UTC timestamps, arrays for paths, null for missing values. Every record stands on its own; there is no host/label blanking as in the table.
  • No per-command branching. A new output module holds an Output value that is threaded through dispatch, and a small Report trait with json() and print_human(). Each command builds a report and calls out.emit(&report). Human mode prints it at once, as before. JSON mode files it under the current repository and writes one document at the end.
  • A dedicated JSON schema. The JSON comes from CLI-side view structs, never from SnapshotEntry/SnapshotStats or other repository and wire types. A change to the on-disk format therefore cannot silently change the script interface.

Document

{
  "version": 1,
  "command": "list",
  "status": "ok",
  "error": null,
  "result": {},
  "repositories": [
    { "label": "main", "url": "/backup/repo", "status": "ok", "skip_reason": null, "error": null,
      "result": { "list": { "snapshots": [ ... ], "hidden": [] } } }
  ]
}
  • One entry per repository. Commands already run once per configured repository, so a bare array could not represent a multi-repository config. With the envelope, the shape is the same for one repository or several.
  • status mirrors the exit code (ok/partial/error/interrupted; 0/3/1/130). Exit codes are unchanged.
  • Early errors go in the top-level error. That covers a missing config, an unknown -R, and an ambiguous or missing snapshot during multi-repo probing.
  • Repository errors stay with the repository. A command that fails after producing data keeps both; for example, check reports result.check and sets error.
  • result is keyed by what ran. prune --compact gives prune + compact, and check --repair gives check + repair. The bare cycle reports cycle with steps, plus backup, prune, compact and check in the same shapes as the standalone commands.

Behaviour with --json

  • Never prompts. Confirmations behave as in non-interactive mode: they require --yes / --yes-delete-this-repo. check --repair with a data-loss plan requires --yes, and config requires --dest.
    break-lock gains a --yes flag for this, so scripts can clear stale session markers with break-lock --sessions --yes; without it, it still prompts or refuses as before.
  • daemon and mount refuse --json. Both run until stopped; the daemon already serves /api/status.json.
  • No backup progress bar unless -v is given. stderr otherwise stays as it was: progress, warnings and errors for people and logs.

Human output is unchanged

I compared stdout, stderr and exit codes against an unmodified main build, and they are byte-identical:

  • Read-only commands: list, info, snapshot info/list --long/diff/find, prune -n [--list], compact -n, compact --report-unreferenced, check, check --repair -n, break-lock, key export, plus the error paths.
  • Commands that change a repository: init, backup, prune --list, compact, restore, snapshot delete, the bare cycle, prune --compact, check --repair --yes, break-lock --sessions, delete --yes-delete-this-repo, key import. These ran on two fresh twin repositories, with snapshot IDs, paths and durations normalized.

Docs

  • New reference page docs/src/content/docs/json-output.md, covering the guarantees, the document format and the result for every command.
  • --json row in the common flags of commands.md.
  • The "JSON output mode" entry is removed from the roadmap.

Tests

New integration tests in cli_integration.rs parse stdout as JSON:

  • typed fields of list --json;
  • every command writes exactly one JSON document (init, backup, list, info, snapshot info/list/find, restore, prune, compact, compact --report-unreferenced, check, check --repair -n, break-lock, upgrade, bare cycle, config);
  • errors land in the document, both per repository and top-level, and commands that would prompt refuse instead;
  • with two repositories, list reports both.

Locally, make pre-commit passes formatting, clippy (-D warnings) and the doc check. In the full test suite, 3,290 tests pass. Two tests fail in this sandbox (vykar-core force_remove_handles_restrictive_dirs and unreadable_pin_fails_closed). They also fail on unmodified main there, because it runs as root, which bypasses the file permissions those tests depend on. Neither touches this change.

🤖 Generated with Claude Code

neurekadev and others added 2 commits November 24, 2026 17:07
A global --json flag replaces the human-readable result with one JSON
document on stdout, so scripts and other programs can consume vykar
without parsing tables. Human output is unchanged.

- New output module: commands build a Report and hand it to Output,
  which prints it at once or files it under the current repository and
  writes one versioned document at the end, also on failure.
- JSON is built from CLI-side view types with raw byte counts, RFC 3339
  UTC times, arrays and null, never from repository or wire types.
- With --json nothing prompts; daemon and mount reject the flag.
- Document the format in a new JSON Output reference page.

Closes borgbase#35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fixes from the local review of the --json change:

- Point stdout at stderr while a --json command runs, so hook output and
  stray prints cannot land before the document.
- Fail with a clear error instead of prompting for a missing passphrase.
- Hold results pre-serialized and stream the document, cutting the
  memory --json adds to large listings.
- Write an error document for command-line usage errors too.
- Report a bare cycle skipped by a hook or a missing repository as
  skipped.
- Classify a repository's outcome once for its status and exit code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@neurekadev

Copy link
Copy Markdown
Author

Code Review

PR #214 · c4a44429..5faeb829 · 24 files · No blocking issues remain

Critical: 0 High: 2 Medium: 4 Low: 2 Informational: 0

# Severity Type Finding Status
1 High Correctness Hook output on stdout corrupts the --json document
crates/vykar-cli/src/output.rs:195
Fixed 5fd9580d
2 High Duplication Bare cycle prints its own backup summary, missing cloud-only lines (pre-existing)
crates/vykar-cli/src/dispatch.rs:225
Follow-up #215
3 Medium Correctness --json still prompts for a missing passphrase and can hang
crates/vykar-cli/src/passphrase.rs:54
Fixed 5fd9580d
4 Medium Performance --json held every result as a Value tree
crates/vykar-cli/src/output.rs:108
Fixed 5fd9580d
5 Medium Correctness Bare cycle skipped by a hook reported status ok
crates/vykar-cli/src/lib.rs:562
Fixed 5fd9580d
6 Medium Duplication Repository outcome classified twice for status and exit code
crates/vykar-cli/src/output.rs:137
Fixed 5fd9580d
7 Low Correctness Command-line usage errors wrote no JSON document
crates/vykar-cli/src/lib.rs:55
Fixed 5fd9580d
8 Low Duplication Cycle step statuses repeated the Status vocabulary
crates/vykar-cli/src/dispatch.rs:194
Fixed 5fd9580d
1 · Hook output on stdout corrupts the --json document
  • Scenario: A config with hooks: { before: "echo hi" } and vykar backup --json: hooks inherit the process stdout, so stdout was hi followed by the document and JSON parsers failed.
  • Evidence: crates/vykar-core/src/hooks.rs runs hooks through shell::run_command_status_with_timeout with inherited stdout; reproduced with the debug binary.
  • Fix: With --json, stdout (fd 1 on Unix, STD_OUTPUT_HANDLE on Windows) points at stderr while the command runs; the document is written to the saved original stdout at the end. Human mode is untouched. (5fd9580d)
  • Fix check: backup --json with an echo hook: stdout is one JSON line, the hook text is on stderr; without --json the hook text stays on stdout.
2 · Bare cycle prints its own backup summary, missing cloud-only lines
  • Scenario: On macOS with cloud-only files, vykar backup prints the cloud-only summary but the bare vykar cycle never does, because print_step_details duplicates the backup summary instead of reusing it.
  • Evidence: The base already had both copies and the difference; this PR keeps human output byte-identical.
  • Follow-up: Pre-existing on main, and fixing it changes human output, so it is tracked separately.
3 · --json still prompts for a missing passphrase and can hang
  • Scenario: An encrypted repository without passphrase, passcommand or VYKAR_PASSPHRASE, run as vykar list --json by a program that keeps stdin open: the hidden prompt read stdin and blocked forever.
  • Evidence: Reproduced: (sleep 6) | timeout 4 vykar list --json was killed by timeout (exit 124).
  • Fix: In --json mode the passphrase prompt fails with "a passphrase is required; set VYKAR_PASSPHRASE or encryption.passcommand". (5fd9580d)
  • Fix check: The same command now exits 1 at once with the error in the document; human mode still prompts as before.
4 · --json held every result as a Value tree
  • Scenario: vykar snapshot list latest --json on a 200,000-file snapshot peaked at 304 MB against 117 MB for the human listing.
  • Evidence: Measured peak RSS; each item became a serde_json::Value map, and the document was then built as one String.
  • Fix: Results are stored pre-serialized (RawValue) in emit order and the document is streamed to stdout; output is always compact. (5fd9580d)
  • Fix check: Same snapshot: 141 MB human vs 159 MB with --json; the output is still one valid JSON line.
  • Fixed: The two reviewers rated this Medium and Low; fixed at the author's decision.
5 · Bare cycle skipped by a hook reported status ok
  • Scenario: vykar --json with a before hook exiting 75, or a missing local repository: the whole cycle was skipped but repositories[].status was "ok" and skip_reason null.
  • Evidence: The cycle records the skip as a step outcome, so the Err(Skipped) path that sets skip_reason never ran.
  • Fix: When the cycle reports itself skipped, the repository is marked skipped with the reason. (5fd9580d)
  • Fix check: The hook-skip and missing-repository cases now give status "skipped" with skip_reason; stderr is unchanged.
6 · Repository outcome classified twice for status and exit code
  • Scenario: A new outcome or exit code had to be added both in Output::end_repo and in lib.rs finish/run_all_repos, or the JSON status and the exit code would disagree.
  • Evidence: Both mapped CliResult<bool> plus the shutdown flag with the same precedence, one to a Status and one to an ExitCode.
  • Fix: One Status::of classification and one Status::exit_code mapping, used by end_repo, run_targeted and run_all_repos. (5fd9580d)
  • Fix check: Exit codes and stderr lines match the base build for single- and multi-repository runs, including continue-on-error.
Low and informational (2)
  • 7 · Command-line usage errors wrote no JSON document (crates/vykar-cli/src/lib.rs:55)
    • Scenario: vykar list --json --last abc exited 2 with empty stdout.
    • Evidence: Cli::parse() exits before any Output exists.
    • Fix: Cli::try_parse(); with --json a usage error also writes an error document, keeping clap's message on stderr and its exit code. (5fd9580d)
    • Fix check: The error document is written with exit 2; --help, --version and non-JSON errors behave as before.
  • 8 · Cycle step statuses repeated the Status vocabulary (crates/vykar-cli/src/dispatch.rs:194)
    • Scenario: Renaming a status word in output::Status would not reach result.cycle.steps[].status.
    • Evidence: StepJson.status hand-wrote the same strings Status serializes to.
    • Fix: StepJson.status is an output::Status. (5fd9580d)
    • Fix check: The JSON is identical.
Dismissed (1)
  • crates/vykar-cli/src/cmd/backup.rs:70: Backup progress gating duplicated in backup.rs and dispatch.rs. Dismissed: Refuted: a single boolean expression, which the duplicate-logic definition excludes.

Claude Opus 5.5 (High) · T3 Code (Claude Code) · Round 1 of 3

@neurekadev
neurekadev marked this pull request as ready for review November 25, 2026 01:29
Under --json nothing prompts, so `break-lock --sessions` could never
remove session markers: the command had no --yes flag. The new flag
skips the confirmation, as it does for upgrade and check --repair, and
the refusal now names it.

Also derive the multi-repository exit code from the shared Status
mapping, and correct the JSON docs: a single path is a string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@neurekadev

Copy link
Copy Markdown
Author

Code Review

PR #214 · c4a44429..5fd9580d · 26 files · No blocking issues remain

Critical: 0 High: 0 Medium: 2 Low: 1 Informational: 0

# Severity Type Finding Status
1 Medium Correctness break-lock --sessions can never remove sessions under --json
crates/vykar-cli/src/cmd/break_lock.rs:103
Fixed c1ae6350
2 Medium Duplication Overall exit code mapped apart from Status::exit_code
crates/vykar-cli/src/lib.rs:495
Fixed c1ae6350
3 Low Correctness JSON docs say every path is an array of strings
docs/src/content/docs/json-output.md:24
Fixed c1ae6350
1 · break-lock --sessions can never remove sessions under --json
  • Scenario: A crashed backup leaves repo/sessions/<id>.json; vykar --json break-lock --sessions exits 1 with "refusing to remove sessions without confirmation in non-interactive mode" and the marker stays. JSON mode never prompts and break-lock had no --yes flag, although the JSON docs say confirmations take the command's --yes flag.
  • Evidence: Reproduced with the head binary on a plaintext repository with a planted marker.
  • Fix: New break-lock --yes skips the confirmation, as for upgrade and check --repair; the refusal names the flag, and the maintenance docs show the scripted form. (c1ae6350)
  • Fix check: vykar --json break-lock --sessions --yes removes the marker, exits 0 and reports sessions_removed: 1; without --yes the prompt and the refusal behave as before.
  • Fixed: The two reviewers rated this Medium and Low; fixed at the author's decision.
2 · Overall exit code mapped apart from Status::exit_code
  • Scenario: Changing which exit code a status maps to in Status::exit_code() would change single-repository runs but not runs over all repositories, whose final code came from a separate table at the end of run_all_repos.
  • Evidence: The end of run_all_repos mapped interrupted/error/partial/ok straight to the EXIT_* constants, the same table as Status::exit_code().
  • Fix: run_all_repos derives one overall Status and returns status.exit_code(), with the same precedence and stderr output. (c1ae6350)
  • Fix check: Multi- and single-repository runs give the same exit codes and stderr as before.
  • Fixed: The two reviewers rated this Medium and Low (and disagreed on whether it predates the PR); fixed at the author's decision.
Low and informational (1)
  • 3 · JSON docs say every path is an array of strings (docs/src/content/docs/json-output.md:24)
    • Scenario: A consumer that trusts "Paths are arrays of strings" decodes snapshot_list[].path or config.path as an array and fails, since only source_paths is an array.
    • Evidence: The single-path fields in the snapshot list, find, diff, restore, config and key export views are strings.
    • Fix: The guarantee now reads: a single path is a string and a list of paths is an array of strings. (c1ae6350)
    • Fix check: Matches every path field in the JSON views.
Dismissed (1)
  • crates/vykar-cli/src/output.rs:227: Output::finish repeats the Status-to-exit-code mapping. Dismissed: Refuted: it maps an exit code back to the top-level status and also handles codes no Status produces (command-line usage errors), so it does a different job.

Claude Opus 5.5 (High) · T3 Code (Claude Code)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: --json for info, list

1 participant