aoc-toolkit 0.1.0-alpha.2

A toolkit for solving Advent of Code problems
Documentation
use std::fs;
use std::io::{self, ErrorKind};
use std::path::{Path, PathBuf};

use super::error::ClientError;
use super::http::AocHttpClient;
use super::session;

pub struct InputStore {
    root: PathBuf,
    http: Option<AocHttpClient>,
}

impl InputStore {
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            http: None,
        }
    }

    /// Returns cached puzzle input or downloads it from Advent of Code.
    ///
    /// # Errors
    ///
    /// Returns an error if the input cannot be read,
    /// downloaded, or stored in the local cache.
    pub fn get(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
        let path = self.input_path(year, day);

        if let Some(cached) = Self::read_cached(&path)? {
            return Ok(cached);
        }

        let input = self.download(year, day)?;

        Self::store(&path, &input)?;

        Ok(input)
    }

    fn input_path(&self, year: usize, day: usize) -> PathBuf {
        self.root.join(year.to_string()).join(format!("{day}.txt"))
    }

    fn read_cached(path: &Path) -> Result<Option<String>, ClientError> {
        match fs::read_to_string(path) {
            Ok(input) if input.trim().is_empty() => Ok(None),

            Ok(input) => Ok(Some(input)),

            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),

            Err(source) => Err(Self::io_error(path, source)),
        }
    }

    fn download(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
        let token = session::get_session()?;

        let http = match &self.http {
            Some(http) => http,
            None => self.http.insert(AocHttpClient::new()?),
        };

        http.fetch_input(year, day, &token)
    }

    fn store(path: &Path, input: &str) -> Result<(), ClientError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|source| Self::io_error(parent, source))?;
        }

        fs::write(path, input).map_err(|source| Self::io_error(path, source))
    }

    fn io_error(path: &Path, source: io::Error) -> ClientError {
        ClientError::Io {
            path: path.to_path_buf(),
            source,
        }
    }
}

#[cfg(test)]
mod tests;