Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
576 changes: 311 additions & 265 deletions src/cli.rs

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ fn main() {
eprintln!("{}", e);
}
if !json_errors && matches!(e, wavec::errors::CliError::Usage(_)) {
wavec::cli::print_usage();
if let Err(error) = wavec::cli::print_usage() {
eprintln!("could not write usage to stdout: {error}");
}
}
process::exit(e.exit_code());
}
Expand Down
50 changes: 50 additions & 0 deletions tests/cli_stdout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: MPL-2.0

use std::process::Command;
use std::{fs::File, io};

const WAVEC: &str = env!("CARGO_BIN_EXE_wavec");

#[test]
fn help_version_and_print_handle_a_closed_stdout_reader() {
let cases: &[(&[&str], &str)] = &[
(&["--help"], "Wave Compiler"),
(&["--version"], "wavec"),
(&["print", "host-target"], "-"),
(&["print", "supported-targets", "--format=json"], "["),
];
for (args, expected) in cases {
let normal = Command::new(WAVEC).args(*args).output().unwrap();
assert!(normal.status.success(), "{args:?}: {normal:?}");
assert!(String::from_utf8_lossy(&normal.stdout).contains(expected), "{args:?}: {normal:?}");

let (reader, writer) = io::pipe().unwrap();
drop(reader);
let closed = Command::new(WAVEC).args(*args).stdout(writer).output().unwrap();
assert!(closed.status.success(), "{args:?}: {closed:?}");
assert_eq!(closed.stderr, normal.stderr, "{args:?}");
}
}

#[test]
fn closed_stdout_preserves_usage_error_status_and_diagnostic() {
let args = ["print", "not-a-wave-print-item"];
let normal = Command::new(WAVEC).args(args).output().unwrap();
assert_eq!(normal.status.code(), Some(2), "{normal:?}");
assert!(!normal.stdout.is_empty(), "{normal:?}");
assert!(!normal.stderr.is_empty(), "{normal:?}");

let (reader, writer) = io::pipe().unwrap();
drop(reader);
let closed = Command::new(WAVEC).args(args).stdout(writer).output().unwrap();
assert_eq!(closed.status.code(), normal.status.code(), "{closed:?}");
assert_eq!(closed.stderr, normal.stderr);
}

#[test]
fn help_reports_other_stdout_errors() {
let read_only = File::open(WAVEC).unwrap();
let output = Command::new(WAVEC).arg("--help").stdout(read_only).output().unwrap();
assert_eq!(output.status.code(), Some(3), "{output:?}");
assert!(String::from_utf8_lossy(&output.stderr).contains("IO Error"), "{output:?}");
}
41 changes: 27 additions & 14 deletions tools/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use crate::{error, Result};
use std::ffi::OsString;
use std::io::Write;
use std::path::PathBuf;
use std::time::Duration;

