From d481c061b91fd2de28a8678dcba605f3cf920adf Mon Sep 17 00:00:00 2001 From: Matthias Endler Date: Wed, 24 Jan 2024 13:12:55 +0100 Subject: [PATCH] Always output valid JSON with `--format=json` (#1356) Previously, when using JSON as the output format, any supplementary warnings included in the output would invalidate the JSON structure. This pull request addresses this issue by redirecting any extra warnings to `stderr`. This change guarantees that the output remains valid JSON even when additional warnings are present. Fixes https://github.com/lycheeverse/lychee/issues/1355 --- lychee-bin/src/main.rs | 4 ++-- lychee-bin/tests/cli.rs | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lychee-bin/src/main.rs b/lychee-bin/src/main.rs index 400b6d7..3535fea 100644 --- a/lychee-bin/src/main.rs +++ b/lychee-bin/src/main.rs @@ -382,8 +382,8 @@ async fn run(opts: &LycheeOptions) -> Result { } if github_issues && opts.config.github_token.is_none() { - let mut f = io::stdout(); - color!(f, YELLOW, "\u{1f4a1} There were issues with Github URLs. You could try setting a Github token and running lychee again.",)?; + let mut handle = io::stderr(); + color!(handle, YELLOW, "\u{1f4a1} There were issues with Github URLs. You could try setting a Github token and running lychee again.",)?; } if opts.config.cache { diff --git a/lychee-bin/tests/cli.rs b/lychee-bin/tests/cli.rs index e71ea95..c97fa37 100644 --- a/lychee-bin/tests/cli.rs +++ b/lychee-bin/tests/cli.rs @@ -111,6 +111,28 @@ mod cli { }}; } + /// JSON-formatted output should always be valid JSON. + /// Additional hints and error messages should be printed to `stderr`. + /// See https://github.com/lycheeverse/lychee/issues/1355 + #[test] + fn test_valid_json_output_to_stdout_on_error() -> Result<()> { + let test_path = fixtures_path().join("TEST_GITHUB_404.md"); + + let mut cmd = main_command(); + cmd.arg("--format") + .arg("json") + .arg(test_path) + .assert() + .failure() + .code(2); + + let output = cmd.output()?; + + // Check that the output is valid JSON + assert!(serde_json::from_slice::(&output.stdout).is_ok()); + Ok(()) + } + #[test] fn test_exclude_all_private() -> Result<()> { test_json_output!(