fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! The four in a row program.

#![forbid(unsafe_code)]
#![warn(clippy::pedantic)]

use fours::app::App;
use fours::app::run;
use fours::cli;
use fours::cli::Command;
use miette::IntoDiagnostic;
use miette::Result;
use std::io::ErrorKind;
use std::io::Write;

fn main() -> Result<()> {
    match cli::parse(std::env::args().skip(1))? {
        Command::Help => print(cli::HELP),
        Command::Version => print(&format!("{} {}", cli::NAME, cli::VERSION)),
        Command::Play(options) => play(options),
    }
}

fn play(options: cli::Options) -> Result<()> {
    let mut app = options.seed.map_or_else(
        || App::new(options.dimensions),
        |seed| App::seeded(options.dimensions, seed),
    );
    app.set_difficulty(options.difficulty);

    run(app)?;
    Ok(())
}

/// Write a line to standard output.
///
/// A closed pipe is how `--help | head` ends, so it is left alone rather than reported.
fn print(text: &str) -> Result<()> {
    let mut output = std::io::stdout().lock();
    let written = writeln!(output, "{text}").and_then(|()| output.flush());

    match written {
        Err(error) if error.kind() == ErrorKind::BrokenPipe => Ok(()),
        other => other.into_diagnostic(),
    }
}