aoc-toolkit 0.1.0-alpha.3

A toolkit for solving Advent of Code problems
Documentation
use thiserror::Error;

use super::calendar::{CalendarDate, edition_days};
use crate::{ClientError, InputSource, InputStore};

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

#[derive(Debug)]
pub struct FetchReport {
    pub year: usize,
    pub day: usize,
    pub outcome: Result<InputSource, ClientError>,
}

#[derive(Debug, Error)]
pub enum FetchError {
    #[error("Invalid Advent of Code year: {0}")]
    InvalidYear(usize),

    #[error("Invalid Advent of Code day: {0}")]
    InvalidDay(usize),

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

    #[error("No puzzles are unlocked for {0}")]
    NoUnlockedPuzzles(usize),

    #[error("Puzzle {year} / Day {day:02} is not unlocked")]
    PuzzleLocked { year: usize, day: usize },

    #[error(transparent)]
    Client(#[from] ClientError),
}

impl FetchOptions {
    fn resolve(&self, today: CalendarDate) -> Result<Vec<(usize, usize)>, FetchError> {
        if self.all && self.day.is_some() {
            return Err(FetchError::AllConflict);
        }

        let year = self.year.unwrap_or(today.year);

        if !(2015..=today.year).contains(&year) {
            return Err(FetchError::InvalidYear(year));
        }

        if let Some(day) = self.day
            && !(1..=edition_days(year)).contains(&day)
        {
            return Err(FetchError::InvalidDay(day));
        }

        let unlocked = today.unlocked_days(year);

        if unlocked == 0 {
            return Err(FetchError::NoUnlockedPuzzles(year));
        }

        if self.all {
            return Ok((1..=unlocked).map(|day| (year, day)).collect());
        }

        let day = self.day.unwrap_or(unlocked);

        if day > unlocked {
            return Err(FetchError::PuzzleLocked { year, day });
        }

        Ok(vec![(year, day)])
    }
}

/// Fetches the requested puzzle inputs.
///
/// Stops after the first acquisition error and returns
/// reports for all attempted puzzles.
///
/// # Errors
///
/// Returns an error if the requested puzzle selection
/// is invalid or the input store cannot be initialized.
pub fn execute(options: &FetchOptions) -> Result<Vec<FetchReport>, FetchError> {
    let days = options.resolve(CalendarDate::today())?;

    let mut store = InputStore::global()?;
    let mut reports = Vec::with_capacity(days.len());

    for (year, day) in days {
        let outcome = store.get_with_source(year, day).map(|(_, source)| source);

        let failed = outcome.is_err();

        reports.push(FetchReport { year, day, outcome });

        if failed {
            break;
        }
    }

    Ok(reports)
}

#[cfg(test)]
mod tests;