wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Shared stdio plumbing for the CLI commands.

use std::io::{self, BufRead, BufWriter, IsTerminal, Write};

const BUF_SIZE: usize = 32 * 1024;

/// Buffered stdout that swallows broken-pipe errors, so piping into `head`
/// exits cleanly instead of erroring.
pub struct Output {
    w: BufWriter<io::Stdout>,
}

impl Output {
    pub fn new() -> Self {
        Self {
            w: BufWriter::with_capacity(BUF_SIZE, io::stdout()),
        }
    }

    /// Flushes and returns the success exit code.
    pub fn finish(&mut self) -> i32 {
        let _ = self.w.flush();
        0
    }

    /// Flushes pending output, reports `msg` on stderr and returns the failure
    /// exit code. Output written before the error is preserved, matching the
    /// original's behavior.
    pub fn fail(&mut self, msg: &str) -> i32 {
        let _ = self.w.flush();
        eprintln!("{msg}");
        1
    }
}

impl Write for Output {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.w.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.w.flush()
    }
}

/// Reports whether stdin is piped rather than attached to a terminal.
pub fn stdin_is_pipe() -> bool {
    !io::stdin().is_terminal()
}

/// Streams stdin line by line, skipping blank lines, reusing one buffer.
/// Stops early when `f` returns `false`.
pub fn write_lines<F>(out: &mut Output, mut f: F)
where
    F: FnMut(&str, &mut Output) -> bool,
{
    let stdin = io::stdin();
    let mut reader = stdin.lock();
    let mut line = String::with_capacity(256);

    loop {
        line.clear();
        match reader.read_line(&mut line) {
            Ok(0) => break,
            Ok(_) => {}
            Err(e) => {
                let _ = out.flush();
                eprintln!("reading stdin: {e}");
                return;
            }
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if !f(trimmed, out) {
            return;
        }
    }
}