//! 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 `/.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 = ""; /// 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; /// Reads the stars of one year from the HTML of its calendar page. pub fn parse_calendar(html: &str, year: u16) -> Result { 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("') 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::().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) -> 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 { let matches: Vec = 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 `/.html` for every year there is a file for. pub fn read_years(dir: &Path) -> Result, 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::().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 .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("
"); if signed_in { html.push_str("[Log Out]"); } else { html.push_str("[Log In]"); } html.push_str("
");
        for (day, state) in days {
            html.push_str(&format!(
                "{day}\n"
            ));
        }
        html.push_str("
"); 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("x", 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()); } }