diff -r 0f2268783c11 -r 65839176cea9 rust/rhg/src/ui.rs --- a/rust/rhg/src/ui.rs Thu Jan 30 09:23:16 2025 +0100 +++ b/rust/rhg/src/ui.rs Fri Jan 31 15:04:13 2025 +0000 @@ -12,7 +12,9 @@ use hg::utils::files::get_bytes_from_path; use std::borrow::Cow; use std::io; +use std::io::BufWriter; use std::io::IsTerminal; +use std::io::StdoutLock; use std::io::{ErrorKind, Write}; pub struct Ui { @@ -56,8 +58,11 @@ /// Returns a buffered handle on stdout for faster batch printing /// operations. - pub fn stdout_buffer(&self) -> StdoutBuffer { - StdoutBuffer::new(self.stdout.lock()) + pub fn stdout_buffer(&self) -> StdoutBuffer<'_, BufWriter> { + StdoutBuffer { + stdout: BufWriter::new(self.stdout.lock()), + colors: &self.colors, + } } /// Write bytes to stdout @@ -77,13 +82,21 @@ stderr.flush().or_else(handle_stderr_error) } +} +/// A buffered stdout writer for faster batch printing operations. +pub struct StdoutBuffer<'a, W> { + colors: &'a Option, + stdout: W, +} + +impl<'a, W: Write> StdoutBuffer<'a, W> { /// Write bytes to stdout with the given label /// /// Like the optional `label` parameter in `mercurial/ui.py`, /// this label influences the color used for this output. pub fn write_stdout_labelled( - &self, + &mut self, bytes: &[u8], label: &str, ) -> Result<(), UiError> { @@ -96,15 +109,15 @@ } } } - self.write_stdout(bytes) + self.write_all(bytes) } fn write_stdout_with_effects( - &self, + &mut self, bytes: &[u8], effects: &[Effect], ) -> io::Result<()> { - let stdout = &mut self.stdout.lock(); + let stdout = &mut self.stdout; let mut write_line = |line: &[u8], first: bool| { // `line` does not include the newline delimiter if !first { @@ -130,7 +143,17 @@ write_line(line, false)? } } - stdout.flush() + Ok(()) + } + + /// Write bytes to stdout buffer + pub fn write_all(&mut self, bytes: &[u8]) -> Result<(), UiError> { + self.stdout.write_all(bytes).or_else(handle_stdout_error) + } + + /// Flush bytes to stdout + pub fn flush(&mut self) -> Result<(), UiError> { + self.stdout.flush().or_else(handle_stdout_error) } } @@ -144,28 +167,6 @@ } } -/// A buffered stdout writer for faster batch printing operations. -pub struct StdoutBuffer { - buf: io::BufWriter, -} - -impl StdoutBuffer { - pub fn new(writer: W) -> Self { - let buf = io::BufWriter::new(writer); - Self { buf } - } - - /// Write bytes to stdout buffer - pub fn write_all(&mut self, bytes: &[u8]) -> Result<(), UiError> { - self.buf.write_all(bytes).or_else(handle_stdout_error) - } - - /// Flush bytes to stdout - pub fn flush(&mut self) -> Result<(), UiError> { - self.buf.flush().or_else(handle_stdout_error) - } -} - /// Sometimes writing to stdout is not possible, try writing to stderr to /// signal that failure, otherwise just bail. fn handle_stdout_error(error: io::Error) -> Result<(), UiError> {