Skip to main content

aoc_toolkit/application/progress/
registry.rs

1use std::io;
2use std::process::ExitStatus;
3
4use crate::adapters;
5use crate::project::{Language, Project};
6
7#[derive(Debug, thiserror::Error)]
8pub enum RegistryError {
9    #[error("Failed to start runner registry command: {0}")]
10    Process(#[from] io::Error),
11
12    #[error("Runner registry command failed ({0})")]
13    RunnerFailed(ExitStatus),
14
15    #[error("Cannot decode runner registry: {0}")]
16    Decode(#[from] serde_json::Error),
17
18    #[error("Runner registry contains invalid, duplicate, or unsorted puzzle days")]
19    InvalidDays,
20}
21
22/// Returns the registered puzzle days for the project's configured runner.
23///
24/// # Errors
25///
26/// Returns an error if the runner fails or returns an invalid registry.
27pub fn registered_days(project: &Project) -> Result<Vec<(usize, usize)>, RegistryError> {
28    let output = match project.config.project.language {
29        Language::Rust => adapters::rust::list_registered_days(project)?,
30    };
31
32    if !output.status.success() {
33        return Err(RegistryError::RunnerFailed(output.status));
34    }
35
36    decode_days(&output.stdout)
37}
38
39fn decode_days(bytes: &[u8]) -> Result<Vec<(usize, usize)>, RegistryError> {
40    let days: Vec<(usize, usize)> = serde_json::from_slice(bytes)?;
41
42    if days
43        .iter()
44        .any(|(year, day)| !(2015..=9999).contains(year) || !(1..=25).contains(day))
45        || days.windows(2).any(|pair| pair[0] >= pair[1])
46    {
47        return Err(RegistryError::InvalidDays);
48    }
49
50    Ok(days)
51}
52
53#[cfg(test)]
54mod tests {
55    use super::{RegistryError, decode_days};
56
57    #[test]
58    fn accepts_empty_and_sorted_registries() {
59        assert_eq!(decode_days(b"[]").unwrap(), []);
60        assert_eq!(
61            decode_days(b"[[2024,25],[2025,1],[2025,12]]").unwrap(),
62            vec![(2024, 25), (2025, 1), (2025, 12)],
63        );
64    }
65
66    #[test]
67    fn rejects_invalid_duplicate_and_unsorted_days() {
68        for payload in [
69            "[[2014,1]]",
70            "[[2025,0]]",
71            "[[2025,26]]",
72            "[[2025,1],[2025,1]]",
73            "[[2025,2],[2025,1]]",
74        ] {
75            assert!(
76                matches!(
77                    decode_days(payload.as_bytes()),
78                    Err(RegistryError::InvalidDays),
79                ),
80                "Accepted registry: {payload}",
81            );
82        }
83    }
84
85    #[test]
86    fn rejects_malformed_json() {
87        assert!(matches!(
88            decode_days(b"not JSON"),
89            Err(RegistryError::Decode(_)),
90        ));
91    }
92}