aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use std::io;
use std::process::ExitStatus;

use crate::adapters;
use crate::project::{Language, Project};

#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("Failed to start runner registry command: {0}")]
    Process(#[from] io::Error),

    #[error("Runner registry command failed ({0})")]
    RunnerFailed(ExitStatus),

    #[error("Cannot decode runner registry: {0}")]
    Decode(#[from] serde_json::Error),

    #[error("Runner registry contains invalid, duplicate, or unsorted puzzle days")]
    InvalidDays,
}

/// Returns the registered puzzle days for the project's configured runner.
///
/// # Errors
///
/// Returns an error if the runner fails or returns an invalid registry.
pub fn registered_days(project: &Project) -> Result<Vec<(usize, usize)>, RegistryError> {
    let output = match project.config.project.language {
        Language::Rust => adapters::rust::list_registered_days(project)?,
    };

    if !output.status.success() {
        return Err(RegistryError::RunnerFailed(output.status));
    }

    decode_days(&output.stdout)
}

fn decode_days(bytes: &[u8]) -> Result<Vec<(usize, usize)>, RegistryError> {
    let days: Vec<(usize, usize)> = serde_json::from_slice(bytes)?;

    if days
        .iter()
        .any(|(year, day)| !(2015..=9999).contains(year) || !(1..=25).contains(day))
        || days.windows(2).any(|pair| pair[0] >= pair[1])
    {
        return Err(RegistryError::InvalidDays);
    }

    Ok(days)
}

#[cfg(test)]
mod tests {
    use super::{RegistryError, decode_days};

    #[test]
    fn accepts_empty_and_sorted_registries() {
        assert_eq!(decode_days(b"[]").unwrap(), []);
        assert_eq!(
            decode_days(b"[[2024,25],[2025,1],[2025,12]]").unwrap(),
            vec![(2024, 25), (2025, 1), (2025, 12)],
        );
    }

    #[test]
    fn rejects_invalid_duplicate_and_unsorted_days() {
        for payload in [
            "[[2014,1]]",
            "[[2025,0]]",
            "[[2025,26]]",
            "[[2025,1],[2025,1]]",
            "[[2025,2],[2025,1]]",
        ] {
            assert!(
                matches!(
                    decode_days(payload.as_bytes()),
                    Err(RegistryError::InvalidDays),
                ),
                "Accepted registry: {payload}",
            );
        }
    }

    #[test]
    fn rejects_malformed_json() {
        assert!(matches!(
            decode_days(b"not JSON"),
            Err(RegistryError::Decode(_)),
        ));
    }
}