Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

fix(cli): print usage errors as JSON on stdout under --json (#1369)

Leon.Cb5743acb9a1a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a123364..d0dcc1c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@
- PHP: `shuffle()`, `str_shuffle()`, `array_rand()`, `random_bytes()` and `lcg_value()` count as
randomness, as `rand()` does. Before, a function that picked or shuffled with them was bridged as
pure, and each recorded case was one draw no port could repeat (#1340 by @Alkhanizi-hashem).
+- A usage error under `--json` (a bad flag value, an unknown option, a missing argument) prints
+ the error JSON on stdout with code `usage` and clap's first line as the message, like every other
+ failure. Before, clap exited before `run()` and stdout stayed empty. `--help`, `--version` and
+ runs without `--json` print what they did before (#1351 by @zichen0116).
- Picking at random from a collection counts as randomness: Swift `.shuffled()` and
`.randomElement()` (the entries never matched, since a name after `.` is skipped), Ruby `.shuffle`
and `.sample`, and Java and Kotlin `.shuffled()`, `.random()` and `Collections.shuffle(`. Before,
diff --git a/src/main.rs b/src/main.rs
index cfc18c6f..4aa2c3f6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1293,7 +1293,39 @@ fn main() -> ExitCode {
}
fn run() -> Result<ExitCode> {
- match Cli::parse().command {
+ // Parse with `try_parse()` so a usage error under `--json` can be reported
+ // as error JSON on stdout, like every other failure (#1351). `Cli::parse()`
+ // exits the process before `main()` gets a chance to do that.
+ let command = match Cli::try_parse() {
+ Ok(cli) => cli.command,
+ Err(e) => {
+ use clap::error::ErrorKind::{DisplayHelp, DisplayVersion};
+ match e.kind() {
+ // Not errors: print exactly what `Cli::parse()` prints today.
+ DisplayHelp | DisplayVersion => {
+ let _ = e.print();
+ return Ok(ExitCode::SUCCESS);
+ }
+ _ => {
+ if wants_json() {
+ let rendered = e.to_string();
+ let first_line = rendered.lines().next().unwrap_or_default();
+ let message = first_line.strip_prefix("error: ").unwrap_or(first_line);
+ println!(
+ "{}",
+ serde_json::json!({
+ "schema": rust_anything::state::schema("error"),
+ "error": { "code": "usage", "message": message },
+ })
+ );
+ }
+ let _ = e.print();
+ return Ok(ExitCode::from(2));
+ }
+ }
+ }
+ };
+ match command {
Cmd::Analyze {
root,
json,
diff --git a/tests/json_output.rs b/tests/json_output.rs
index 5a6f0755..b66911ca 100644
--- a/tests/json_output.rs
+++ b/tests/json_output.rs
@@ -152,6 +152,34 @@ fn map_says_which_units_are_on_and_which_port_version_it_saw() {
std::fs::remove_dir_all(&repo).unwrap();
}
+#[test]
+fn a_failure_under_json_from_usage_is_json_on_stdout() {
+ for args in [
+ vec!["gate", "--json", "--held-out-cases", "many"],
+ vec!["analyze", ".", "--json", "--lang", "klingon"],
+ ] {
+ let out = run(&args, None);
+ assert_eq!(out.status.code(), Some(2));
+ let v = json(&out);
+ assert_eq!(v["schema"], "rust-anything/error@1");
+ assert_eq!(v["error"]["code"], "usage");
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert_eq!(
+ v["error"]["message"],
+ stderr
+ .lines()
+ .next()
+ .unwrap()
+ .strip_prefix("error: ")
+ .unwrap()
+ );
+ let plain: Vec<_> = args.into_iter().filter(|arg| *arg != "--json").collect();
+ let out = run(&plain, None);
+ assert_eq!(out.status.code(), Some(2));
+ assert!(out.stdout.is_empty(), "without --json stdout stays empty");
+ }
+}
+
#[test]
fn a_failure_under_json_is_json_on_stdout() {
for args in [["gate", "--json"], ["diff", "--json"]] {