Skip to main content

schema_sql_generator/common/
print_writer.rs

1use std::io::{BufWriter, ErrorKind, Write};
2
3pub struct PrintWriter {
4    writer: BufWriter<Box<dyn Write>>,
5    auto_flush: bool,
6    exit_quietly_on_broken_pipe: bool,
7}
8
9fn is_broken_pipe(e: &std::io::Error) -> bool {
10    e.kind() == ErrorKind::BrokenPipe
11}
12
13impl PrintWriter {
14    pub fn new(writer: Box<dyn Write>) -> Self {
15        Self {
16            writer: BufWriter::new(writer),
17            auto_flush: false,
18            exit_quietly_on_broken_pipe: false,
19        }
20    }
21
22    pub fn new_auto_flush(writer: Box<dyn Write>) -> Self {
23        Self {
24            writer: BufWriter::new(writer),
25            auto_flush: true,
26            exit_quietly_on_broken_pipe: false,
27        }
28    }
29
30    /// Opts into treating a broken pipe as "exit the process quietly" instead of
31    /// panicking. Only appropriate for a writer that's actually connected to something
32    /// pipe-like (e.g. a CLI's stdout, which may be piped into `head`/`less` and closed
33    /// early - a routine condition every other Unix-style text-producing tool exits from
34    /// silently, and Rust ignoring `SIGPIPE` by default turns into an `io::Error` here
35    /// instead of the process dying outright). This is opt-in and off by default because
36    /// `PrintWriter` is also used to write to plain files (which can't produce a broken
37    /// pipe in practice) and in-process buffers - an embedder writing to one of those
38    /// should never have the *whole process* exited out from under it by a shared
39    /// low-level writer type on some other, unexpected I/O condition.
40    pub fn exit_quietly_on_broken_pipe(mut self, value: bool) -> Self {
41        self.exit_quietly_on_broken_pipe = value;
42        self
43    }
44
45    /// Handles a write/flush failure, following the `exit_quietly_on_broken_pipe`
46    /// policy for a broken pipe specifically. Any other I/O error (disk full,
47    /// permission denied, ...) is always unexpected here - there's no meaningful
48    /// recovery for a generator not built around `Result`-returning writes, so it
49    /// always fails loudly via panic.
50    fn handle_write_error(&self, context: &str, e: std::io::Error) -> ! {
51        if self.exit_quietly_on_broken_pipe && is_broken_pipe(&e) {
52            std::process::exit(0);
53        }
54        panic!("Error while {}: {}", context, e)
55    }
56
57    pub fn print(&mut self, text: &str) {
58        if let Err(e) = write!(self.writer, "{}", text) {
59            self.handle_write_error("writing", e);
60        }
61    }
62
63    pub fn println(&mut self, text: &str) {
64        if let Err(e) = writeln!(self.writer, "{}", text) {
65            self.handle_write_error("writing", e);
66        }
67        if self.auto_flush {
68            self.flush();
69        }
70    }
71
72    pub fn printf(&mut self, args: std::fmt::Arguments) {
73        if let Err(e) = write!(self.writer, "{}", args) {
74            self.handle_write_error("writing", e);
75        }
76        if self.auto_flush {
77            self.flush();
78        }
79    }
80
81    pub fn newline(&mut self) {
82        if let Err(e) = writeln!(self.writer) {
83            self.handle_write_error("writing", e);
84        }
85        if self.auto_flush {
86            self.flush();
87        }
88    }
89
90    pub fn flush(&mut self) {
91        if let Err(e) = self.writer.flush() {
92            self.handle_write_error("flushing", e);
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use std::io;
101
102    /// A `Write` impl that always fails with a configurable error kind, used to drive
103    /// `PrintWriter` down its error-handling paths without needing a real closed pipe.
104    struct FailingWriter(ErrorKind);
105
106    impl Write for FailingWriter {
107        fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
108            Err(io::Error::from(self.0))
109        }
110
111        fn flush(&mut self) -> io::Result<()> {
112            Err(io::Error::from(self.0))
113        }
114    }
115
116    #[test]
117    fn is_broken_pipe_classifies_error_kinds_correctly() {
118        assert!(is_broken_pipe(&io::Error::from(ErrorKind::BrokenPipe)));
119        assert!(!is_broken_pipe(&io::Error::from(ErrorKind::PermissionDenied)));
120        assert!(!is_broken_pipe(&io::Error::from(ErrorKind::OutOfMemory)));
121    }
122
123    #[test]
124    #[should_panic(expected = "Error while flushing")]
125    fn flush_panics_on_a_non_broken_pipe_error() {
126        // Unexpected I/O errors (not a broken pipe) must still fail loudly, since
127        // nothing downstream is built to recover from a partially-written script.
128        // (`print` alone doesn't reach the underlying `Write` here - `BufWriter`
129        // buffers a short string rather than flushing it immediately - so this drives
130        // the error path via an explicit `flush()`, which always reaches it.)
131        let mut writer = PrintWriter::new(Box::new(FailingWriter(ErrorKind::PermissionDenied)));
132        writer.print("hello");
133        writer.flush();
134    }
135
136    #[test]
137    #[should_panic(expected = "Error while flushing")]
138    fn flush_panics_on_a_broken_pipe_by_default() {
139        // `PrintWriter` is also used to write to plain files (schema-installer's temp
140        // file, the CLI's output file) and in-process buffers - neither can produce a
141        // broken pipe in practice, but if one somehow did, a shared low-level writer
142        // type silently exiting the whole process out from under an arbitrary embedder
143        // would be far more surprising than a panic. Quietly exiting on a broken pipe
144        // is opt-in (`exit_quietly_on_broken_pipe(true)`) for exactly this reason - the
145        // default must still panic.
146        let mut writer = PrintWriter::new(Box::new(FailingWriter(ErrorKind::BrokenPipe)));
147        writer.print("hello");
148        writer.flush();
149    }
150
151    // Note: the broken-pipe-exits-quietly path itself calls `std::process::exit(0)`,
152    // which can't be exercised in-process without terminating the test runner -
153    // `is_broken_pipe`'s classification (tested above) is what determines whether that
154    // path is taken once a caller has opted in via `exit_quietly_on_broken_pipe(true)`.
155}