aoc-toolkit 0.1.0-alpha.2

A toolkit for solving Advent of Code problems
Documentation
use crate::adapters;
use crate::project::{Language, Project};
use std::process::ExitStatus;

#[derive(Debug, Default, Clone, Copy)]
pub struct RunOptions {
    pub year: Option<usize>,
    pub day: Option<u8>,
    pub part: Option<u8>,
    pub all: bool,
}

/// Executes a project's configured runner.
///
/// # Errors
///
/// Returns an error if the options are invalid
/// or the runner process cannot be executed.
pub fn execute(project: &Project, options: &RunOptions) -> Result<ExitStatus, RunError> {
    options.validate()?;

    match project.config.project.language {
        Language::Rust => Ok(adapters::rust::run(project, options)?),
    }
}

#[derive(Debug, thiserror::Error)]
pub enum RunOptionsError {
    #[error("Day must be between 1 and 25")]
    InvalidDay,

    #[error("Part must be either 1 or 2")]
    InvalidPart,

    #[error("--all cannot be combined with --day or --part")]
    AllConflict,

    #[error("--day is required when using --year with --part")]
    MissingDay,
}

impl RunOptions {
    /// # Errors
    ///
    /// Returns an error if the options are invalid.
    pub fn validate(&self) -> Result<(), RunOptionsError> {
        if self.day.is_some_and(|day| !(1..=25).contains(&day)) {
            return Err(RunOptionsError::InvalidDay);
        }

        if self.part.is_some_and(|part| !(1..=2).contains(&part)) {
            return Err(RunOptionsError::InvalidPart);
        }

        if self.all && (self.day.is_some() || self.part.is_some()) {
            return Err(RunOptionsError::AllConflict);
        }

        if self.year.is_some() && self.part.is_some() && self.day.is_none() {
            return Err(RunOptionsError::MissingDay);
        }

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum RunError {
    #[error(transparent)]
    InvalidOptions(#[from] RunOptionsError),

    #[error("Failed to execute runner: {0}")]
    Process(#[from] std::io::Error),
}