Skip to main content

aoc_toolkit/client/
inputs.rs

1use std::fs;
2use std::io::{self, ErrorKind};
3use std::path::{Path, PathBuf};
4
5use super::error::ClientError;
6use super::http::AocHttpClient;
7use super::session;
8
9pub struct InputStore {
10    root: PathBuf,
11    http: Option<AocHttpClient>,
12}
13
14impl InputStore {
15    #[must_use]
16    pub fn new(root: impl Into<PathBuf>) -> Self {
17        Self {
18            root: root.into(),
19            http: None,
20        }
21    }
22
23    /// Returns cached puzzle input or downloads it from Advent of Code.
24    ///
25    /// # Errors
26    ///
27    /// Returns an error if the input cannot be read,
28    /// downloaded, or stored in the local cache.
29    pub fn get(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
30        let path = self.input_path(year, day);
31
32        if let Some(cached) = Self::read_cached(&path)? {
33            return Ok(cached);
34        }
35
36        let input = self.download(year, day)?;
37
38        Self::store(&path, &input)?;
39
40        Ok(input)
41    }
42
43    fn input_path(&self, year: usize, day: usize) -> PathBuf {
44        self.root.join(year.to_string()).join(format!("{day}.txt"))
45    }
46
47    fn read_cached(path: &Path) -> Result<Option<String>, ClientError> {
48        match fs::read_to_string(path) {
49            Ok(input) if input.trim().is_empty() => Ok(None),
50
51            Ok(input) => Ok(Some(input)),
52
53            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
54
55            Err(source) => Err(Self::io_error(path, source)),
56        }
57    }
58
59    fn download(&mut self, year: usize, day: usize) -> Result<String, ClientError> {
60        let token = session::get_session()?;
61
62        let http = match &self.http {
63            Some(http) => http,
64            None => self.http.insert(AocHttpClient::new()?),
65        };
66
67        http.fetch_input(year, day, &token)
68    }
69
70    fn store(path: &Path, input: &str) -> Result<(), ClientError> {
71        if let Some(parent) = path.parent() {
72            fs::create_dir_all(parent).map_err(|source| Self::io_error(parent, source))?;
73        }
74
75        fs::write(path, input).map_err(|source| Self::io_error(path, source))
76    }
77
78    fn io_error(path: &Path, source: io::Error) -> ClientError {
79        ClientError::Io {
80            path: path.to_path_buf(),
81            source,
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests;