Skip to content

Commit d481c06

Browse files
authored
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 #1355
1 parent 3558031 commit d481c06

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

lychee-bin/src/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -382,8 +382,8 @@ async fn run(opts: &LycheeOptions) -> Result<i32> {
382382
}
383383

384384
if github_issues && opts.config.github_token.is_none() {
385-
let mut f = io::stdout();
386-
color!(f, YELLOW, "\u{1f4a1} There were issues with Github URLs. You could try setting a Github token and running lychee again.",)?;
385+
let mut handle = io::stderr();
386+
color!(handle, YELLOW, "\u{1f4a1} There were issues with Github URLs. You could try setting a Github token and running lychee again.",)?;
387387
}
388388

389389
if opts.config.cache {

lychee-bin/tests/cli.rs

+22
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,28 @@ mod cli {
111111
}};
112112
}
113113

114+
/// JSON-formatted output should always be valid JSON.
115+
/// Additional hints and error messages should be printed to `stderr`.
116+
/// See https://github.com/lycheeverse/lychee/issues/1355
117+
#[test]
118+
fn test_valid_json_output_to_stdout_on_error() -> Result<()> {
119+
let test_path = fixtures_path().join("TEST_GITHUB_404.md");
120+
121+
let mut cmd = main_command();
122+
cmd.arg("--format")
123+
.arg("json")
124+
.arg(test_path)
125+
.assert()
126+
.failure()
127+
.code(2);
128+
129+
let output = cmd.output()?;
130+
131+
// Check that the output is valid JSON
132+
assert!(serde_json::from_slice::<Value>(&output.stdout).is_ok());
133+
Ok(())
134+
}
135+
114136
#[test]
115137
fn test_exclude_all_private() -> Result<()> {
116138
test_json_output!(

0 commit comments

Comments
 (0)