aoc-toolkit 0.1.0-alpha.2

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 crate::adapters::browser::{is_native_origin, run_native_host};
use args::{Cli, Commands};
use error::CliError;

pub fn run() -> ExitCode {
    if env::args_os()
        .nth(1)
        .and_then(|arg| arg.into_string().ok())
        .is_some_and(|arg| is_native_origin(&arg))
    {
        return run_native_host();
    }

    let cli = Cli::parse();

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

fn execute(command: Commands) -> Result<ExitCode, CliError> {
    match command {
        Commands::Init(args) => {
            commands::init::execute(args)?;

            Ok(ExitCode::SUCCESS)
        }

        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)?;

            let status = run::execute(&project, &options)?;

            Ok(process_exit_code(status))
        }
        Commands::New(args) => {
            commands::new::execute(&args)?;

            Ok(ExitCode::SUCCESS)
        }
        Commands::Auth(args) => {
            commands::auth::execute(&args)?;

            Ok(ExitCode::SUCCESS)
        }
        Commands::Browser(args) => {
            commands::browser::execute(&args)?;

            Ok(ExitCode::SUCCESS)
        }
        Commands::Setup(args) => {
            commands::setup::execute(&args)?;

            Ok(ExitCode::SUCCESS)
        }
    }
}

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