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
This commit is contained in:
Matthias Endler 2024-01-24 13:12:55 +01:00 committed by GitHub
parent 3558031527
commit d481c061b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 24 additions and 2 deletions

View file

@ -382,8 +382,8 @@ async fn run(opts: &LycheeOptions) -> Result<i32> {
}
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 {

View file

@ -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::<Value>(&output.stdout).is_ok());
Ok(())
}
#[test]
fn test_exclude_all_private() -> Result<()> {
test_json_output!(