diff --git a/.cargo/config.toml b/.cargo/config.toml index 7df566c..51dd142 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -7,4 +7,5 @@ read = "run --quiet --release -- read" solve = "run --quiet --release -- solve" all = "run --quiet --release -- all" time = "run --quiet --release -- time" +stars = "run --quiet --release -- stars" diff --git a/.gitignore b/.gitignore index 216820d..302749e 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,7 @@ dhat-heap.json # Benchmarks data/timings.json + +# Saved AoC calendar pages + +data/stars/ diff --git a/README.md b/README.md index c466824..00274f3 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ + + + diff --git a/src/main.rs b/src/main.rs index 3422a09..61bf314 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use advent_of_code::template::commands::{all, download, read, scaffold, solve, time}; +use advent_of_code::template::commands::{all, download, read, scaffold, solve, stars, time}; use args::{AppArguments, parse}; #[cfg(feature = "today")] @@ -38,6 +38,9 @@ mod args { day: Option, store: bool, }, + Stars { + dir: String, + }, #[cfg(feature = "today")] Today, } @@ -87,6 +90,11 @@ mod args { download: !args.contains("--no-download"), overwrite: args.contains("--overwrite"), }, + Some("stars") => AppArguments::Stars { + dir: args + .opt_free_from_str()? + .unwrap_or_else(|| "data/stars".to_string()), + }, Some("solve") => AppArguments::Solve { day: parse_day(&mut args)?, release: args.contains("--release"), @@ -130,6 +138,7 @@ fn main() { } => time::handle(year, day, all, store), AppArguments::Download { day } => download::handle(day), AppArguments::Read { day } => read::handle(day), + AppArguments::Stars { dir } => stars::handle(std::path::Path::new(&dir)), AppArguments::Scaffold { day, download, diff --git a/src/template/commands/mod.rs b/src/template/commands/mod.rs index 36be280..8e5203d 100644 --- a/src/template/commands/mod.rs +++ b/src/template/commands/mod.rs @@ -3,4 +3,5 @@ pub mod download; pub mod read; pub mod scaffold; pub mod solve; +pub mod stars; pub mod time; diff --git a/src/template/commands/stars.rs b/src/template/commands/stars.rs new file mode 100644 index 0000000..5157acf --- /dev/null +++ b/src/template/commands/stars.rs @@ -0,0 +1,30 @@ +use std::{fs, path::Path, process}; + +use crate::template::stars::{construct_table, read_years, replace_table}; + +const README: &str = "README.md"; + +fn update(dir: &Path) -> Result { + let years = read_years(dir)?; + let readme = fs::read_to_string(README).map_err(|e| format!("cannot read {README}: {e}"))?; + let updated = replace_table(&readme, &construct_table(&years))?; + if updated == readme { + return Ok("stars table already up to date.".to_string()); + } + fs::write(README, updated).map_err(|e| format!("cannot write {README}: {e}"))?; + Ok(format!("updated the stars table for {} year(s).", years.len())) +} + +/// Rebuilds the stars table in the README from the calendar pages saved in `dir`. +/// +/// Fails without touching the README when any page is missing, signed out or unreadable, +/// so a failed fetch can never show up as days without stars. +pub fn handle(dir: &Path) { + match update(dir) { + Ok(message) => println!("{message}"), + Err(e) => { + eprintln!("stars: {e}"); + process::exit(1); + } + } +} diff --git a/src/template/mod.rs b/src/template/mod.rs index ca64cc7..b0fb73c 100644 --- a/src/template/mod.rs +++ b/src/template/mod.rs @@ -9,6 +9,7 @@ pub use day::*; mod day; mod readme_benchmarks; mod run_multi; +pub mod stars; mod timings; pub const ANSI_ITALIC: &str = "\x1b[3m"; diff --git a/src/template/stars.rs b/src/template/stars.rs new file mode 100644 index 0000000..f90c260 --- /dev/null +++ b/src/template/stars.rs @@ -0,0 +1,227 @@ +//! 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()); + } +}