aoc_input_lib/
lib.rs

1mod error;
2use std::{io::Write, path::PathBuf};
3
4use error::Error;
5
6type AocResult<T> = Result<T, Error>;
7
8pub fn get_puzzle_input(year: u32, day: u32, session: Option<String>) -> AocResult<String> {
9    match from_cache(year, day) {
10        Some(input) => Ok(input),
11        None => session
12            .ok_or(Error::SessionRequired)
13            .and_then(|session| from_web(year, day, session, true)),
14    }
15}
16
17pub fn from_web(year: u32, day: u32, session: String, should_cache: bool) -> AocResult<String> {
18    let url = format!("https://adventofcode.com/{}/day/{}/input", year, day);
19
20    let cookie = format!("session={}", session);
21
22    let puzzle_input = reqwest::blocking::Client::new()
23        .get(url)
24        .header("Cookie", cookie)
25        .send()?
26        .text()?;
27
28    if should_cache {
29        set_cache(year, day, puzzle_input.clone());
30    }
31    Ok(puzzle_input)
32}
33
34// directory structure:
35// ~/.aoc_puzzles/{year}/day-{day}.txt
36fn get_path(year: u32, day: u32) -> Option<PathBuf> {
37    home::home_dir().map(|mut h| {
38        h.push(format!(".aoc_puzzles/{year}/day-{day}.txt"));
39        h
40    })
41}
42
43/// Try to get the puzzle from the cache.
44fn from_cache(year: u32, day: u32) -> Option<String> {
45    get_path(year, day).and_then(|p| std::fs::read_to_string(p).ok())
46}
47
48/// Try to cache the puzzle input under the home directory.
49/// Discard any errors if caching fails
50fn set_cache(year: u32, day: u32, puzzle_input: String) {
51    if let Some(p) = get_path(year, day) {
52        // should not panic
53        let prefix = p.parent().unwrap();
54
55        _ = std::fs::create_dir_all(prefix);
56        _ = std::fs::File::create(p).and_then(|mut f| f.write_all(puzzle_input.as_bytes()));
57    };
58}