diff --git a/CHANGELOG.md b/CHANGELOG.md index 783db6a..73852a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,21 @@ with a custom scheme: - **`build.sh` rejects an unknown command** The `case` matched `help|*` before the `*` branch, so a mistyped command (`./build.sh relase`) printed the help and exited 0 — a CI step with a typo would pass without building anything — and the `Unknown command` branch could never run. An unknown command now prints `Unknown command: ` and the help to stderr and exits 1; `help` and no arguments still print the help and exit 0. +- **`--json` leaves exactly one JSON document on stdout, on every path (closes #16)** + `--json` promised a single parseable document but broke in four places. `confirm()` (`src/utils/fs.rs`) wrote its prompt to stdout, so `baller --json eject` on a terminal printed `Are you sure…? [y/N]` into the stream; `help`, `help ` and `version` ignored `--json` and printed text; clap answered `-h`/`--help`/`-V`/`--version` itself in text before baller's flags were read; and every error went to stderr as `[Error]: …`, leaving a consumer an empty stdout. Prompts now go to stderr, and under `--json` `confirm()` asks nothing: it returns the new `BallError::ConfirmationRequired` (carrying the question), so `eject`, `sweep`, `substitute` and `inject` need `--yes` under `--json` and change nothing without it. `execute_command_help` and `execute_command_version` (`src/cli/`) take `GlobalFlags` and print JSON documents: the overview lists `commands`, `injected` and `global_options`, a built-in's detail splits its help lines into `arguments`/`subcommands` rows of `name`/`description` plus `notes` paragraphs, and an injected command's detail carries every `.ball` field. Text help is byte-for-byte unchanged. `BallerCommand::parse_command` now takes the argument list; when clap reports a display request and `--json` is on the command line, the request is re-parsed as `help []` or `version`, keeping `--config` so injected commands still load. `main` reports a failure under `--json` as `{"command", "error", "code"}` on stdout (`utils::output::error_json`; `code` is the new `BallError::code()`, the variant name), with `command` read off the raw arguments by `cli::parse::scan_args` when clap fails before naming a subcommand (`null` if none). The exception is `referee audit`/`check`/`scan --fail-on`, which print their report and then fail: `print_json` and `referee`'s `deliver` record that a document went out, and `main` then sends the error to stderr as text, so stdout still holds one document. Under `--json` colour is off, so no escape codes reach JSON strings. Smaller fixes on the same paths: `inject --json` now reports `{"command": "inject", "name", "binary"}` instead of text, and `substitute`'s rollback warning moved from a stdout `println!` to `tracing::warn!`. Behaviour changes: prompts are on stderr in text mode too; `baller --json sweep` without `--yes` now fails with `ConfirmationRequired` instead of prompting, and its unreachable `"status": "aborted"` document is gone. New `tests/json_output.rs` drives the real binary and parses stdout as a single document for help, version, display flags, CLI and command errors, every confirmation, the read-only commands, and `--fail-on` against a mock OSV server. Documented in `docs/commands.md` (including a new `version` section), `docs/error-handling.md`, `docs/architecture.md` and `docs/inject.md`. + +- **`roster --json` prints only the search document, and hooks and package managers stay off `--json` stdout (closes #40)** + When the name was not on the roster, `execute_roster` (`src/commands/roster.rs`) printed `Searching '' not found locally, searching registries...` with `println!` before `search_remote` printed its JSON, so `baller --json roster ` was text followed by a document and failed `jq`. The notice is progress, so it now goes through `tracing::info!`: on stderr, and hidden by `-q` and `--json`. In text mode it moves from stdout to stderr, which only shows when stdout is piped. The same match fell back to a registry search on *any* `get_package` error, so a roster that could not be read was reported as "not installed" and searched for; only `PackageNotFound` falls back now (`local_lookup`), and any other error is returned — the pattern #78 fixed for `is_frozen`. A full audit of baller's own stdout writes found no other print ahead of a `--json` document, but child processes inherit stdout too: a hook script that printed, `sudo apt-get/dnf/pacman install` for a system package, or `cargo install`, wrote into the stream ahead of the JSON. Under `--json` their stdout now goes to stderr through `utils::output::child_stdout()` (`src/core/hooks.rs`, `src/http/system.rs`, `src/http/cargo.rs`); `main` sets the mode once with `set_json_mode`, so `run_hook`'s 23 callers are untouched. Text mode is unchanged: a hook still prints to stdout. Injected commands still pass their output straight through, by design. New tests in `tests/json_output.rs` pin the search document, the notice on stderr and its absence under `-q`, and a hook's output on stderr under `--json` and on stdout without it; each fails when its fix is reverted. Documented in `docs/commands.md`, `docs/hooks.md` and `docs/architecture.md`. + +- **`version` under `--quiet` keeps printing, by design (closes #41)** + #41 asked for `baller --json version` to print JSON — done in the `--json` fix above — and for `baller --quiet version` to print nothing. The second half is not adopted: `--quiet` suppresses progress output, and every command still prints its result under it (`-q roster` still prints the table), so a silent `-q version` would be the one command whose result disappears, and would do nothing at all. The `--quiet` row in `docs/commands.md` and the `version` section now say so, and `tests/json_output.rs` pins `-q version` printing `Baller `. + +- **`draft` no longer prints a stray `quiet=false` while installing a system package** + Installing a system package printed `System installing via apt... quiet=false` on stderr. Before the tracing migration (#32, `d5bf020`) progress went through a helper, `output::info(quiet, msg)`, that skipped the line when quiet; the migration turned its calls into `tracing::info!(…)`, but one call in `src/commands/draft.rs` kept the `quiet` argument, which tracing reads as a field to print. The argument is gone: the tracer already drops `info` lines under `-q` and `--json`, so the line is still hidden there. The leftover `test_info_is_quiet_safe` in `src/utils/output.rs`, which still exercised `tracing::info!(bool, …)`, is removed with it. + +- **Referee's mock OSV server no longer drops a request that arrives late on Windows** + `test_a_cached_verdict_does_not_cover_another_version` and `test_refresh_re_queries_a_cached_identity` failed intermittently on the Windows CI runner with one request counted instead of two. The `MockServer` in `src/security/integration.rs` polls a non-blocking listener, and on Windows an accepted socket inherits that non-blocking mode, which voids `read_request`'s 5-second read timeout: a request still in flight when the connection was accepted read as `WouldBlock` and was dropped unrecorded, so the client saw a closed connection and Referee reported `unverified`. Linux sockets do not inherit the mode, so the bug never showed there. `read_request` now puts the stream back in blocking mode first. The new `test_the_mock_server_waits_for_a_request_that_arrives_late` sends its request 200 ms after connecting; built without the fix it failed 3 of 3 runs on a Windows 11 VM and under Wine, and with it it passed 3 of 3. + --- ## [0.2.0] - 2026-10-01 diff --git a/Cargo.lock b/Cargo.lock index 82ae48c..9995b48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -130,7 +130,7 @@ dependencies = [ [[package]] name = "baller" -version = "0.1.5" +version = "0.2.0" dependencies = [ "base64", "bzip2", diff --git a/Cargo.toml b/Cargo.toml index c62828a..40d687b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "baller" -version = "0.1.5" +version = "0.2.0" edition = "2021" authors = ["HMythical "] description = "A package manager for Windows & Linux Similar to Chocolatey, but with a sense of syntactical humor!" diff --git a/docs/architecture.md b/docs/architecture.md index 40ea2d8..df20322 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -311,10 +311,29 @@ packages installed as dependencies are marked `user_installed = false`, while packages explicitly installed via `draft` are marked `user_installed = true`. ### Confirmation Prompts -Destructive commands (`eject`, `sweep`, `substitute`) prompt for confirmation -unless the global `--yes` / `-y` flag is passed. `--yes` is one of the global -flags declared on `BallerCommand` and carried to commands via -`AppContext::flags` (`src/context.rs`). +Destructive commands (`eject`, `sweep`, `substitute`, `inject`) prompt for +confirmation unless the global `--yes` / `-y` flag is passed. `--yes` is one of +the global flags declared on `BallerCommand` and carried to commands via +`AppContext::flags` (`src/context.rs`). `utils::fs::confirm` takes the `--json` +flag too: prompts go to stderr, and under `--json` it returns +`ConfirmationRequired` instead of prompting. + +### JSON Output +Under `--json` every run leaves exactly one JSON document on stdout. Commands +print theirs through `utils::output::print_json`, which also records that a +document went out. `main` reports a failure as `utils::output::error_json` +(`command`, `error`, `code`) on stdout, unless a document was already printed +(`referee --fail-on`), in which case the error goes to stderr as text. Errors +raised before clap returns a parsed command still know `--json` and the +subcommand from `cli::parse::scan_args`, which reads the raw arguments; the +same scan rewrites `--json` with `-h`/`--help`/`-V`/`--version`, which clap +would otherwise answer itself in text, into the JSON-aware `help []` +and `version` subcommands. +Child processes inherit baller's stdout, so hooks (`core::hooks`) and the +package-manager installs (`http::system`, `http::cargo`) take theirs from +`utils::output::child_stdout()`: stderr under `--json`, inherited otherwise. +`main` sets the mode once with `set_json_mode`, the way it sets `colored`'s +override, so the flag is not threaded through every `run_hook` caller. ### Version Comparison The `update` command uses `parse_version_flexible()` for version comparison, diff --git a/docs/commands.md b/docs/commands.md index dc4d708..a9148f0 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -18,8 +18,8 @@ These work on every subcommand and may appear before or after it — | Flag | Description | |------|-------------| -| `--yes`, `-y` | Skip confirmation prompts (`eject`, `sweep`, `substitute`) | -| `--quiet`, `-q` | Suppress progress bars and step-by-step output | +| `--yes`, `-y` | Skip confirmation prompts (`eject`, `sweep`, `substitute`, `inject`); required for them under `--json` | +| `--quiet`, `-q` | Suppress progress bars and step-by-step output; a command's result (a table, a report, `version`) is still printed | | `--verbose`, `-v` | Increase output detail: resolved URLs, source chains and cache paths on stderr. `roster` prints full detail blocks | | `--json` | Emit machine-readable JSON instead of formatted text; implies quiet | | `--no-hooks` | Skip every pre/post install, eject and update hook | @@ -28,7 +28,21 @@ These work on every subcommand and may appear before or after it — | `--no-referee` | Skip the Referee security checks (both phases) for this run — see [referee.md](referee.md) | `--json` prints a single JSON document on stdout and suppresses every other -print, so command output stays parseable. +print, so command output stays parseable. That holds for every path: + +- `help`, `help `, `version`, and `-h`/`--help`/`-V`/`--version` + combined with `--json`, print JSON documents (see [help](#help--list-commands-or-describe-one) + and [version](#version--print-the-version)). +- A failure prints `{"command": …, "error": …, "code": …}` on stdout instead of + `[Error]: …` on stderr, and still exits 1 — see + [error-handling.md](error-handling.md#overview). +- Confirmation prompts are never shown: a command that would prompt fails with + a `ConfirmationRequired` error instead, so pass `--yes` to run `eject`, + `sweep`, `substitute` or `inject` under `--json`. +- Programs baller runs on the way — hook scripts, `apt-get`/`dnf`/`pacman` + for system packages, `cargo install` — still run, but their output goes to + stderr instead of stdout. (An injected command's output is its own, and + passes straight through.) Progress lines and verbose detail are written to **stderr**; stdout carries only the data a command produces. `-v` raises the detail level, `-q` and @@ -235,7 +249,11 @@ Active Roster (2 players): **With a package name:** Shows detailed info for a locally installed package, or falls back to searching remote registries. Remote search results include -descriptions when available. +descriptions when available. The `'' not found locally, searching +registries...` notice is progress output: it goes to stderr and is hidden by +`-q` and `--json`, so `--json` prints only the search document. Only a package +that is absent from the roster falls back to the search; if the roster itself +cannot be read, that error is reported instead. ``` $ baller roster ripgrep @@ -609,6 +627,9 @@ Done Injected 'my-tool' -> /usr/local/bin/my-tool Run it with: baller my-tool ``` +Under `--json`, `inject` needs `--yes` (its prompts are never shown) and +reports `{"command": "inject", "name": …, "binary": …}` on success. + --- ## referee — Audit the Roster for Vulnerabilities @@ -696,7 +717,35 @@ error. For an injected command the detail view shows its version, author, flags, dependencies, root requirement, and the binary it points at. `baller --help` and `-h` still print clap's own summary (stdout, exit 0) and -point at `baller help` for the injected list. +point at `baller help` for the injected list. Combined with `--json` they are +answered by `help` instead: `baller --json --help` is `baller --json help`, and +`baller --json eject -h` is `baller --json help eject` (a `referee` subcommand's +`-h` describes `referee`). + +With `--json` the overview lists `commands` (`name`, `summary`, `usage`), +`injected` (`name`, `description`, `version`) and `global_options` (`name`, +`description`). A built-in's detail carries `topic`, `kind: "builtin"`, +`summary`, `usage`, `arguments` and `subcommands` (each `name`/`description`) +and `notes`; an injected command's carries `kind: "injected"` and every field +of its `.ball` manifest. An unknown name is a JSON error. + +``` +$ baller --json help eject +{ + "command": "help", + "topic": "eject", + "kind": "builtin", + "summary": "Ejects (Uninstalls) a player from your team", + "usage": "baller eject ", + "arguments": [ + { "name": "", "description": "Package to uninstall" }, + { "name": "-f, --force", "description": "Eject even when the package is frozen" }, + … + ], + "subcommands": [], + "notes": ["Frozen packages must be unfrozen before they can be ejected."] +} +``` ``` $ baller help roster @@ -709,6 +758,19 @@ Usage: baller roster [PACKAGE_NAME] --- +## version — Print the Version + +``` +baller version +``` + +Prints `Baller `. `baller -V`/`--version` is clap's own form of the +same request (`baller `). With `--json`, all three print +`{"command": "version", "version": ""}`. `--quiet` does not hide it: +like every command's result, the version is data, not progress. + +--- + ## Confirmation Prompts Destructive commands (`eject`, `sweep`, `substitute`) prompt for confirmation @@ -722,3 +784,16 @@ Ejected myapp $ baller eject --yes myapp Ejected myapp ``` + +The prompt is written to stderr, so it never mixes into output piped from +stdout. Under `--json` nothing is prompted: the command fails with a +`ConfirmationRequired` JSON error and changes nothing, and `--yes` is required. + +``` +$ baller --json eject myapp +{ + "command": "eject", + "error": "confirmation required: Are you sure you want to eject myapp? — pass --yes/-y to proceed under --json", + "code": "ConfirmationRequired" +} +``` diff --git a/docs/error-handling.md b/docs/error-handling.md index 860f4e8..4180b0d 100644 --- a/docs/error-handling.md +++ b/docs/error-handling.md @@ -6,6 +6,25 @@ BALLER uses the `BallError` enum for all error types. Commands propagate errors via the `?` operator. User-facing errors are printed with `[Error]:` prefix and the process exits with a non-zero status code. +Under the global `--json` flag the error is instead the run's JSON document, on +stdout, and stderr stays empty: + +```json +{ + "command": "build", + "error": "manifest not found: /x/baller.toml", + "code": "InvalidConfig" +} +``` + +`command` is the subcommand that failed — `null` when the command line could +not be parsed far enough to name one — `error` is the same message the text +form prints, and `code` is the `BallError` variant name below, stable for +scripts to branch on. The exit code is still 1. The one exception is a command +that has already printed its document: `baller --json referee … --fail-on` +prints its report and then fails, so the `RefereeAuditFailed` message goes to +stderr as text and stdout keeps the report as its only document. + ## Error Types | Variant | Meaning | @@ -28,6 +47,9 @@ the process exits with a non-zero status code. | `RefereeBlocked` | Referee's advisory gate refused the plan. Carries every package over the block threshold with its advisories and the reason. Raised before the install loop, so nothing was downloaded, linked or recorded | | `RefereeScanBlocked` | Referee's artifact scan refused a downloaded package. Carries the package, version and every finding. Raised after extraction and before linking; the extract directory and cached archive are both purged (`discarded = false` on `build`'s cargo path, where the user's own compiled binary is deliberately left in place) | | `RefereeUnavailable` | The advisory service could not be reached. Fatal only under `fail_policy = fail-closed`; the default fail-open path reports the packages as `unverified` and continues | +| `ConfirmationAborted` | The user answered no to a confirmation prompt | +| `ConfirmationRequired` | A destructive command needed confirmation under `--json`, where nothing is ever prompted. Carries the question; pass `--yes` to proceed | +| `PipeRedirected` | A confirmation prompt could not be asked because stdin is not a terminal; pass `--yes` | | `RefereeAuditFailed` | `baller referee audit`/`check`/`scan --fail-on block\|warn` found an advisory or re-scan finding at or above that level; each package is named with the phase that tripped it. Raised after the report is printed, only to make the exit code non-zero for CI; nothing was changed | ## Database Startup Errors @@ -281,6 +303,13 @@ Destructive operations require user confirmation unless `--yes` / `-y` is provid - **`eject`** — removes a package and its orphaned dependencies - **`sweep`** — clears cached archives (and, with `--all`, extracted packages) - **`substitute`** — installs the replacement and removes the old package +- **`inject`** — adds a command that runs an arbitrary binary (three prompts) + +The prompt is written to stderr, so stdout only ever carries command output. +With stdin redirected the prompt cannot be answered and the command fails with +`PipeRedirected`; under `--json` nothing is prompted at all and the command +fails with `ConfirmationRequired`, reported as a JSON error. Either way nothing +has been changed, and `--yes` is the way through. ## Orphan Dependency Cleanup diff --git a/docs/hooks.md b/docs/hooks.md index 649f9d6..b0b19d5 100644 --- a/docs/hooks.md +++ b/docs/hooks.md @@ -55,6 +55,13 @@ echo "Installing ripgrep $(echo $BALLER_PACKAGE_VERSION) via baller" echo "fd $BALLER_PACKAGE_VERSION installed at $BALLER_INSTALL_PATH" ``` +## Output + +A hook shares baller's terminal: what it prints appears alongside baller's own +output. Under `--json` its stdout is sent to stderr instead, so the script +still runs and its output is still visible, but it never lands in the JSON +document on stdout. + ## Environment Variables All hooks receive the following environment variables: diff --git a/docs/inject.md b/docs/inject.md index c646449..e28ffff 100644 --- a/docs/inject.md +++ b/docs/inject.md @@ -109,6 +109,11 @@ Final confirmation: inject 'lz4c' from /usr/local/bin/lz4c? [yes/no] Answering anything other than `yes` or `y` at any prompt **aborts immediately** without writing anything. +The prompts are written to stderr. `--yes` skips all three. Under `--json` they +are never shown: without `--yes` the injection fails with a +`ConfirmationRequired` JSON error before the `.ball` file is read, and with it +success is reported as `{"command": "inject", "name": …, "binary": …}`. + ## Validation Rules `inject` rejects manifests that: diff --git a/src/cli/help.rs b/src/cli/help.rs index 155fccb..0780fed 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -1,7 +1,11 @@ use colored::Colorize; +use serde::Serialize; +use serde_json::{json, Value}; +use crate::context::GlobalFlags; use crate::core::injected::{load_injected, InjectedCommand}; use crate::error::error::BallError; +use crate::utils::output::print_json; const TAGLINE: &str = "B.A.L.L.E.R - The Binary Allocation & Library Launch Environment in Rust"; @@ -14,8 +18,13 @@ struct BuiltinCommand { summary: &'static str, usage: &'static str, /// Argument and flag lines, already formatted as `name explanation`. + /// + /// An indented line continues the explanation above it, and a + /// `Subcommands:` line starts the subcommand list: `--json` relies on both + /// to split the lines back into rows. details: &'static [&'static str], - /// Free-form paragraphs shown under the arguments. + /// Free-form paragraphs shown under the arguments. A `\n` inside one is a + /// line break in the text help and a space in `--json`. notes: &'static [&'static str], } @@ -122,10 +131,8 @@ const BUILTIN_COMMANDS: [BuiltinCommand; 12] = [ "-f, --force Build over an existing installation of the same package", "--source Override the manifest's source before resolving", ], - notes: &[ - "A Cargo project's dependencies are resolved by cargo itself, so", - "--source and --no-deps do not apply to one.", - ], + notes: &["A Cargo project's dependencies are resolved by cargo itself, so\n\ + --source and --no-deps do not apply to one."], }, BuiltinCommand { name: "inject", @@ -133,10 +140,10 @@ const BUILTIN_COMMANDS: [BuiltinCommand; 12] = [ usage: "baller inject ", details: &[" .ball file describing the command to add"], notes: &[ - "Injecting takes three confirmations: the named binary then runs as", - "'baller ' with your privileges.", - "Injected commands are stored in injected_commands.json under baller's", - "config directory, and are listed at the bottom of 'baller help'.", + "Injecting takes three confirmations: the named binary then runs as\n\ + 'baller ' with your privileges.", + "Injected commands are stored in injected_commands.json under baller's\n\ + config directory, and are listed at the bottom of 'baller help'.", ], }, BuiltinCommand { @@ -160,14 +167,14 @@ const BUILTIN_COMMANDS: [BuiltinCommand; 12] = [ "sbom CycloneDX 1.5 JSON of the roster: --out , --format cyclonedx-json", ], notes: &[ - "Every subcommand is read-only: a flagged package stays installed until", - "you eject or update it yourself. --fail-on only changes the exit code", - "(1 when an advisory or a re-scan finding reaches the level), for CI.", - "'cache' writes only to the verdict cache; 'cache', 'config' and 'sbom'", - "work with Referee off.", - "Referee also runs automatically before draft, update, substitute and", - "build install anything. Pass --no-referee to skip it for one command, or", - "set 'enabled = false' under [referee] in baller.conf to turn it off.", + "Every subcommand is read-only: a flagged package stays installed until\n\ + you eject or update it yourself. --fail-on only changes the exit code\n\ + (1 when an advisory or a re-scan finding reaches the level), for CI.", + "'cache' writes only to the verdict cache; 'cache', 'config' and 'sbom'\n\ + work with Referee off.", + "Referee also runs automatically before draft, update, substitute and\n\ + build install anything. Pass --no-referee to skip it for one command, or\n\ + set 'enabled = false' under [referee] in baller.conf to turn it off.", ], }, BuiltinCommand { @@ -202,22 +209,36 @@ const GLOBAL_OPTIONS: [&str; 10] = [ /// Prints the command overview, or the details of a single command. /// /// `topic` resolves against built-ins first, then injected commands, so a -/// built-in can never be shadowed in help output. -pub fn execute_command_help(baller_dir: &str, topic: Option<&str>) -> Result<(), BallError> { +/// built-in can never be shadowed in help output. Under `--json` the same +/// content is printed as one JSON document instead. +pub fn execute_command_help( + baller_dir: &str, + topic: Option<&str>, + flags: &GlobalFlags, +) -> Result<(), BallError> { let injected = load_injected(baller_dir); let Some(name) = topic else { + if flags.json { + return print_json(&overview_json(&injected)); + } println!("{}", render_overview(&injected)); return Ok(()); }; if let Some(builtin) = find_builtin(name) { + if flags.json { + return print_json(&builtin_detail_json(builtin)); + } println!("{}", render_builtin_detail(builtin)); return Ok(()); } match injected.iter().find(|c| c.command_name == name) { Some(command) => { + if flags.json { + return print_json(&injected_detail_json(command)); + } println!("{}", render_injected_detail(command)); Ok(()) } @@ -360,6 +381,128 @@ fn column_width(injected: &[InjectedCommand]) -> usize { .unwrap_or(0) } +/// One `name explanation` line of the help text, split for `--json`. +#[derive(Debug, Serialize)] +struct HelpRow { + name: String, + description: String, +} + +/// Split preformatted help lines into `(arguments, subcommands)` rows. +/// +/// The name ends at the first double space. An indented line is a wrapped +/// explanation and joins the row above; `Subcommands:` moves every later row +/// into the second list; blank lines only separate. +fn split_rows(lines: &[&str]) -> (Vec, Vec) { + let mut arguments: Vec = Vec::new(); + let mut subcommands: Vec = Vec::new(); + let mut in_subcommands = false; + + for line in lines { + if line.trim().is_empty() { + continue; + } + if *line == "Subcommands:" { + in_subcommands = true; + continue; + } + + let rows = if in_subcommands { + &mut subcommands + } else { + &mut arguments + }; + + if line.starts_with(' ') { + if let Some(row) = rows.last_mut() { + row.description.push(' '); + row.description.push_str(line.trim()); + } + continue; + } + + let (name, description) = line.split_once(" ").unwrap_or((line, "")); + rows.push(HelpRow { + name: name.trim().to_string(), + description: description.trim().to_string(), + }); + } + + (arguments, subcommands) +} + +/// `baller --json help`: every command, built-in and injected. +fn overview_json(injected: &[InjectedCommand]) -> Value { + let commands: Vec = BUILTIN_COMMANDS + .iter() + .map(|c| { + json!({ + "name": c.name, + "summary": c.summary, + "usage": c.usage, + }) + }) + .collect(); + + let injected: Vec = injected + .iter() + .map(|c| { + json!({ + "name": c.command_name, + "description": c.description, + "version": c.version, + }) + }) + .collect(); + + json!({ + "command": "help", + "about": TAGLINE, + "usage": "baller [ARGS]...", + "commands": commands, + "injected": injected, + "global_options": split_rows(&GLOBAL_OPTIONS).0, + }) +} + +/// `baller --json help `. +fn builtin_detail_json(command: &BuiltinCommand) -> Value { + let (arguments, subcommands) = split_rows(command.details); + let notes: Vec = command + .notes + .iter() + .map(|note| note.replace('\n', " ")) + .collect(); + + json!({ + "command": "help", + "topic": command.name, + "kind": "builtin", + "summary": command.summary, + "usage": command.usage, + "arguments": arguments, + "subcommands": subcommands, + "notes": notes, + }) +} + +/// `baller --json help `: every field of its `.ball` manifest. +fn injected_detail_json(command: &InjectedCommand) -> Value { + json!({ + "command": "help", + "topic": command.command_name, + "kind": "injected", + "description": command.description, + "usage": format!("baller {} [ARGS]...", command.command_name), + "version": command.version, + "author": command.author, + "flags": command.flags, + "depends": command.depends, + "require_root": command.require_root, + "binary": command.path.display().to_string(), + }) +} + fn describe(command: &InjectedCommand) -> String { if command.description.is_empty() { "no description provided".to_string() @@ -395,6 +538,17 @@ mod tests { dir.to_string_lossy().to_string() } + fn text() -> GlobalFlags { + GlobalFlags::default() + } + + fn json_flags() -> GlobalFlags { + GlobalFlags { + json: true, + ..GlobalFlags::default() + } + } + fn sample() -> InjectedCommand { InjectedCommand { command_name: "my-tool".to_string(), @@ -515,7 +669,7 @@ mod tests { #[test] fn test_help_overview_runs() { let dir = test_dir("overview"); - assert!(execute_command_help(&dir, None).is_ok()); + assert!(execute_command_help(&dir, None, &text()).is_ok()); let _ = std::fs::remove_dir_all(&dir); } @@ -524,7 +678,7 @@ mod tests { let dir = test_dir("builtin_topic"); for command in BUILTIN_COMMANDS.iter() { assert!( - execute_command_help(&dir, Some(command.name)).is_ok(), + execute_command_help(&dir, Some(command.name), &text()).is_ok(), "help failed for '{}'", command.name ); @@ -536,14 +690,14 @@ mod tests { fn test_help_topic_resolves_injected_command() { let dir = test_dir("injected_topic"); save_injected(&dir, &[sample()]).unwrap(); - assert!(execute_command_help(&dir, Some("my-tool")).is_ok()); + assert!(execute_command_help(&dir, Some("my-tool"), &text()).is_ok()); let _ = std::fs::remove_dir_all(&dir); } #[test] fn test_help_topic_unknown_is_an_error() { let dir = test_dir("unknown_topic"); - let err = execute_command_help(&dir, Some("not-a-command")).unwrap_err(); + let err = execute_command_help(&dir, Some("not-a-command"), &text()).unwrap_err(); let msg = format!("{}", err); assert!(msg.contains("not-a-command")); assert!(msg.contains("does not exist")); @@ -559,13 +713,167 @@ mod tests { // Injection rejects built-in names, but a hand-edited store must not // be able to hide the real command's help either. - assert!(execute_command_help(&dir, Some("draft")).is_ok()); + assert!(execute_command_help(&dir, Some("draft"), &text()).is_ok()); let detail = render_builtin_detail(find_builtin("draft").unwrap()); assert!(detail.contains("")); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn test_help_json_runs_for_overview_and_every_topic() { + let dir = test_dir("json_topics"); + save_injected(&dir, &[sample()]).unwrap(); + assert!(execute_command_help(&dir, None, &json_flags()).is_ok()); + for command in BUILTIN_COMMANDS.iter() { + assert!(execute_command_help(&dir, Some(command.name), &json_flags()).is_ok()); + } + assert!(execute_command_help(&dir, Some("my-tool"), &json_flags()).is_ok()); + assert!(matches!( + execute_command_help(&dir, Some("not-a-command"), &json_flags()), + Err(BallError::UnsupportedCommand(_)) + )); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_overview_json_lists_builtins_injected_and_global_options() { + let value = overview_json(&[sample()]); + assert_eq!(value["command"], "help"); + + let commands = value["commands"].as_array().unwrap(); + assert_eq!(commands.len(), BUILTIN_COMMANDS.len()); + assert_eq!(commands[0]["name"], "draft"); + assert_eq!(commands[0]["usage"], "baller draft "); + + assert_eq!(value["injected"][0]["name"], "my-tool"); + assert_eq!( + value["injected"][0]["description"], + "A helpful tool that does X" + ); + assert_eq!(value["injected"][0]["version"], "1.0.0"); + + let options = value["global_options"].as_array().unwrap(); + assert_eq!(options.len(), GLOBAL_OPTIONS.len()); + assert_eq!(options[0]["name"], "-y, --yes"); + assert_eq!(options[0]["description"], "Skip confirmation prompts"); + assert!(options.iter().any(|o| o["name"] == "--config ")); + } + + #[test] + fn test_overview_json_with_no_injected_commands_is_an_empty_list() { + let value = overview_json(&[]); + assert_eq!(value["injected"], json!([])); + } + + #[test] + fn test_builtin_detail_json_splits_arguments() { + let value = builtin_detail_json(find_builtin("eject").unwrap()); + assert_eq!(value["topic"], "eject"); + assert_eq!(value["kind"], "builtin"); + assert_eq!(value["usage"], "baller eject "); + assert_eq!(value["arguments"][1]["name"], "-f, --force"); + assert_eq!( + value["arguments"][1]["description"], + "Eject even when the package is frozen" + ); + assert_eq!(value["subcommands"], json!([])); + assert_eq!( + value["notes"], + json!(["Frozen packages must be unfrozen before they can be ejected."]) + ); + } + + #[test] + fn test_builtin_detail_json_folds_wrapped_lines() { + let value = builtin_detail_json(find_builtin("build").unwrap()); + let path = &value["arguments"][0]; + assert_eq!(path["name"], ""); + assert_eq!( + path["description"], + "Manifest (.toml or .json) to build from, or a directory \ + containing a Cargo project (Rust sources are compiled \ + with 'cargo build --release' and installed)" + ); + assert_eq!( + value["notes"], + json!([ + "A Cargo project's dependencies are resolved by cargo itself, so \ + --source and --no-deps do not apply to one." + ]) + ); + } + + #[test] + fn test_referee_detail_json_lists_its_subcommands() { + let value = builtin_detail_json(find_builtin("referee").unwrap()); + let arguments = value["arguments"].as_array().unwrap(); + assert_eq!(arguments.len(), 3); + assert_eq!(arguments[0]["name"], "[PACKAGE_NAME]"); + + let subcommands = value["subcommands"].as_array().unwrap(); + let names: Vec<&str> = subcommands + .iter() + .map(|s| { + s["name"] + .as_str() + .unwrap() + .split_whitespace() + .next() + .unwrap() + }) + .collect(); + assert_eq!(names, ["audit", "check", "scan", "cache", "config", "sbom"]); + assert!(subcommands[0]["description"] + .as_str() + .unwrap() + .ends_with("--format , --out ")); + assert_eq!(value["notes"].as_array().unwrap().len(), 3); + } + + #[test] + fn test_every_help_row_has_a_name_and_a_description() { + for command in BUILTIN_COMMANDS.iter() { + let (arguments, subcommands) = split_rows(command.details); + for row in arguments.iter().chain(subcommands.iter()) { + assert!( + !row.name.is_empty() && !row.description.is_empty(), + "'{}' has a malformed help row: {:?}", + command.name, + row + ); + } + } + for row in split_rows(&GLOBAL_OPTIONS).0 { + assert!(!row.name.is_empty() && !row.description.is_empty()); + } + } + + #[test] + fn test_notes_render_as_lines_in_text_and_paragraphs_in_json() { + let command = find_builtin("inject").unwrap(); + let detail = render_builtin_detail(command); + assert!(detail.contains("runs as\n'baller ' with your privileges.")); + + let value = builtin_detail_json(command); + let notes = value["notes"].as_array().unwrap(); + assert_eq!(notes.len(), 2); + assert!(notes.iter().all(|n| !n.as_str().unwrap().contains('\n'))); + } + + #[test] + fn test_injected_detail_json_carries_every_manifest_field() { + let value = injected_detail_json(&sample()); + assert_eq!(value["topic"], "my-tool"); + assert_eq!(value["kind"], "injected"); + assert_eq!(value["usage"], "baller my-tool [ARGS]..."); + assert_eq!(value["author"], "HMythical"); + assert_eq!(value["flags"], json!(["-y", "--yes"])); + assert_eq!(value["depends"], json!(["python3"])); + assert_eq!(value["require_root"], true); + assert_eq!(value["binary"], "/usr/local/bin/my-tool"); + } + #[test] fn test_every_clap_subcommand_is_documented() { let command = BallerCommand::command(); diff --git a/src/cli/parse.rs b/src/cli/parse.rs index 4b8bc78..42b7120 100644 --- a/src/cli/parse.rs +++ b/src/cli/parse.rs @@ -18,7 +18,8 @@ use crate::core::injected::resolve_baller_dir; use crate::core::registry::RegistrySource; use crate::error::error::BallError; use clap::error::ErrorKind; -use clap::{Args, Parser, Subcommand, ValueEnum}; +use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum}; +use std::ffi::OsString; #[derive(Parser, Debug)] #[command(name = "baller")] @@ -396,13 +397,20 @@ impl RefereeArgs { } impl BallerCommand { - pub fn parse_command() -> Result { - match BallerCommand::try_parse() { + /// Parse a full command line, the binary's own name first. + pub fn parse_command(args: &[OsString]) -> Result { + match BallerCommand::try_parse_from(args) { Ok(cmd) => Ok(cmd), + // clap answers -h/-V itself, in text. Under --json the same request + // is re-parsed as the JSON-aware `help`/`version` subcommand. + Err(e) if is_display_request(e.kind()) && scan_args(args).json => { + BallerCommand::try_parse_from(display_request_as_subcommand(args, e.kind())) + .map_err(cli_error) + } // Help and version are requests, not failures: let clap print them // on its own stream and exit the way it normally would. Err(e) if is_display_request(e.kind()) => e.exit(), - Err(e) => Err(BallError::InvalidConfig(format!("CLI Error: {}", e))), + Err(e) => Err(cli_error(e)), } } @@ -544,10 +552,12 @@ impl BallerCommand { ), CommandTypes::Inject { path } => execute_inject(ctx, path), CommandTypes::Referee(args) => execute_referee(ctx, &args.to_command()), - CommandTypes::Help { command } => { - execute_command_help(&resolve_baller_dir(&ctx.config), command.as_deref()) - } - CommandTypes::Version => execute_command_version(), + CommandTypes::Help { command } => execute_command_help( + &resolve_baller_dir(&ctx.config), + command.as_deref(), + &ctx.flags, + ), + CommandTypes::Version => execute_command_version(&ctx.flags), CommandTypes::External(args) => { let (name, rest) = args .split_first() @@ -558,6 +568,32 @@ impl BallerCommand { } } +impl CommandTypes { + /// The subcommand as named on the command line: the `command` a `--json` + /// error document reports. + pub fn name(&self) -> &str { + match self { + CommandTypes::Draft { .. } => "draft", + CommandTypes::Eject { .. } => "eject", + CommandTypes::Freeze { .. } => "freeze", + CommandTypes::Roster { .. } => "roster", + CommandTypes::Substitute { .. } => "substitute", + CommandTypes::Sweep { .. } => "sweep", + CommandTypes::Update { .. } => "update", + CommandTypes::Build { .. } => "build", + CommandTypes::Inject { .. } => "inject", + CommandTypes::Referee(_) => "referee", + CommandTypes::Help { .. } => "help", + CommandTypes::Version => "version", + CommandTypes::External(args) => args.first().map_or("", String::as_str), + } + } +} + +fn cli_error(e: clap::Error) -> BallError { + BallError::InvalidConfig(format!("CLI Error: {}", e)) +} + /// True when clap "failed" only because it was asked to print help or version. fn is_display_request(kind: ErrorKind) -> bool { matches!( @@ -568,10 +604,86 @@ fn is_display_request(kind: ErrorKind) -> bool { ) } +/// What a command line says before clap has parsed it. +#[derive(Debug, Default, PartialEq)] +pub struct RawArgs { + /// `--json` was passed to baller itself + pub json: bool, + /// `--config `, so a rewritten help request still finds the injected + /// commands stored under it + pub config: Option, + /// The built-in subcommand, by its canonical name + pub subcommand: Option, +} + +/// Read the global flags and the subcommand off a raw command line. +/// +/// Only consulted where clap has no `BallerCommand` to give: a CLI error, or a +/// help/version flag it would answer itself. Follows clap where it matters: +/// baller's flags end at `--` and at an unknown (injected) subcommand, whose +/// arguments are that command's own, and a top-level `-h`/`-V` is answered +/// before any subcommand after it is read. +pub fn scan_args(args: &[OsString]) -> RawArgs { + let command = BallerCommand::command(); + let mut raw = RawArgs::default(); + let mut top_level_display = false; + let mut iter = args.iter().skip(1); + + while let Some(arg) = iter.next() { + let Some(text) = arg.to_str() else { + continue; + }; + match text { + "--" => break, + "--json" => raw.json = true, + "--config" => raw.config = iter.next().cloned(), + _ if text.starts_with("--config=") => { + raw.config = Some(OsString::from(&text["--config=".len()..])); + } + "-h" | "--help" | "-V" | "--version" if raw.subcommand.is_none() => { + top_level_display = true; + } + _ if text.starts_with('-') || top_level_display || raw.subcommand.is_some() => {} + _ => match command.find_subcommand(text) { + Some(subcommand) => raw.subcommand = Some(subcommand.get_name().to_string()), + None => break, + }, + } + } + + raw +} + +/// `baller --json [] --help` as `baller --json help []`, and +/// `baller --json -V` as `baller --json version`. +/// +/// Only `--json` and `--config` survive the rewrite: they are the only flags +/// that change what `help` and `version` print. +fn display_request_as_subcommand(args: &[OsString], kind: ErrorKind) -> Vec { + let raw = scan_args(args); + let mut rewritten: Vec = vec![ + args.first().cloned().unwrap_or_else(|| "baller".into()), + "--json".into(), + ]; + + if let Some(dir) = raw.config { + rewritten.push("--config".into()); + rewritten.push(dir); + } + + if kind == ErrorKind::DisplayVersion { + rewritten.push("version".into()); + } else { + rewritten.push("help".into()); + rewritten.extend(raw.subcommand.map(OsString::from)); + } + + rewritten +} + #[cfg(test)] mod tests { use super::*; - use clap::CommandFactory; fn parse(args: &[&str]) -> BallerCommand { BallerCommand::try_parse_from(args).unwrap() @@ -875,6 +987,117 @@ mod tests { } } + fn os_args(args: &[&str]) -> Vec { + args.iter().map(OsString::from).collect() + } + + #[test] + fn test_command_name_is_the_subcommand_typed() { + for args in [ + vec!["baller", "draft", "fd"], + vec!["baller", "eject", "fd"], + vec!["baller", "freeze", "fd"], + vec!["baller", "roster"], + vec!["baller", "substitute", "a", "b"], + vec!["baller", "sweep"], + vec!["baller", "update"], + vec!["baller", "build", "."], + vec!["baller", "inject", "x.ball"], + vec!["baller", "referee"], + vec!["baller", "help"], + vec!["baller", "version"], + vec!["baller", "my-tool", "--flag"], + ] { + assert_eq!(parse(&args).command.name(), args[1]); + } + } + + #[test] + fn test_scan_args_reads_json_config_and_subcommand() { + let raw = scan_args(&os_args(&[ + "baller", "--config", "/tmp/b", "draft", "fd", "--json", + ])); + assert_eq!( + raw, + RawArgs { + json: true, + config: Some(OsString::from("/tmp/b")), + subcommand: Some("draft".to_string()), + } + ); + + let raw = scan_args(&os_args(&["baller", "--config=/tmp/c", "roster"])); + assert_eq!(raw.config, Some(OsString::from("/tmp/c"))); + assert!(!raw.json); + + // A --config value is never mistaken for the subcommand. + let raw = scan_args(&os_args(&["baller", "--config", "draft", "roster"])); + assert_eq!(raw.subcommand.as_deref(), Some("roster")); + } + + #[test] + fn test_scan_args_leaves_an_injected_commands_arguments_alone() { + let raw = scan_args(&os_args(&["baller", "my-tool", "--json"])); + assert_eq!(raw, RawArgs::default()); + + let raw = scan_args(&os_args(&["baller", "--json", "my-tool", "--help"])); + assert!(raw.json); + assert_eq!(raw.subcommand, None); + + let raw = scan_args(&os_args(&["baller", "--", "--json"])); + assert!(!raw.json); + } + + #[test] + fn test_scan_args_follows_clap_on_a_top_level_display_flag() { + // clap answers a top-level -h before reading the subcommand after it. + let raw = scan_args(&os_args(&["baller", "--help", "draft", "--json"])); + assert!(raw.json); + assert_eq!(raw.subcommand, None); + + // After the subcommand, --version is draft's own option. + let raw = scan_args(&os_args(&["baller", "draft", "--version", "1", "-h"])); + assert_eq!(raw.subcommand.as_deref(), Some("draft")); + } + + #[test] + fn test_display_request_becomes_the_json_aware_subcommand() { + let rewritten = display_request_as_subcommand( + &os_args(&["baller", "--json", "--config", "/b", "draft", "--help"]), + ErrorKind::DisplayHelp, + ); + assert_eq!( + rewritten, + os_args(&["baller", "--json", "--config", "/b", "help", "draft"]) + ); + + let rewritten = display_request_as_subcommand( + &os_args(&["baller", "-q", "--json", "-h"]), + ErrorKind::DisplayHelp, + ); + assert_eq!(rewritten, os_args(&["baller", "--json", "help"])); + + let rewritten = display_request_as_subcommand( + &os_args(&["baller", "-V", "--json"]), + ErrorKind::DisplayVersion, + ); + assert_eq!(rewritten, os_args(&["baller", "--json", "version"])); + } + + #[test] + fn test_json_display_requests_parse_as_help_and_version() { + let cmd = + BallerCommand::parse_command(&os_args(&["baller", "--json", "eject", "-h"])).unwrap(); + assert!(cmd.json); + match cmd.command { + CommandTypes::Help { command } => assert_eq!(command.as_deref(), Some("eject")), + other => panic!("expected Help, got {:?}", other), + } + + let cmd = BallerCommand::parse_command(&os_args(&["baller", "--json", "-V"])).unwrap(); + assert!(matches!(cmd.command, CommandTypes::Version)); + } + fn referee(args: &[&str]) -> RefereeCommand { match parse(args).command { CommandTypes::Referee(referee) => referee.to_command(), diff --git a/src/cli/version.rs b/src/cli/version.rs index 52e777e..414501c 100644 --- a/src/cli/version.rs +++ b/src/cli/version.rs @@ -1,7 +1,33 @@ +use serde_json::json; + +use crate::context::GlobalFlags; use crate::error::error::BallError; +use crate::utils::output::print_json; + +pub fn execute_command_version(flags: &GlobalFlags) -> Result<(), BallError> { + if flags.json { + return print_json(&json!({ + "command": "version", + "version": env!("CARGO_PKG_VERSION"), + })); + } -pub fn execute_command_version() -> Result<(), BallError> { println!("Baller {}", env!("CARGO_PKG_VERSION")); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_version_runs_in_text_and_json() { + assert!(execute_command_version(&GlobalFlags::default()).is_ok()); + let flags = GlobalFlags { + json: true, + ..GlobalFlags::default() + }; + assert!(execute_command_version(&flags).is_ok()); + } +} diff --git a/src/commands/draft.rs b/src/commands/draft.rs index 44b4d00..632c50e 100644 --- a/src/commands/draft.rs +++ b/src/commands/draft.rs @@ -142,12 +142,7 @@ pub fn execute_draft( // System packages are installed via the native package manager, // not downloaded/archived. Record them in the DB and continue. if let PackageSource::System { manager } = &pkg_to_install.source { - tracing::info!( - quiet, - "{} installing via {}...", - "System".green(), - manager.cyan(), - ); + tracing::info!("{} installing via {}...", "System".green(), manager.cyan()); install_system_package(manager, &pkg_to_install.name)?; let is_root = pkg_to_install.name == pkg.name; diff --git a/src/commands/eject.rs b/src/commands/eject.rs index d206d64..a80c623 100644 --- a/src/commands/eject.rs +++ b/src/commands/eject.rs @@ -34,10 +34,13 @@ pub fn execute_eject( // E4: Confirmation prompt (unless --yes/-y) if !ctx.flags.yes - && !confirm(&format!( - "Are you sure you want to eject {}? [y/N]", - installed.name.cyan() - ))? + && !confirm( + &format!( + "Are you sure you want to eject {}? [y/N]", + installed.name.cyan() + ), + ctx.flags.json, + )? { return Err(BallError::ConfirmationAborted); } diff --git a/src/commands/inject.rs b/src/commands/inject.rs index de116ee..088d179 100644 --- a/src/commands/inject.rs +++ b/src/commands/inject.rs @@ -1,12 +1,14 @@ use std::path::{Path, PathBuf}; use colored::Colorize; +use serde_json::json; use crate::context::AppContext; use crate::core::ball_parser::{parse_ball_file, BallManifest}; use crate::core::injected::{resolve_baller_dir, upsert_injected, InjectedCommand}; use crate::error::error::BallError; use crate::utils::fs::confirm; +use crate::utils::output::print_json; /// Names baller reserves for its own subcommands; an injected command may not /// shadow any of them. @@ -33,12 +35,14 @@ pub fn execute_inject(ctx: &AppContext, path: &str) -> Result<(), BallError> { if !ctx.flags.yes { if !confirm( "This will modify baller's runtime behavior by adding a new command. Continue? [yes/no]", + ctx.flags.json, )? { return Err(BallError::ConfirmationAborted); } if !confirm( "Only inject .ball files from sources you trust: the binary they name runs with your privileges. Continue? [yes/no]", + ctx.flags.json, )? { return Err(BallError::ConfirmationAborted); } @@ -47,11 +51,14 @@ pub fn execute_inject(ctx: &AppContext, path: &str) -> Result<(), BallError> { let manifest = parse_ball_file(Path::new(path))?; if !ctx.flags.yes - && !confirm(&format!( - "Final confirmation: inject '{}' from {}? [yes/no]", - manifest.command_name.cyan(), - manifest.path.display().to_string().cyan() - ))? + && !confirm( + &format!( + "Final confirmation: inject '{}' from {}? [yes/no]", + manifest.command_name.cyan(), + manifest.path.display().to_string().cyan() + ), + ctx.flags.json, + )? { return Err(BallError::ConfirmationAborted); } @@ -66,6 +73,14 @@ pub fn execute_inject(ctx: &AppContext, path: &str) -> Result<(), BallError> { let binary = command.path.display().to_string(); upsert_injected(&baller_dir, command)?; + if ctx.flags.json { + return print_json(&json!({ + "command": "inject", + "name": name, + "binary": binary, + })); + } + println!( "{} Injected '{}' -> {}", "Done".green().bold(), diff --git a/src/commands/referee/export.rs b/src/commands/referee/export.rs index c482e72..8f5a78a 100644 --- a/src/commands/referee/export.rs +++ b/src/commands/referee/export.rs @@ -14,6 +14,7 @@ use crate::error::error::BallError; use crate::security::export::{render_markdown, render_sarif, ScanOutcome}; use crate::security::GateOutcome; use crate::utils::fs::atomic_write; +use crate::utils::output::mark_document_printed; /// Everything an audit produced, for rendering. pub struct AuditReport<'a> { @@ -49,6 +50,7 @@ pub fn deliver(contents: &str, out: Option<&str>, label: &str) -> Result<(), Bal match out { None => { print!("{}", with_newline(contents)); + mark_document_printed(); Ok(()) } Some(path) => { diff --git a/src/commands/roster.rs b/src/commands/roster.rs index 37e8b0e..7a70151 100644 --- a/src/commands/roster.rs +++ b/src/commands/roster.rs @@ -29,10 +29,12 @@ pub fn execute_roster( } if let Some(pkg_name) = package_name { - return match ctx.db.get_package(pkg_name) { - Ok(pkg) => show_detail(ctx, &pkg), - Err(_) => { - println!( + return match local_lookup(ctx.db.get_package(pkg_name))? { + Some(pkg) => show_detail(ctx, &pkg), + None => { + // Progress, not data: on stderr, and silent under -q/--json so + // the search result stays the only thing on stdout. + tracing::info!( "{} '{}' not found locally, searching registries...", "Searching".cyan(), pkg_name.cyan() @@ -45,6 +47,21 @@ pub fn execute_roster( list_packages(ctx, opts) } +/// A roster lookup: the installed package, or `None` when it is simply not +/// installed here — the cue to search the registries instead. +/// +/// Any other failure is the database's and is returned as-is: falling back to +/// a registry search would report a broken roster as "not installed". +fn local_lookup( + lookup: Result, +) -> Result, BallError> { + match lookup { + Ok(pkg) => Ok(Some(pkg)), + Err(BallError::PackageNotFound(_)) => Ok(None), + Err(e) => Err(e), + } +} + fn list_packages(ctx: &AppContext, opts: &RosterOptions) -> Result<(), BallError> { let mut pkgs = ctx.db.list_packages()?; @@ -310,6 +327,23 @@ mod tests { assert_eq!(RegistrySource::System.db_name(), "system"); } + #[test] + fn test_a_missing_package_falls_back_to_the_registries() { + let lookup = local_lookup(Err(BallError::PackageNotFound("fd".to_string()))); + assert!(matches!(lookup, Ok(None))); + } + + #[test] + fn test_a_failed_lookup_is_reported_not_searched() { + let lookup = local_lookup(Err(BallError::InvalidConfig( + "failed to query package 'fd': disk I/O error".to_string(), + ))); + match lookup { + Err(BallError::InvalidConfig(msg)) => assert!(msg.contains("disk I/O error")), + other => panic!("expected the lookup error back, got {:?}", other), + } + } + #[test] fn test_roster_options_default_to_plain_list() { let opts = RosterOptions { diff --git a/src/commands/substitute.rs b/src/commands/substitute.rs index 1b0b4d9..f9b7c58 100644 --- a/src/commands/substitute.rs +++ b/src/commands/substitute.rs @@ -90,7 +90,7 @@ pub fn execute_substitute( ) }; - if !confirm(&prompt)? { + if !confirm(&prompt, ctx.flags.json)? { return Err(BallError::ConfirmationAborted); } } @@ -188,7 +188,7 @@ pub fn execute_substitute( if let Some((ref install_path, ref _bin_path)) = new_installed { let _ = ctx.db.remove_package(&pkg.name); let _ = std::fs::remove_dir_all(install_path); - println!( + tracing::warn!( "{} Rolled back substitution due to error: {}", "Warning".red(), e diff --git a/src/commands/sweep.rs b/src/commands/sweep.rs index 4627cd6..2fcdab0 100644 --- a/src/commands/sweep.rs +++ b/src/commands/sweep.rs @@ -116,14 +116,7 @@ pub fn execute_sweep(ctx: &AppContext, opts: &SweepOptions) -> Result<(), BallEr ) }; - if !confirm(&prompt)? { - if json { - return print_json(&json!({ - "command": "sweep", - "mode": mode, - "status": "aborted", - })); - } + if !confirm(&prompt, json)? { return Err(BallError::ConfirmationAborted); } } diff --git a/src/core/hooks.rs b/src/core/hooks.rs index 62e7480..e4d7750 100644 --- a/src/core/hooks.rs +++ b/src/core/hooks.rs @@ -3,6 +3,7 @@ use std::process::Command; use crate::config::config::HooksConfig; use crate::error::error::BallError; +use crate::utils::output::child_stdout; #[derive(Debug, Clone, Copy, PartialEq)] pub enum HookType { @@ -167,6 +168,9 @@ fn execute_hook( cmd.env(k, v); } + // Under --json the script's output goes to stderr, not into the document. + cmd.stdout(child_stdout()); + let status = cmd.status().map_err(|e| { BallError::InvalidConfig(format!("failed to execute hook '{}': {}", script_name, e)) })?; diff --git a/src/error/error.rs b/src/error/error.rs index 7a2f234..eb5da31 100644 --- a/src/error/error.rs +++ b/src/error/error.rs @@ -42,6 +42,9 @@ pub enum BallError { msg: String, }, ConfirmationAborted, + /// A prompt needed an answer under `--json`, where nobody is there to give + /// one. Carries the question, without its `[y/N]` hint. + ConfirmationRequired(String), /// No release asset matches the host platform. /// /// A hard error: only `PackageNotFound` is skippable during dependency @@ -187,6 +190,12 @@ impl fmt::Display for BallError { BallError::ConfirmationAborted => write!(f, "Aborted"), + BallError::ConfirmationRequired(question) => write!( + f, + "confirmation required: {} — pass --yes/-y to proceed under --json", + question + ), + BallError::NoMatchingAsset { package, platform, @@ -324,6 +333,43 @@ impl fmt::Display for BallError { } } +impl BallError { + /// The variant name, as the `code` field of a `--json` error document. + /// + /// Stable across message rewording, so a script can branch on it without + /// parsing the human text. + pub fn code(&self) -> &'static str { + match self { + BallError::UnsupportedOs(_) => "UnsupportedOs", + BallError::UnsupportedCommand(_) => "UnsupportedCommand", + BallError::UnknownParameter(_) => "UnknownParameter", + BallError::FileIoErr(_) => "FileIoErr", + BallError::InvalidConfig(_) => "InvalidConfig", + BallError::UnknownConfigEntry(_) => "UnknownConfigEntry", + BallError::NetworkError(_) => "NetworkError", + BallError::PackageNotFound(_) => "PackageNotFound", + BallError::HashMismatch(_) => "HashMismatch", + BallError::ExtractionFailed(_) => "ExtractionFailed", + BallError::DependencyCycle(_) => "DependencyCycle", + BallError::VersionConflict(_) => "VersionConflict", + BallError::PackageFrozen(_) => "PackageFrozen", + BallError::PackageManagerError(_) => "PackageManagerError", + BallError::InjectedCommandError(_) => "InjectedCommandError", + BallError::PipeRedirected { .. } => "PipeRedirected", + BallError::ConfirmationAborted => "ConfirmationAborted", + BallError::ConfirmationRequired(_) => "ConfirmationRequired", + BallError::NoMatchingAsset { .. } => "NoMatchingAsset", + BallError::NoBinaryFound { .. } => "NoBinaryFound", + BallError::PlatformMismatch { .. } => "PlatformMismatch", + BallError::RefereeBlocked { .. } => "RefereeBlocked", + BallError::RefereeScanBlocked { .. } => "RefereeScanBlocked", + BallError::RefereeUnavailable { .. } => "RefereeUnavailable", + BallError::RefereeAuditFailed { .. } => "RefereeAuditFailed", + BallError::UnresolvedDependencies(_) => "UnresolvedDependencies", + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -551,6 +597,42 @@ mod tests { assert!(debug.contains("PackageNotFound")); } + #[test] + fn test_confirmation_required_display() { + let err = BallError::ConfirmationRequired("Are you sure you want to eject fd?".to_string()); + let msg = format!("{}", err); + assert!(msg.starts_with("confirmation required: Are you sure you want to eject fd?")); + assert!(msg.contains("--yes")); + } + + #[test] + fn test_code_is_the_variant_name() { + // The Debug form starts with the variant name, so the two must agree. + let errors = [ + BallError::PackageNotFound("x".to_string()), + BallError::FileIoErr(std::io::Error::other("x")), + BallError::ConfirmationAborted, + BallError::ConfirmationRequired("x".to_string()), + BallError::PipeRedirected { + pipe: "stdin".to_string(), + msg: "x".to_string(), + }, + BallError::RefereeAuditFailed { + band: "warn", + packages: vec![], + }, + BallError::UnresolvedDependencies(vec![]), + ]; + for err in &errors { + assert!( + format!("{:?}", err).starts_with(err.code()), + "code '{}' does not match {:?}", + err.code(), + err + ); + } + } + #[test] fn test_scan_blocked_bullets_carry_a_severity_label() { use crate::security::scan::{ScanRule, ScanSeverity}; diff --git a/src/http/cargo.rs b/src/http/cargo.rs index de22ff5..30a2aab 100644 --- a/src/http/cargo.rs +++ b/src/http/cargo.rs @@ -2,13 +2,16 @@ use std::process::Command; use crate::core::package::{Package, PackageSource}; use crate::error::error::BallError; +use crate::utils::output::child_stdout; /// Install a crate from crates.io with `cargo install`. /// -/// Runs without `sudo`: cargo builds into the user's `~/.cargo/bin`. +/// Runs without `sudo`: cargo builds into the user's `~/.cargo/bin`. Under +/// `--json` its stdout goes to stderr (`child_stdout`), like a hook's. pub fn install_cargo_package(crate_name: &str) -> Result<(), BallError> { let status = Command::new("cargo") .args(["install", crate_name]) + .stdout(child_stdout()) .status() .map_err(|e| BallError::PackageManagerError(format!("failed to run cargo: {}", e)))?; diff --git a/src/http/system.rs b/src/http/system.rs index f8008a2..cfe30e5 100644 --- a/src/http/system.rs +++ b/src/http/system.rs @@ -2,23 +2,28 @@ use std::process::Command; use crate::core::package::{Package, PackageSource}; use crate::error::error::BallError; +use crate::utils::output::child_stdout; /// Install a system package using the native package manager. /// /// Invokes the appropriate CLI (`apt-get`, `dnf`, or `pacman`) under `sudo`. -/// Returns an error for unknown managers. +/// Returns an error for unknown managers. Under `--json` the manager's output +/// goes to stderr (`child_stdout`), so it never lands in the JSON document. pub fn install_system_package(manager: &str, name: &str) -> Result<(), BallError> { let status = match manager { "apt" => Command::new("sudo") .args(["apt-get", "install", "-y", name]) + .stdout(child_stdout()) .status() .map_err(|e| BallError::PackageManagerError(format!("failed to run apt-get: {}", e)))?, "dnf" => Command::new("sudo") .args(["dnf", "install", "-y", name]) + .stdout(child_stdout()) .status() .map_err(|e| BallError::PackageManagerError(format!("failed to run dnf: {}", e)))?, "pacman" => Command::new("sudo") .args(["pacman", "-S", "--noconfirm", name]) + .stdout(child_stdout()) .status() .map_err(|e| BallError::PackageManagerError(format!("failed to run pacman: {}", e)))?, _ => { diff --git a/src/main.rs b/src/main.rs index 5ab6038..a30b8f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,27 +11,56 @@ mod utils; use std::{ env::{self, home_dir}, + ffi::OsString, path::PathBuf, process::exit, }; use crate::{ - cli::parse::BallerCommand, + cli::parse::{scan_args, BallerCommand}, config::config::{BallerConfig, HooksConfig}, context::AppContext, error::error::BallError, utils::fs::ensure_dir, utils::logging::init_tracing, + utils::output::{document_printed, print_json_error, set_json_mode}, }; +/// What the error path needs to know about the run that failed. +struct Run { + json: bool, + /// The subcommand, or `None` when the command line never named one + command: Option, +} + fn main() { - if let Err(e) = entry() { - eprintln!("\n[Error]: {}", e); + let args: Vec = env::args_os().collect(); + + // Read off the raw arguments first, so an error raised before clap returns + // a parsed command can still be reported as JSON. + let raw = scan_args(&args); + let mut run = Run { + json: raw.json, + command: raw.subcommand, + }; + + if let Err(e) = entry(&args, &mut run) { + report_error(&run, &e); exit(1); } } -fn entry() -> Result<(), BallError> { +/// Under `--json` the error is the run's JSON document on stdout; otherwise, +/// and when a document already went out (`referee --fail-on` prints its report +/// and then fails), it goes to stderr as text so stdout holds one document. +fn report_error(run: &Run, e: &BallError) { + if run.json && !document_printed() && print_json_error(run.command.as_deref(), e).is_ok() { + return; + } + eprintln!("\n[Error]: {}", e); +} + +fn entry(args: &[OsString], run: &mut Run) -> Result<(), BallError> { if !cfg!(target_os = "linux") && !cfg!(target_os = "windows") { return Err(BallError::UnsupportedOs(format!( "the following OS is unsupported: {}\n\t please use Windows or Linux", @@ -39,9 +68,13 @@ fn entry() -> Result<(), BallError> { ))); } - let command: BallerCommand = BallerCommand::parse_command()?; + let command: BallerCommand = BallerCommand::parse_command(args)?; + run.json = command.json; + run.command = Some(command.command.name().to_string()); + set_json_mode(command.json); - if command.no_color { + // JSON is never coloured: escapes would land inside its strings. + if command.no_color || command.json { colored::control::set_override(false); } diff --git a/src/security/integration.rs b/src/security/integration.rs index 2e7cf02..0570254 100644 --- a/src/security/integration.rs +++ b/src/security/integration.rs @@ -108,6 +108,10 @@ impl Drop for MockServer { } fn read_request(stream: &TcpStream) -> Option { + // On Windows an accepted socket inherits the listener's non-blocking mode, + // which voids the read timeout: a request still in flight would read as + // `WouldBlock` and be dropped unrecorded. + stream.set_nonblocking(false).ok()?; stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?; let mut reader = BufReader::new(stream); @@ -295,6 +299,31 @@ const CRITICAL: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"; const MEDIUM: &str = "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"; const LOW: &str = "CVSS:3.1/AV:L/AC:H/PR:H/UI:R/S:U/C:L/I:N/A:N"; +#[test] +fn test_the_mock_server_waits_for_a_request_that_arrives_late() { + let server = MockServer::start(|_| (200, "{}".to_string())); + let address = server.base_url.trim_start_matches("http://").to_string(); + + // The server accepts within milliseconds; the request only follows later, + // as it can on a loaded CI runner. + let mut client = TcpStream::connect(&address).unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + thread::sleep(Duration::from_millis(200)); + let _ = client.write_all(b"GET /late HTTP/1.1\r\nHost: mock\r\n\r\n"); + let mut response = String::new(); + let _ = client.read_to_string(&mut response); + + assert_eq!( + server.request_count(), + 1, + "a request that arrives after the accept was dropped" + ); + assert_eq!(server.requests()[0].path, "/late"); + assert!(response.starts_with("HTTP/1.1 200"), "got: {:?}", response); +} + #[test] fn test_a_package_with_no_advisories_passes_silently() { let server = MockServer::start(|_| (200, batch(&[&[]]))); diff --git a/src/utils/fs.rs b/src/utils/fs.rs index 447a398..26fd22f 100644 --- a/src/utils/fs.rs +++ b/src/utils/fs.rs @@ -221,7 +221,17 @@ pub fn format_size(bytes: u64) -> String { } /// Prompt user for confirmation from stdin. Returns true if user confirms. -pub fn confirm(prompt: &str) -> Result { +/// +/// The prompt goes to stderr so stdout only ever carries a command's output. +/// Under `--json` (`json`) nothing is asked at all: the caller is a program, +/// so the question comes back as a `ConfirmationRequired` error for `main` to +/// report as JSON, and `--yes` is the way through. +pub fn confirm(prompt: &str, json: bool) -> Result { + if json { + let question = prompt.rsplit_once(" [").map_or(prompt, |(q, _)| q); + return Err(BallError::ConfirmationRequired(question.to_string())); + } + let stdin = io::stdin(); if !stdin.is_terminal() { @@ -231,8 +241,8 @@ pub fn confirm(prompt: &str) -> Result { }); } - print!("{prompt} "); - io::stdout().flush().ok(); + eprint!("{prompt} "); + io::stderr().flush().ok(); let mut input = String::new(); io::stdin().read_line(&mut input).ok(); Ok(matches!(input.trim().to_lowercase().as_str(), "y" | "yes")) diff --git a/src/utils/output.rs b/src/utils/output.rs index 275ac2b..1870c11 100644 --- a/src/utils/output.rs +++ b/src/utils/output.rs @@ -1,7 +1,41 @@ +use std::io; +use std::process::Stdio; +use std::sync::atomic::{AtomicBool, Ordering}; + use serde::Serialize; +use serde_json::{json, Value}; use crate::error::error::BallError; +/// Set once a document has gone to stdout, so the error path in `main` can +/// tell whether stdout is still free for a JSON error. +static DOCUMENT_PRINTED: AtomicBool = AtomicBool::new(false); + +/// `--json` for this run, set once by `main` before any command runs. +static JSON_MODE: AtomicBool = AtomicBool::new(false); + +/// Record whether this run is under `--json`. +/// +/// Process-wide, like `colored`'s override, so the code that spawns child +/// processes deep inside a command (hooks, package managers) can keep their +/// output off stdout without threading the flag through every caller. +pub fn set_json_mode(json: bool) { + JSON_MODE.store(json, Ordering::SeqCst); +} + +/// Where a child process's stdout should go. +/// +/// A hook or `apt-get` inherits baller's stdout, so under `--json` whatever it +/// prints would land in front of the JSON document. There it goes to stderr +/// instead, still visible; otherwise it is inherited as before. +pub fn child_stdout() -> Stdio { + if JSON_MODE.load(Ordering::SeqCst) { + Stdio::from(io::stderr()) + } else { + Stdio::inherit() + } +} + /// Print a value as pretty JSON on stdout. /// /// Used by commands running under the global `--json` flag, where every other @@ -10,9 +44,43 @@ pub fn print_json(value: &T) -> Result<(), BallError> { let rendered = serde_json::to_string_pretty(value) .map_err(|e| BallError::InvalidConfig(format!("failed to render JSON output: {}", e)))?; println!("{}", rendered); + mark_document_printed(); Ok(()) } +/// Record that this run has put its document on stdout. +/// +/// `print_json` calls this itself; anything else that writes a whole document +/// to stdout (`referee audit --format`, `referee sbom`) calls it directly. +pub fn mark_document_printed() { + DOCUMENT_PRINTED.store(true, Ordering::SeqCst); +} + +/// Whether a document has already gone to stdout during this run. +/// +/// `referee --fail-on` prints its report and then fails; a second document +/// after it would leave stdout unparseable, so its error stays on stderr. +pub fn document_printed() -> bool { + DOCUMENT_PRINTED.load(Ordering::SeqCst) +} + +/// The document a failed `--json` run prints in place of `[Error]: …`. +/// +/// `command` is the subcommand that failed, or `None` when the command line +/// could not be parsed far enough to name one. +pub fn error_json(command: Option<&str>, err: &BallError) -> Value { + json!({ + "command": command, + "error": err.to_string(), + "code": err.code(), + }) +} + +/// Print `err` as the run's JSON document on stdout. +pub fn print_json_error(command: Option<&str>, err: &BallError) -> Result<(), BallError> { + print_json(&error_json(command, err)) +} + #[cfg(test)] mod tests { use super::*; @@ -22,12 +90,24 @@ mod tests { fn test_print_json_serializes() { let value = json!({ "command": "roster", "count": 2 }); assert!(print_json(&value).is_ok()); + assert!(document_printed()); + } + + #[test] + fn test_error_json_carries_command_message_and_code() { + let err = BallError::PackageNotFound("fd".to_string()); + let value = error_json(Some("draft"), &err); + assert_eq!(value["command"], "draft"); + assert_eq!(value["error"], err.to_string()); + assert_eq!(value["code"], "PackageNotFound"); } #[test] - fn test_info_is_quiet_safe() { - tracing::info!(true, "suppressed"); - tracing::info!(false, "printed"); + fn test_error_json_without_a_command_is_null() { + let err = BallError::InvalidConfig("CLI Error: bad".to_string()); + let value = error_json(None, &err); + assert!(value["command"].is_null()); + assert_eq!(value["code"], "InvalidConfig"); } #[test] diff --git a/tests/json_output.rs b/tests/json_output.rs new file mode 100644 index 0000000..88aa687 --- /dev/null +++ b/tests/json_output.rs @@ -0,0 +1,610 @@ +//! `--json` end to end: whatever a run does, stdout holds exactly one JSON +//! document (issue #16). +//! +//! These drive the real binary rather than calling commands in-process, since +//! the bugs they pin are about which stream a byte lands on: a prompt on +//! stdout, an error that never reaches it, clap printing help on its own. +//! Every case gets its own `--config` directory, so cases share nothing and +//! can run in parallel. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::thread; + +use serde_json::{json, Value}; + +/// The binary under test. +/// +/// `BALLER_TEST_BIN` overrides cargo's path, so this test compiled for Windows +/// can be copied to a Windows host and pointed at the `baller.exe` beside it. +fn baller_bin() -> PathBuf { + std::env::var_os("BALLER_TEST_BIN") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_baller"))) +} + +/// A baller directory no other case can see. +struct Sandbox { + dir: PathBuf, +} + +impl Sandbox { + fn new(tag: &str) -> Self { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::SeqCst); + let dir = std::env::temp_dir().join("baller_json_tests").join(format!( + "{}_{}_{}", + std::process::id(), + tag, + n + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Sandbox { dir } + } + + /// Run baller with `args` after `--config `. + fn run(&self, args: &[&str]) -> Output { + let mut full = vec!["--config", self.dir.to_str().unwrap()]; + full.extend_from_slice(args); + self.run_raw(&full) + } + + /// Run baller with exactly `args`, home directories pointed at the sandbox. + fn run_raw(&self, args: &[&str]) -> Output { + Command::new(baller_bin()) + .args(args) + .env("HOME", &self.dir) + .env("USERPROFILE", &self.dir) + .env("LOCALAPPDATA", &self.dir) + .env_remove("BALLER_LOG") + .env_remove("CLICOLOR_FORCE") + .stdin(Stdio::null()) + .output() + .expect("run the baller binary") + } + + fn write_conf(&self, contents: &str) { + std::fs::write(self.dir.join("baller.conf"), contents).unwrap(); + } + + /// Put `name` on the roster as a cargo package, the way `draft` records one. + fn seed_package(&self, name: &str, version: &str) { + // The first run creates the database and its schema. + assert!(self.run(&["--json", "roster"]).status.success()); + let db = rusqlite::Connection::open(self.dir.join("db").join("baller.db")).unwrap(); + db.execute( + "INSERT INTO installed_packages (name, version, source, source_detail, install_path, bin_path) + VALUES (?1, ?2, 'cargo', ?1, ?3, ?3)", + rusqlite::params![ + name, + version, + self.dir.join("missing").to_string_lossy() + ], + ) + .unwrap(); + } +} + +impl Sandbox { + /// A `hook` script for `package` that prints `hook-ran-for-`. + fn write_hook(&self, package: &str, hook: &str) { + let hooks = self.dir.join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + #[cfg(windows)] + let (file, body) = ( + format!("{}_{}.ps1", package, hook), + "Write-Output \"hook-ran-for-$env:BALLER_PACKAGE_NAME\"\n", + ); + #[cfg(not(windows))] + let (file, body) = ( + format!("{}_{}.sh", package, hook), + "echo \"hook-ran-for-$BALLER_PACKAGE_NAME\"\n", + ); + std::fs::write(hooks.join(file), body).unwrap(); + } +} + +impl Drop for Sandbox { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// Stdout parsed as one JSON document; anything else on it fails the test. +fn document(out: &Output) -> Value { + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "stdout is not a single JSON document ({}):\n--- stdout\n{}\n--- stderr\n{}", + e, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }) +} + +/// A failed run's JSON error: exit 1, the document on stdout, stderr silent. +fn error_document(out: &Output) -> Value { + assert_eq!(out.status.code(), Some(1), "expected exit code 1"); + let value = document(out); + assert!( + out.stderr.is_empty(), + "a --json error should leave stderr empty, got: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(value["error"].is_string(), "no error message in {}", value); + value +} + +fn stdout(out: &Output) -> String { + String::from_utf8_lossy(&out.stdout).to_string() +} + +fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).to_string() +} + +// ---------------------------------------------------------------- help/version + +#[test] +fn test_json_help_overview_is_a_document() { + let sandbox = Sandbox::new("help_overview"); + let out = sandbox.run(&["--json", "help"]); + assert!(out.status.success()); + let value = document(&out); + assert_eq!(value["command"], "help"); + assert_eq!(value["commands"].as_array().unwrap().len(), 12); + assert_eq!(value["injected"], json!([])); + assert!(value["global_options"] + .as_array() + .unwrap() + .iter() + .any(|o| o["name"] == "--json")); +} + +#[test] +fn test_json_help_topic_is_a_document() { + let sandbox = Sandbox::new("help_topic"); + let value = document(&sandbox.run(&["--json", "help", "eject"])); + assert_eq!(value["topic"], "eject"); + assert_eq!(value["kind"], "builtin"); + assert_eq!(value["usage"], "baller eject "); +} + +#[test] +fn test_json_help_and_version_flags_are_answered_in_json() { + let sandbox = Sandbox::new("display_flags"); + + for args in [ + vec!["--json", "--help"], + vec!["--json", "-h"], + vec!["--help", "--json"], + // A top-level -h is answered before the subcommand after it, as clap does. + vec!["--json", "--help", "draft"], + ] { + let out = sandbox.run(&args); + assert!(out.status.success(), "{:?} failed", args); + let value = document(&out); + assert_eq!(value["command"], "help", "{:?}", args); + assert!(value["topic"].is_null(), "{:?}", args); + } + + for (args, topic) in [ + (vec!["--json", "draft", "--help"], "draft"), + (vec!["draft", "-h", "--json"], "draft"), + // draft's own --version takes a value; it is not a version request. + ( + vec!["--json", "draft", "fd", "--version", "1.0.0", "--help"], + "draft", + ), + (vec!["--json", "referee", "cache", "--help"], "referee"), + ] { + let value = document(&sandbox.run(&args)); + assert_eq!(value["topic"], topic, "{:?}", args); + } + + for args in [ + vec!["--json", "-V"], + vec!["--json", "--version"], + vec!["--json", "version"], + ] { + let out = sandbox.run(&args); + assert!(out.status.success(), "{:?} failed", args); + assert_eq!( + document(&out), + json!({ "command": "version", "version": env!("CARGO_PKG_VERSION") }), + "{:?}", + args + ); + } +} + +#[test] +fn test_json_help_flag_keeps_the_config_directory() { + let sandbox = Sandbox::new("help_config"); + let binary = baller_bin(); + std::fs::write( + sandbox.dir.join("injected_commands.json"), + json!([{ + "command_name": "my-tool", + "description": "A helpful tool", + "version": "1.0.0", + "flags": [], + "author": "", + "require_root": false, + "depends": [], + "path": binary, + }]) + .to_string(), + ) + .unwrap(); + + // --config sits before the help flag; the rewrite must carry it along, or + // the injected commands stored under it go missing. + let value = document(&sandbox.run(&["--json", "--help"])); + assert_eq!(value["injected"][0]["name"], "my-tool"); +} + +#[test] +fn test_text_help_and_version_are_unchanged() { + let sandbox = Sandbox::new("text_display"); + + // clap names the binary as invoked: `baller.exe` on Windows. + let out = sandbox.run(&["--help"]); + assert!(out.status.success()); + assert!(stdout(&out).contains("[OPTIONS] ")); + assert!(serde_json::from_slice::(&out.stdout).is_err()); + + let out = sandbox.run(&["-V"]); + assert_eq!( + stdout(&out), + format!("baller {}\n", env!("CARGO_PKG_VERSION")) + ); + + let out = sandbox.run(&["version"]); + assert_eq!( + stdout(&out), + format!("Baller {}\n", env!("CARGO_PKG_VERSION")) + ); + + // --quiet hides progress, never a command's result (#41). + let out = sandbox.run(&["-q", "version"]); + assert_eq!( + stdout(&out), + format!("Baller {}\n", env!("CARGO_PKG_VERSION")) + ); + + let out = sandbox.run(&["--no-color", "help"]); + assert!(stdout(&out).starts_with("B.A.L.L.E.R - ")); + assert!(stdout(&out).contains("Commands:")); +} + +// ---------------------------------------------------------------------- errors + +#[test] +fn test_json_errors_are_documents_on_stdout() { + let sandbox = Sandbox::new("errors"); + + let value = error_document(&sandbox.run(&["--json", "help", "not-a-command"])); + assert_eq!(value["command"], "help"); + assert_eq!(value["code"], "UnsupportedCommand"); + + let missing = sandbox.dir.join("missing.toml"); + let value = error_document(&sandbox.run(&["--json", "build", missing.to_str().unwrap()])); + assert_eq!(value["command"], "build"); + assert!(value["error"] + .as_str() + .unwrap() + .contains("manifest not found")); + + let value = error_document(&sandbox.run(&["--json", "eject", "not-installed"])); + assert_eq!(value["command"], "eject"); + assert_eq!(value["code"], "PackageNotFound"); +} + +#[test] +fn test_json_cli_errors_are_documents_on_stdout() { + let sandbox = Sandbox::new("cli_errors"); + + // clap fails before it returns a parsed command; the subcommand is still + // read off the raw arguments. + let value = error_document(&sandbox.run(&["--json", "draft"])); + assert_eq!(value["command"], "draft"); + assert_eq!(value["code"], "InvalidConfig"); + assert!(value["error"].as_str().unwrap().contains("")); + + let value = error_document(&sandbox.run(&["--json", "--bogus"])); + assert!(value["command"].is_null()); + + let value = error_document(&sandbox.run(&["--json"])); + assert!(value["command"].is_null()); + assert!(value["error"] + .as_str() + .unwrap() + .contains("requires a subcommand")); +} + +#[test] +fn test_text_errors_still_go_to_stderr() { + let sandbox = Sandbox::new("text_errors"); + let out = sandbox.run(&["help", "not-a-command"]); + assert_eq!(out.status.code(), Some(1)); + assert!(out.stdout.is_empty()); + assert!(stderr(&out).contains("[Error]: the following command does not exist")); +} + +#[test] +fn test_json_after_an_injected_command_belongs_to_it() { + let sandbox = Sandbox::new("external_json"); + // `--json` after an unknown subcommand is that command's argument, so + // baller itself is not in JSON mode and reports the error as text. + let out = sandbox.run(&["no-such-tool", "--json"]); + assert_eq!(out.status.code(), Some(1)); + assert!(out.stdout.is_empty()); + assert!(stderr(&out).contains("no-such-tool")); +} + +// --------------------------------------------------------------- confirmations + +#[test] +fn test_json_eject_without_yes_asks_for_it_instead_of_prompting() { + let sandbox = Sandbox::new("eject_confirm"); + sandbox.seed_package("some-pkg", "1.0.0"); + + let value = error_document(&sandbox.run(&["--json", "eject", "some-pkg"])); + assert_eq!(value["command"], "eject"); + assert_eq!(value["code"], "ConfirmationRequired"); + let message = value["error"].as_str().unwrap(); + assert!(message.contains("Are you sure you want to eject some-pkg?")); + assert!(message.contains("--yes")); + assert!(!message.contains("[y/N]")); + + // Nothing was ejected. + let roster = document(&sandbox.run(&["--json", "roster"])); + assert_eq!(roster["count"], 1); +} + +#[test] +fn test_json_sweep_without_yes_asks_for_it_instead_of_prompting() { + let sandbox = Sandbox::new("sweep_confirm"); + let cache = sandbox.dir.join("cache"); + std::fs::create_dir_all(&cache).unwrap(); + let archive = cache.join("pkg-1.0.0.tar.gz"); + std::fs::write(&archive, vec![0u8; 2048]).unwrap(); + + let value = error_document(&sandbox.run(&["--json", "sweep"])); + assert_eq!(value["command"], "sweep"); + assert_eq!(value["code"], "ConfirmationRequired"); + assert!(archive.exists()); + + let value = document(&sandbox.run(&["--json", "--yes", "sweep"])); + assert_eq!(value["command"], "sweep"); + assert!(!archive.exists()); +} + +/// A `.ball` file for a command named `name` that runs baller itself. +fn ball_file(dir: &Path, name: &str) -> PathBuf { + let path = dir.join(format!("{}.ball", name)); + std::fs::write( + &path, + format!( + "[COMMAND-NAME]\nCOMMAND-NAME = \"{}\"\n\n[DESCRIPTION]\nDESCRIPTION = \"Test tool\"\n\n\ + [VERSION]\nVERSION = \"1.0.0\"\n\n[PATH]\nPATH = {}\n", + name, + baller_bin().display() + ), + ) + .unwrap(); + path +} + +#[test] +fn test_json_inject_without_yes_asks_for_it_and_with_yes_reports_json() { + let sandbox = Sandbox::new("inject"); + let ball = ball_file(&sandbox.dir, "json-tool"); + + let value = error_document(&sandbox.run(&["--json", "inject", ball.to_str().unwrap()])); + assert_eq!(value["command"], "inject"); + assert_eq!(value["code"], "ConfirmationRequired"); + + let out = sandbox.run(&["--json", "--yes", "inject", ball.to_str().unwrap()]); + assert!(out.status.success(), "inject failed: {}", stdout(&out)); + let value = document(&out); + assert_eq!(value["command"], "inject"); + assert_eq!(value["name"], "json-tool"); + + let help = document(&sandbox.run(&["--json", "help", "json-tool"])); + assert_eq!(help["kind"], "injected"); + assert_eq!(help["description"], "Test tool"); +} + +// ------------------------------------------------------------ success commands + +#[test] +fn test_json_read_only_commands_print_one_document() { + let sandbox = Sandbox::new("read_only"); + sandbox.seed_package("serde", "1.0.229"); + + for args in [ + vec!["--json", "roster"], + vec!["--json", "roster", "serde"], + vec!["--json", "freeze", "--list"], + vec!["--json", "sweep", "--dry-run"], + vec!["--json", "referee", "config"], + vec!["--json", "referee", "cache"], + vec!["--json", "referee", "sbom"], + vec!["--json", "freeze", "serde"], + vec!["--json", "freeze", "serde"], + ] { + let out = sandbox.run(&args); + assert!(out.status.success(), "{:?} failed: {}", args, stderr(&out)); + document(&out); + } +} + +// ------------------------------------------------------------- roster search + +/// Every registry source switched off, so a search answers at once, with +/// nothing, and never touches the network. +const NO_SOURCES: &str = "github_enabled = false\nballer_enabled = false\n\ + chocolatey_enabled = false\nsystem_enabled = false\n\ + cargo_enabled = false\n"; + +#[test] +fn test_json_roster_of_an_uninstalled_name_is_one_document() { + let sandbox = Sandbox::new("roster_remote"); + sandbox.write_conf(NO_SOURCES); + + // The "not found locally" notice used to be printed ahead of this (#40). + let out = sandbox.run(&["--json", "roster", "not-installed"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert_eq!( + document(&out), + json!({ "command": "roster", "query": "not-installed", "results": [] }) + ); + assert!(out.stderr.is_empty(), "{}", stderr(&out)); +} + +#[test] +fn test_roster_search_notice_is_progress_on_stderr() { + let sandbox = Sandbox::new("roster_notice"); + sandbox.write_conf(NO_SOURCES); + + let out = sandbox.run(&["roster", "not-installed"]); + assert!(out.status.success()); + assert!(stdout(&out).contains("No packages found matching 'not-installed'")); + assert!(!stdout(&out).contains("not found locally")); + assert!(stderr(&out).contains("'not-installed' not found locally, searching registries")); + + let out = sandbox.run(&["-q", "roster", "not-installed"]); + assert!(out.status.success()); + assert!(!stderr(&out).contains("not found locally")); +} + +// ----------------------------------------------------------- child processes + +#[test] +fn test_json_hook_output_goes_to_stderr() { + let sandbox = Sandbox::new("hook_output"); + sandbox.seed_package("a-pkg", "1.0.0"); + sandbox.seed_package("b-pkg", "1.0.0"); + sandbox.write_hook("a-pkg", "pre_eject"); + sandbox.write_hook("b-pkg", "pre_eject"); + + // The hook still runs under --json, but what it prints stays out of the + // document. + let out = sandbox.run(&["--json", "--yes", "eject", "a-pkg"]); + assert!(out.status.success(), "{}", stderr(&out)); + let value = document(&out); + assert_eq!(value["command"], "eject"); + assert_eq!(value["package"], "a-pkg"); + assert!(stderr(&out).contains("hook-ran-for-a-pkg")); + + // Text mode is unchanged: the hook shares baller's stdout. + let out = sandbox.run(&["--yes", "eject", "b-pkg"]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(stdout(&out).contains("hook-ran-for-b-pkg")); +} + +// --------------------------------------------------------- referee --fail-on + +/// An OSV stand-in: every package matches one critical advisory. +fn critical_osv() -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + answer(stream); + } + }); + base +} + +fn answer(mut stream: TcpStream) { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut request_line = String::new(); + if reader.read_line(&mut request_line).is_err() { + return; + } + let mut length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap_or(0); + } + } + let mut body = vec![0u8; length]; + let _ = reader.read_exact(&mut body); + + let response = if request_line.contains("/v1/vulns/") { + json!({ + "id": "GHSA-test", + "summary": "serde is affected", + "aliases": ["CVE-GHSA-test"], + "severity": [{ + "type": "CVSS_V3", + "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" + }], + "affected": [{ + "package": { "ecosystem": "crates.io", "name": "serde" }, + "ranges": [{ "type": "SEMVER", "events": [{ "introduced": "0" }] }] + }] + }) + } else { + let queries = serde_json::from_slice::(&body) + .ok() + .and_then(|v| v["queries"].as_array().map(Vec::len)) + .unwrap_or(1); + let hit = json!({ "vulns": [{ "id": "GHSA-test", "modified": "2026-01-01T00:00:00Z" }] }); + json!({ "results": vec![hit; queries] }) + } + .to_string(); + + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + response.len(), + response + ); +} + +#[test] +fn test_fail_on_keeps_stdout_to_the_report() { + let sandbox = Sandbox::new("fail_on"); + sandbox.write_conf(&format!("osv_base_url = {}\n", critical_osv())); + sandbox.seed_package("serde", "1.0.229"); + + for args in [ + vec![ + "--json", + "referee", + "audit", + "--no-scan", + "--fail-on", + "block", + ], + vec!["--json", "referee", "check", "--fail-on", "block"], + ] { + let out = sandbox.run(&args); + assert_eq!(out.status.code(), Some(1), "{:?} should fail", args); + + // One document, and it is the report: the failure is not a second one. + let value = document(&out); + assert_eq!(value["command"], "referee", "{:?}", args); + assert!(value.get("error").is_none(), "{:?}", args); + assert_eq!(value["packages"][0]["name"], "serde", "{:?}", args); + + assert!( + stderr(&out).contains("[Error]"), + "{:?}: the failure should be on stderr, got: {}", + args, + stderr(&out) + ); + } +}