use super::Outcome;
use std::io::{ErrorKind, Write};
pub(super) fn shown(text: &str, verdict: Outcome) -> Outcome {
shown_to(&mut std::io::stdout().lock(), text, verdict)
}
fn shown_to(out: &mut impl Write, text: &str, verdict: Outcome) -> Outcome {
match written(out, text) {
Ok(()) => verdict,
Err(message) => {
eprintln!("ctrm: {message}");
Outcome::Usage
}
}
}
fn written(out: &mut impl Write, text: &str) -> Result<(), String> {
match writeln!(out, "{text}").and_then(|()| out.flush()) {
Err(e) if e.kind() != ErrorKind::BrokenPipe => {
Err(format!("stdout: {e}"))
}
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::{Outcome, shown_to, written};
use std::io::{Error, ErrorKind, Write};
struct Failing(ErrorKind);
impl Write for Failing {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(Error::from(self.0))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn a_report_is_written_with_its_newline() {
let mut out = Vec::new();
assert!(written(&mut out, "a.md:1:1 U+2014 ascii").is_ok());
assert_eq!(out, b"a.md:1:1 U+2014 ascii\n");
}
#[test]
fn a_reader_that_stopped_listening_is_not_an_error() {
let mut out = Failing(ErrorKind::BrokenPipe);
assert!(written(&mut out, "x").is_ok());
}
#[test]
fn any_other_failed_write_is_named() {
let mut out = Failing(ErrorKind::StorageFull);
let said = written(&mut out, "x").err().unwrap_or_default();
assert!(said.starts_with("stdout: "), "{said}");
}
#[test]
fn a_closed_pipe_keeps_the_verdict() {
let mut out = Failing(ErrorKind::BrokenPipe);
let kept = shown_to(&mut out, "x", Outcome::Violation);
assert_eq!(kept, Outcome::Violation);
}
#[test]
fn lost_output_is_a_usage_exit() {
let mut out = Failing(ErrorKind::StorageFull);
assert_eq!(shown_to(&mut out, "x", Outcome::Ok), Outcome::Usage);
}
}