summaryrefslogtreecommitdiffstats
path: root/scripts/aoc_inputs.rs
blob: 322ec72a681a5952ba64c55fae35fa1deefc0026 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env -S cargo +nightly -Zscript
```cargo
[dependencies]
anyhow = "1.0.75"
reqwest = { version = "0.11.22", features = ["blocking"] }
```

use anyhow::Context;
use reqwest::{
    blocking::Client,
    header::{HeaderMap, HeaderValue, CONTENT_TYPE, COOKIE, USER_AGENT},
    redirect::Policy,
};

const YEAR: u32 = 2023;
const PKG_VER: &str = env!("CARGO_PKG_VERSION");
const PKG_NAME: &str = env!("CARGO_PKG_NAME");

fn main() -> anyhow::Result<()> {
    let cookie = std::fs::read_to_string("./target/.aoc_session")?;

    let mut headers = HeaderMap::new();
    headers.insert(CONTENT_TYPE, HeaderValue::from_str("text/plain")?);
    headers.insert(COOKIE, HeaderValue::from_str(&format!("session={}", cookie.trim()))?);
    headers.insert(USER_AGENT, HeaderValue::from_str(&format!("{PKG_NAME} {PKG_VER}"))?);

    let http_client = Client::builder()
        .default_headers(headers)
        .redirect(Policy::none())
        .build()?;

    let mods = get_days("./src").context("No src directory found")?;
    let inputs = get_days("./input").context("No input directory found")?;

    for day in mods {
        if !inputs.contains(&day) {
            let url = format!("https://adventofcode.com/{}/day/{}/input", YEAR, day);
            let input = http_client
                .get(url)
                .send()
                .and_then(|response| response.error_for_status())
                .and_then(|response| response.text())?;

            std::fs::write(format!("./input/day_{day:02}.txt"), input)?;
        }
    }

    Ok(())
}

fn get_days(dir: &str) -> Option<Vec<u8>> {
    let mut mods = vec![];

    for d in std::fs::read_dir(dir).ok()?.flatten() {
        let path = d.path();

        if let Some(n) = path
            .file_stem()
            .and_then(|s| s.to_str())
            .and_then(|s| s.strip_prefix("day_"))
            .and_then(|s| s.parse().ok())
        {
            mods.push(n);
        };
    }

    Some(mods)
}