Something went wrong. Try again.
My AOC solutions, rust ofc
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228//! Maintains the year by day stars table in the README.//!//! The only source of truth is Advent of Code itself: the calendar page of a year, fetched with//! the account's session cookie, marks every day with the number of stars the server has accepted.//! Nothing here looks at local solutions or tests.//!//! This module never talks to the network and never sees the session cookie. A separate step//! (see `.tangled/workflows/stars.yml`) saves each calendar page as `<dir>/<year>.html`.
use std::collections::BTreeMap;use std::fmt::Write as _;use std::{fs, path::Path};
use crate::template::{FIRST_YEAR, MAX_YEAR, last_day};
pub const MARKER: &str = "<!--- stars table --->";
/// Link AoC shows only for a signed in session. Without it the calendar shows no stars at all,/// so a page that lacks it must never be turned into a table of empty days.const SIGNED_IN_MARKER: &str = "/auth/logout";
/// Number of accepted stars per day (0, 1 or 2) of a single year.pub type YearStars = BTreeMap<u8, u8>;
/// Reads the stars of one year from the HTML of its calendar page.pub fn parse_calendar(html: &str, year: u16) -> Result<YearStars, String> { if !html.contains(SIGNED_IN_MARKER) { return Err(format!( "{year}: page does not look signed in (is the session cookie valid?)" )); }
let mut days = YearStars::new(); for (start, _) in html.match_indices("<a ") { let Some(len) = html[start..].find('>') else { continue; }; let tag = &html[start..start + len]; let Some(classes) = attribute(tag, "class") else { continue; }; let mut day = None; let mut stars = 0; for class in classes.split_whitespace() { if let Some(n) = class.strip_prefix("calendar-day") { day = n.parse::<u8>().ok(); } else if class == "calendar-verycomplete" { stars = 2; } else if class == "calendar-complete" { stars = 1; } } if let Some(day) = day { if day == 0 || day > last_day(year) { return Err(format!("{year}: unexpected day {day} on the calendar page")); } days.insert(day, stars); } }
if days.is_empty() { return Err(format!("{year}: no calendar days found on the page")); } Ok(days)}
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { let needle = format!(" {name}=\""); let start = tag.find(&needle)? + needle.len(); let end = tag[start..].find('"')?; Some(&tag[start..start + end])}
/// Builds the table, between two marker lines, with the newest year first.pub fn construct_table(years: &BTreeMap<u16, YearStars>) -> String { let mut out = String::new(); let _ = writeln!(out, "{MARKER}"); let _ = writeln!(out, "## Advent of Code stars"); let _ = writeln!(out); let _ = write!(out, "| Year |"); for day in 1..=25 { let _ = write!(out, " {day} |"); } let _ = writeln!(out, " Total |"); let _ = write!(out, "| :---: |"); for _ in 1..=25 { let _ = write!(out, " :---: |"); } let _ = writeln!(out, " :---: |");
for (year, days) in years.iter().rev() { let _ = write!(out, "| [{year}](https://adventofcode.com/{year}) |"); let mut total = 0u32; for day in 1..=25u8 { let cell = if day > last_day(*year) { "-" } else { match days.get(&day).copied().unwrap_or(0) { 2 => "⭐⭐", 1 => "⭐", _ => "", } }; total += u32::from(days.get(&day).copied().unwrap_or(0)); let _ = write!(out, " {cell} |"); } let _ = writeln!(out, " {total} |"); } let _ = write!(out, "{MARKER}"); out}
/// Replaces everything between (and including) the two marker lines. Text outside is untouched.pub fn replace_table(readme: &str, table: &str) -> Result<String, String> { let matches: Vec<usize> = readme.match_indices(MARKER).map(|m| m.0).collect(); let [start, end] = matches[..] else { return Err(format!( "expected exactly two `{MARKER}` lines in the README, found {}", matches.len() )); }; let end = end + MARKER.len(); Ok(format!("{}{}{}", &readme[..start], table, &readme[end..]))}
/// Reads `<dir>/<year>.html` for every year there is a file for.pub fn read_years(dir: &Path) -> Result<BTreeMap<u16, YearStars>, String> { let mut years = BTreeMap::new(); let entries = fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?; for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().into_owned(); let Some(year) = name .strip_suffix(".html") .and_then(|y| y.parse::<u16>().ok()) .filter(|y| (FIRST_YEAR..=MAX_YEAR).contains(y)) else { continue; }; let html = fs::read_to_string(entry.path()).map_err(|e| format!("{year}: {e}"))?; years.insert(year, parse_calendar(&html, year)?); } if years.is_empty() { return Err(format!("no <year>.html files in {}", dir.display())); } Ok(years)}
#[cfg(all(test, feature = "test_lib"))]mod tests { use super::*;
// Hand-written fixture shaped like an Advent of Code calendar page (checked against the markup // of a signed in page; the star classes are those of the page's own stylesheet). fn page(days: &[(u8, &str)], signed_in: bool) -> String { let mut html = String::from("<html><body><header>"); if signed_in { html.push_str("<a href=\"/2025/auth/logout\">[Log Out]</a>"); } else { html.push_str("<a href=\"/auth/login\">[Log In]</a>"); } html.push_str("</header><pre class=\"calendar\">"); for (day, state) in days { html.push_str(&format!( "<a aria-label=\"Day {day}\" href=\"/2025/day/{day}\" class=\"calendar-day{day}{state}\"><span class=\"calendar-day\">{day}</span></a>\n" )); } html.push_str("</pre></body></html>"); html }
#[test] fn reads_stars_per_day() { let html = page(&[(1, " calendar-verycomplete"), (2, " calendar-complete"), (3, "")], true); let days = parse_calendar(&html, 2025).unwrap(); assert_eq!(days.get(&1), Some(&2)); assert_eq!(days.get(&2), Some(&1)); assert_eq!(days.get(&3), Some(&0)); assert_eq!(days.len(), 3); }
#[test] fn rejects_signed_out_page() { let html = page(&[(1, " calendar-complete")], false); assert!(parse_calendar(&html, 2025).is_err()); }
#[test] fn rejects_page_without_calendar_and_out_of_range_days() { assert!(parse_calendar("<a href=\"/auth/logout\">x</a>", 2025).is_err()); assert!(parse_calendar(&page(&[(13, "")], true), 2025).is_err()); assert!(parse_calendar(&page(&[(13, "")], true), 2024).is_ok()); }
#[test] fn table_is_a_year_by_day_matrix_newest_first() { let mut years = BTreeMap::new(); years.insert(2024, YearStars::from([(1, 2), (2, 1)])); years.insert(2025, YearStars::from([(1, 2), (12, 1)])); let table = construct_table(&years); let lines: Vec<&str> = table.lines().collect(); assert_eq!(lines[0], MARKER); assert!(lines[5].starts_with("| [2025]")); assert!(lines[6].starts_with("| [2024]")); // 2025 has 12 days: day 13 onwards is "-", day 12 shows one star. assert!(lines[5].contains("| ⭐ | - |")); assert!(lines[5].ends_with("| 3 |")); assert!(lines[6].ends_with("| 3 |")); assert!(!lines[6].contains("| - |")); assert_eq!(lines.last().copied(), Some(MARKER)); }
#[test] fn replaces_only_between_markers() { let readme = format!("intro\n\n{MARKER}\nold\n{MARKER}\n\noutro\n"); let table = format!("{MARKER}\nnew\n{MARKER}"); let updated = replace_table(&readme, &table).unwrap(); assert_eq!(updated, format!("intro\n\n{MARKER}\nnew\n{MARKER}\n\noutro\n")); assert_eq!(replace_table(&updated, &table).unwrap(), updated); }
#[test] fn needs_exactly_two_markers() { assert!(replace_table("none", "t").is_err()); assert!(replace_table(&format!("{MARKER}\n"), "t").is_err()); assert!(replace_table(&format!("{MARKER}{MARKER}{MARKER}"), "t").is_err()); }}