texplain 0.1.0

Strip LaTeX to plain text with 1:1 line mapping, so prose linters report the source line.
Documentation
//! Binary crate for the texplain CLI: strip LaTeX to plain text with 1:1 line mapping.

use std::ffi::OsString;
use std::fmt::Display;
use std::io::Write as _;
use std::path::Path;
use std::process::ExitCode;

/// How the CLI was invoked, once the arguments make sense.
///
/// Parsing into a value keeps [`main`] free of argument shape checks, and makes
/// the "exactly one path" rule a thing the type system carries rather than a
/// length comparison repeated at each use.
#[derive(Debug)]
struct Invocation {
    /// The `.tex` file to strip.
    path: OsString,
}

/// One line of usage text, shown when the arguments do not parse.
const USAGE: &str = "Usage: texplain <file.tex>";

impl Invocation {
    /// Parse `args` (already excluding argv[0]), or `None` if the shape is wrong.
    ///
    /// Arguments are [`OsString`], not [`String`]: a path need not be valid
    /// UTF-8, and rejecting one that is not would be a bug rather than a
    /// diagnosis.
    fn parse(mut args: impl Iterator<Item = OsString>) -> Option<Self> {
        match (args.next(), args.next()) {
            (Some(path), None) => Some(Self { path }),
            _ => None,
        }
    }
}

/// Write one line to stderr, ignoring a broken pipe.
///
/// The `print*`/`eprint*` macros panic when writing fails, which is the wrong
/// behaviour for a filter in a shell pipeline.
fn warn(msg: &dyn Display) {
    let mut stderr = std::io::stderr().lock();
    drop(writeln!(stderr, "{msg}"));
}

/// Strip `path` and write the result to stdout.
///
/// # Errors
///
/// Returns the message to print if the file cannot be read or stdout cannot be
/// written.
fn run(path: &Path) -> Result<(), String> {
    let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let output = texplain::strip_reader(file).map_err(|e| format!("{}: {e}", path.display()))?;

    // `output` is already newline-terminated, so `write!`, not `writeln!`.
    let mut stdout = std::io::stdout().lock();
    write!(stdout, "{output}").map_err(|e| format!("stdout: {e}"))?;
    stdout.flush().map_err(|e| format!("stdout: {e}"))
}

/// Entry point for the texplain CLI.
///
/// Usage: `texplain <file.tex>`
///
/// Reads a LaTeX file and writes the stripped plain text to stdout, preserving
/// line numbers (line N of output = line N of input).
fn main() -> ExitCode {
    let Some(invocation) = Invocation::parse(std::env::args_os().skip(1)) else {
        warn(&USAGE);
        return ExitCode::FAILURE;
    };

    match run(Path::new(&invocation.path)) {
        Ok(()) => ExitCode::SUCCESS,
        Err(msg) => {
            warn(&format_args!("texplain: {msg}"));
            ExitCode::FAILURE
        }
    }
}