diff --git a/src/bin/main.rs b/src/bin/main.rs index 88281d296be..a3adc06b0f6 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -43,7 +43,13 @@ fn main() { } }; // Make sure standard output is flushed before we exit. - std::io::stdout().flush().unwrap(); + // Silently ignore broken pipe errors, but any other errors are unexpected. + match std::io::stdout().flush() { + Err(e) if e.kind() != io::ErrorKind::BrokenPipe => { + panic!("flushing stdout failed: unexpected error: {:?}", e) + } + _ => {} + }; // Exit with given exit code. // diff --git a/src/rustfmt_diff.rs b/src/rustfmt_diff.rs index c9883452185..0c5a4bb505c 100644 --- a/src/rustfmt_diff.rs +++ b/src/rustfmt_diff.rs @@ -164,11 +164,29 @@ impl OutputWriter { match &mut self.terminal { Some(ref mut t) => { if let Some(color) = color { - t.fg(color).unwrap(); + match t.fg(color) { + // If writing to a broken pipe, there is no reason to continue. + // Any other error is unexpected, however. + Err(term::Error::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => { + std::process::exit(1); + }, + Err(e) => panic!("write failed: unexpected error: {:?}", e), + _ => {}, + }; + } + match writeln!(t, "{msg}") { + Err(e) if e.kind() == io::ErrorKind::BrokenPipe => std::process::exit(1), + Err(e) => panic!("write failed: unexpected error: {:?}", e), + _ => {} } - writeln!(t, "{msg}").unwrap(); if color.is_some() { - t.reset().unwrap(); + match t.reset() { + Err(term::Error::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => { + std::process::exit(1); + }, + Err(e) => panic!("write failed: unexpected error: {:?}", e), + _ => {}, + }; } } None => println!("{msg}"),