Expand Down Expand Up @@ -174,28 +175,40 @@ pub fn main(arguments: &[OsString]) -> Result<i32> {
spec.cwd = cwd;
spec.stream = !capture;
let output = spec.run()?;
let status = if output.status < 0 { 128 - output.status } else { output.status };
if capture {
print!("{}", output.text_stdout());
let stdout_result = utils::cli_output::stdout().and_then(|mut stdout| {
write!(stdout, "{}", output.text_stdout())?;
stdout.flush()
});
eprint!("{}", output.text_stderr());
if let Err(error) = stdout_result {
if output.failure.is_none() && status == 0 {
return Err(error.into());
}
eprintln!("wave-tools: could not write captured stdout: {error}");
}
}
if let Some(reason) = output.failure {
return Err(error(reason));
}
return Ok(if output.status < 0 { 128 - output.status } else { output.status });
return Ok(status);
}
if command == "--help" || command == "help" {
println!("wave-tools: native Wave build, test and distribution contracts");
println!(" config version|rust-version|build-inputs");
println!(" matrix [--json] [--github-output PATH]");
println!(" test|corpus --wavec PATH [--target-id ID] [--report-json PATH]");
println!(" check std-policy|std-inputs|case-sources|binary|crt|extracted-package|ci-jobs|release-assets");
println!(" maintain format|std-api|maintainers|unicode|verify-patch");
println!(" build-cargo|package|install|clean");
println!(" prepare host|cross|loongarch|std|pins|tooling");
println!(" sdk|freebsd|native-std|msvc-acceptance|diagnose-windows-arm64");
println!(" ci artifact|report|runtime-evidence");
println!(" release|nightly --stage STAGE [--publish]");
println!(" exec [--timeout SECONDS] [--output-limit BYTES] -- COMMAND ...");
let mut stdout = utils::cli_output::stdout()?;
writeln!(stdout, "wave-tools: native Wave build, test and distribution contracts")?;
writeln!(stdout, " config version|rust-version|build-inputs")?;
writeln!(stdout, " matrix [--json] [--github-output PATH]")?;
writeln!(stdout, " test|corpus --wavec PATH [--target-id ID] [--report-json PATH]")?;
writeln!(stdout, " check std-policy|std-inputs|case-sources|binary|crt|extracted-package|ci-jobs|release-assets")?;
writeln!(stdout, " maintain format|std-api|maintainers|unicode|verify-patch")?;
writeln!(stdout, " build-cargo|package|install|clean")?;
writeln!(stdout, " prepare host|cross|loongarch|std|pins|tooling")?;
writeln!(stdout, " sdk|freebsd|native-std|msvc-acceptance|diagnose-windows-arm64")?;
writeln!(stdout, " ci artifact|report|runtime-evidence")?;
writeln!(stdout, " release|nightly --stage STAGE [--publish]")?;
writeln!(stdout, " exec [--timeout SECONDS] [--output-limit BYTES] -- COMMAND ...")?;
stdout.flush()?;
return Ok(0);
}
Err(error(format!("unknown command: {}", command.to_string_lossy())))
Expand Down
14 changes: 8 additions & 6 deletions tools/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ fn capture(
) -> thread::JoinHandle<std::io::Result<Vec<u8>>> {
thread::spawn(move || {
let mut stdout_log = stdout_log;
let mut stdout = (stream && !stderr).then(utils::cli_output::stdout).transpose()?;
let mut bytes = Vec::new();
let mut buffer = [0; 16 * 1024];
loop {
Expand All @@ -249,19 +250,20 @@ fn capture(
.map_err(|_| std::io::Error::other("log mutex poisoned"))?
.write_all(&buffer[..count])?;
}
if stream {
if stderr {
std::io::stderr().write_all(&buffer[..count])?;
} else {
std::io::stdout().write_all(&buffer[..count])?;
}
if let Some(stdout) = &mut stdout {
stdout.write_all(&buffer[..count])?;
} else if stream && stderr {
std::io::stderr().write_all(&buffer[..count])?;
}
let retained = (limit.saturating_sub(bytes.len())).min(count);
bytes.extend_from_slice(&buffer[..retained]);
if retained != count {
overflow.store(true, Ordering::SeqCst);
}
}
if let Some(stdout) = &mut stdout {
stdout.flush()?;
}
Ok(bytes)
})
}
Expand Down
64 changes: 64 additions & 0 deletions tools/tests/cli_stdout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: MPL-2.0

use std::process::Command;
use std::{fs::File, io};

const WAVE_TOOLS: &str = env!("CARGO_BIN_EXE_wave-tools");

#[test]
fn help_handles_a_closed_stdout_reader() {
let normal = Command::new(WAVE_TOOLS).arg("--help").output().unwrap();
assert!(normal.status.success(), "{normal:?}");
assert!(normal
.stdout
.starts_with(b"wave-tools: native Wave build, test and distribution contracts\n"));

let (reader, writer) = io::pipe().unwrap();
drop(reader);
let closed = Command::new(WAVE_TOOLS).arg("--help").stdout(writer).output().unwrap();
assert!(closed.status.success(), "{closed:?}");
assert_eq!(closed.stderr, normal.stderr);
}

#[test]
fn exec_preserves_child_status_and_stderr_when_stdout_closes() {
for capture in [false, true] {
let mut command = Command::new(WAVE_TOOLS);
command.args(["exec", "--timeout", "10"]);
if capture {
command.arg("--capture");
}
command.args(["--", WAVE_TOOLS, "__fixture-process", "bytes"]);

let normal = command.output().unwrap();
assert_eq!(normal.status.code(), Some(7), "{normal:?}");
assert_eq!(normal.stdout, if capture { "�".as_bytes() } else { &[255] });
assert_eq!(normal.stderr, b"error");

let (reader, writer) = io::pipe().unwrap();
drop(reader);
let closed = command.stdout(writer).output().unwrap();
assert_eq!(closed.status.code(), normal.status.code(), "{closed:?}");
assert_eq!(closed.stderr, normal.stderr);

if capture {
let read_only = File::open(WAVE_TOOLS).unwrap();
let failed_write = command.stdout(read_only).output().unwrap();
assert_eq!(failed_write.status.code(), normal.status.code(), "{failed_write:?}");
assert!(failed_write.stderr.starts_with(b"error"), "{failed_write:?}");
assert!(
String::from_utf8_lossy(&failed_write.stderr)
.contains("could not write captured stdout"),
"{failed_write:?}"
);
}
}
}

#[test]
fn help_reports_other_stdout_errors() {
let read_only = File::open(WAVE_TOOLS).unwrap();
let output = Command::new(WAVE_TOOLS).arg("--help").stdout(read_only).output().unwrap();
assert_eq!(output.status.code(), Some(1), "{output:?}");
assert!(output.stderr.starts_with(b"wave-tools: "), "{output:?}");
}
55 changes: 55 additions & 0 deletions utils/src/cli_output.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// SPDX-License-Identifier: MPL-2.0

use std::io::{self, ErrorKind, Write};
#[cfg(unix)]
use std::os::fd::AsFd;

#[cfg(unix)]
type Output = std::fs::File;
#[cfg(not(unix))]
type Output = io::Stdout;

/// CLI output can be discarded after the downstream reader closes the pipe.
/// Other write errors still reach the command's normal error handler.
pub struct CliStdout {
output: Output,
closed: bool,
}

pub fn stdout() -> io::Result<CliStdout> {
// Rust's Unix Stdout discards EBADF. Write through an owned duplicate
// so that invalid and read-only stdout descriptors surface as errors.
#[cfg(unix)]
let output = Output::from(io::stdout().as_fd().try_clone_to_owned()?);
#[cfg(not(unix))]
let output = io::stdout();
Ok(CliStdout { output, closed: false })
}

impl Write for CliStdout {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.closed {
return Ok(bytes.len());
}
match self.output.write(bytes) {
Err(error) if error.kind() == ErrorKind::BrokenPipe => {
self.closed = true;
Ok(bytes.len())
},
result => result,
}
}

fn flush(&mut self) -> io::Result<()> {
if self.closed {
return Ok(());
}
match self.output.flush() {
Err(error) if error.kind() == ErrorKind::BrokenPipe => {
self.closed = true;
Ok(())
},
result => result,
}
}
}
1 change: 1 addition & 0 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//! Keep this crate independent of frontend and backend types so formatting,
//! terminal color, and serialization helpers remain reusable at every compiler layer.

pub mod cli_output;
pub mod colorex;
pub mod const_int;
pub mod display_width;
Expand Down
Loading