aoc-toolkit 0.1.0-alpha.1

A toolkit for solving Advent of Code problems
Documentation
mod args;
mod commands;
mod error;
pub mod output;

use std::env;
use std::process::{ExitCode, ExitStatus};

use clap::{CommandFactory, Parser, error::ErrorKind};

use crate::application::run::{self, RunOptions};
use crate::project::Project;

use args::{Cli, Commands};
use error::CliError;

pub fn run() -> ExitCode {
    let cli = Cli::parse();

    match execute(cli.command) {
        Ok(status) => process_exit_code(status),
        Err(error) => {
            eprintln!("✗ {error}");
            ExitCode::FAILURE
        }
    }
}

fn execute(command: Commands) -> Result<ExitStatus, CliError> {
    match command {
        Commands::Run(args) => {
            let options = RunOptions::from(args);

            if let Err(error) = options.validate() {
                Cli::command()
                    .error(ErrorKind::InvalidValue, error.to_string())
                    .exit();
            }

            let cwd = env::current_dir().map_err(CliError::CurrentDirectory)?;

            let project = Project::discover(&cwd)?;

            Ok(run::execute(&project, &options)?)
        }
    }
}

fn process_exit_code(status: ExitStatus) -> ExitCode {
    status
        .code()
        .and_then(|code| u8::try_from(code).ok())
        .map_or(ExitCode::FAILURE, ExitCode::from)
}