aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
mod calendar_html;
mod edition;
mod readme;
mod registry;
mod report;
mod stars;
mod store;
mod sync;

pub use super::calendar::DayAvailability;
pub use calendar_html::CalendarHtmlError;
pub use edition::{ProgressDay, SolverRegistration, current_edition_year, edition_progress};
pub use readme::{ReadmeSectionError, ReadmeWriteError, replace_progress_section, update_readme};
pub use registry::{RegistryError, registered_days};
pub use report::{EditionProgress, ProgressDayReport};
pub use stars::{StarSnapshot, StarStore, StarStoreError, VerifiedStar};
pub use store::{LocalProgressStore, LocalProgressStoreError};
pub use sync::{StarSyncError, StarSyncOutcome, cached_stars, sync_stars};

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::run::{PartStatus, ProgressReport};

const LOCAL_PROGRESS_SCHEMA_VERSION: u32 = 1;

/// Latest local execution outcomes for one project and language.
#[derive(Debug, Default)]
pub struct LocalProgress {
    parts: BTreeMap<(usize, usize, u8), PartStatus>,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct LocalProgressFile {
    schema_version: u32,
    parts: Vec<StoredPart>,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct StoredPart {
    year: usize,
    day: usize,
    part: u8,
    status: PartStatus,
}

#[derive(Debug, thiserror::Error)]
pub enum LocalProgressError {
    #[error("Invalid local progress JSON: {0}")]
    Json(#[from] serde_json::Error),

    #[error("Unsupported local progress schema version: {0}")]
    UnsupportedVersion(u32),

    #[error("Invalid local progress entry for {year} / Day {day:02} / Part {part}")]
    InvalidPart { year: usize, day: usize, part: u8 },

    #[error("Duplicate local progress entry for {year} / Day {day:02} / Part {part}")]
    DuplicatePart { year: usize, day: usize, part: u8 },
}

impl LocalProgress {
    /// Records only the parts that ran in this execution.
    pub fn record(&mut self, report: &ProgressReport) {
        for day in &report.days {
            for part in &day.parts {
                self.parts
                    .insert((day.year, day.day, part.part), part.status);
            }
        }
    }

    /// Returns the last recorded outcome for a part, if it has run.
    #[must_use]
    pub fn part_status(&self, year: usize, day: usize, part: u8) -> Option<PartStatus> {
        self.parts.get(&(year, day, part)).copied()
    }

    /// Encodes the local progress snapshot.
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot cannot be serialized.
    pub fn to_json(&self) -> Result<Vec<u8>, LocalProgressError> {
        let parts = self
            .parts
            .iter()
            .map(|(&(year, day, part), &status)| StoredPart {
                year,
                day,
                part,
                status,
            })
            .collect();

        Ok(serde_json::to_vec_pretty(&LocalProgressFile {
            schema_version: LOCAL_PROGRESS_SCHEMA_VERSION,
            parts,
        })?)
    }

    /// Decodes a previously stored local progress snapshot.
    ///
    /// # Errors
    ///
    /// Returns an error if the schema version is unsupported or the data is invalid.
    pub fn from_json(bytes: &[u8]) -> Result<Self, LocalProgressError> {
        #[derive(Deserialize)]
        struct Header {
            schema_version: u32,
        }

        let header: Header = serde_json::from_slice(bytes)?;
        if header.schema_version != LOCAL_PROGRESS_SCHEMA_VERSION {
            return Err(LocalProgressError::UnsupportedVersion(
                header.schema_version,
            ));
        }

        let file: LocalProgressFile = serde_json::from_slice(bytes)?;
        let mut progress = Self::default();

        for StoredPart {
            year,
            day,
            part,
            status,
        } in file.parts
        {
            if !(2015..=9999).contains(&year)
                || !(1..=25).contains(&day)
                || !(1..=2).contains(&part)
            {
                return Err(LocalProgressError::InvalidPart { year, day, part });
            }

            if progress.parts.insert((year, day, part), status).is_some() {
                return Err(LocalProgressError::DuplicatePart { year, day, part });
            }
        }

        Ok(progress)
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{Value, json};

    use super::{LocalProgress, LocalProgressError, PartStatus, ProgressReport};

    fn report(parts: &Value, day_error: &Value) -> ProgressReport {
        serde_json::from_value(json!({
            "schema_version": 1,
            "days": [{
                "year": 2025,
                "day": 3,
                "parts": parts,
                "day_error": day_error,
            }],
        }))
        .unwrap()
    }

    #[test]
    fn updates_only_the_part_that_ran() {
        let mut progress = LocalProgress::default();

        progress.record(&report(
            &json!([
                { "part": 1, "status": "succeeded" },
                { "part": 2, "status": "succeeded" }
            ]),
            &Value::Null,
        ));
        progress.record(&report(
            &json!([{ "part": 2, "status": "panicked" }]),
            &Value::Null,
        ));

        assert_eq!(
            progress.part_status(2025, 3, 1),
            Some(PartStatus::Succeeded)
        );
        assert_eq!(progress.part_status(2025, 3, 2), Some(PartStatus::Panicked));
        assert_eq!(progress.part_status(2025, 4, 1), None);
    }

    #[test]
    fn day_level_failure_preserves_previous_part_outcomes() {
        let mut progress = LocalProgress::default();

        progress.record(&report(
            &json!([{ "part": 1, "status": "succeeded" }]),
            &Value::Null,
        ));
        progress.record(&report(&json!([]), &json!("panic")));

        assert_eq!(
            progress.part_status(2025, 3, 1),
            Some(PartStatus::Succeeded)
        );
        assert_eq!(progress.part_status(2025, 3, 2), None);
    }

    #[test]
    fn round_trips_local_progress() {
        let mut progress = LocalProgress::default();
        progress.record(&report(
            &json!([
                { "part": 1, "status": "succeeded" },
                { "part": 2, "status": "panicked" }
            ]),
            &Value::Null,
        ));

        let bytes = progress.to_json().unwrap();
        let restored = LocalProgress::from_json(&bytes).unwrap();

        assert_eq!(
            restored.part_status(2025, 3, 1),
            Some(PartStatus::Succeeded)
        );
        assert_eq!(restored.part_status(2025, 3, 2), Some(PartStatus::Panicked));
        assert_eq!(restored.to_json().unwrap(), bytes);
    }

    #[test]
    fn rejects_unsupported_local_progress_schema() {
        assert!(matches!(
            LocalProgress::from_json(br#"{"schema_version":2,"entries":[]}"#),
            Err(LocalProgressError::UnsupportedVersion(2)),
        ));
    }

    #[test]
    fn rejects_duplicate_local_progress_entries() {
        let entry = json!({
            "year": 2025,
            "day": 3,
            "part": 1,
            "status": "succeeded",
        });
        let bytes = serde_json::to_vec(&json!({
            "schema_version": 1,
            "parts": [&entry, &entry],
        }))
        .unwrap();

        assert!(matches!(
            LocalProgress::from_json(&bytes),
            Err(LocalProgressError::DuplicatePart {
                year: 2025,
                day: 3,
                part: 1,
            }),
        ));
    }
}