From e0a3f745ad09dbf8239f284f2681704e278e6c0f Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Fri, 15 Dec 2023 17:17:00 -0600 Subject: build: add aoc_inputs.rs script to get inputs --- scripts/aoc_inputs.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100755 scripts/aoc_inputs.rs diff --git a/scripts/aoc_inputs.rs b/scripts/aoc_inputs.rs new file mode 100755 index 0000000..322ec72 --- /dev/null +++ b/scripts/aoc_inputs.rs @@ -0,0 +1,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> { + 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) +} -- cgit v1.2.3-70-g09d2