advent-of-code/build.rs

39 lines
1.3 KiB
Rust

use reqwest::{blocking::Client, cookie::Jar};
use std::{collections::HashMap, env, fs, path::PathBuf, sync::Arc};
const BASE_URL: &str = "https://adventofcode.com";
const YEAR: &str = "2022";
fn main() {
// get env and dotenv into hashmap
let file = fs::read_to_string(".env").unwrap_or(String::new());
let env = file
.lines()
.filter_map(|line| line.split_once('='))
.map(|(key, value)| (key.to_string(), value.to_string()))
.chain(env::vars())
.collect::<HashMap<_, _>>();
// create session cookie
let session = env
.get("SESSION")
.expect("SESSION environment variable not set, retrieve it from https://adventofcode.com");
let cookie = format!("session={session}");
// setup client
let jar = Arc::new(Jar::default());
jar.add_cookie_str(&cookie, &BASE_URL.parse().unwrap());
let client = Client::builder().cookie_provider(jar).build().unwrap();
// download until day fails
for day in 1..=25 {
let path = PathBuf::from(format!("input/day{day}.txt"));
if path.try_exists().is_err() {
let url = format!("{BASE_URL}/{YEAR}/day/{day}/input");
let Ok(res) = client.get(url).send() else {
break
};
fs::write(path, res.text().unwrap()).unwrap();
}
}
}