aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use tempfile::NamedTempFile;

use super::{LocalProgress, LocalProgressError};
use crate::application::run::ProgressReport;
use crate::project::Language;

/// Stores local progress for one project and language.
pub struct LocalProgressStore {
    directory: PathBuf,
    filename: &'static str,
}

#[derive(Debug, thiserror::Error)]
pub enum LocalProgressStoreError {
    #[error("Cannot access local progress at {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error(transparent)]
    Snapshot(#[from] LocalProgressError),
}

impl LocalProgressStore {
    #[must_use]
    pub fn new(project_root: &Path, language: Language) -> Self {
        let filename = match language {
            Language::Rust => "rust.json",
        };

        Self {
            directory: project_root.join(".aoc-toolkit").join("progress"),
            filename,
        }
    }

    /// Loads the last saved snapshot, or empty progress if none exists.
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot cannot be read or decoded.
    pub fn load(&self) -> Result<LocalProgress, LocalProgressStoreError> {
        let path = self.directory.join(self.filename);

        match fs::read(&path) {
            Ok(bytes) => Ok(LocalProgress::from_json(&bytes)?),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(LocalProgress::default()),
            Err(source) => Err(io_error(&path, source)),
        }
    }

    /// Merges the reported part outcomes and atomically replaces the snapshot.
    ///
    /// # Errors
    ///
    /// Returns an error if the snapshot cannot be loaded, locked, or written.
    pub fn record(&self, report: &ProgressReport) -> Result<(), LocalProgressStoreError> {
        if report.days.iter().all(|day| day.parts.is_empty()) {
            return Ok(());
        }

        fs::create_dir_all(&self.directory).map_err(|source| io_error(&self.directory, source))?;

        let path = self.directory.join(self.filename);
        let lock_path = path.with_extension("lock");
        let lock = File::options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&lock_path)
            .map_err(|source| io_error(&lock_path, source))?;
        lock.lock().map_err(|source| io_error(&lock_path, source))?;

        let mut progress = self.load()?;
        progress.record(report);
        let bytes = progress.to_json()?;

        let mut temporary = NamedTempFile::new_in(&self.directory)
            .map_err(|source| io_error(&self.directory, source))?;
        temporary
            .write_all(&bytes)
            .map_err(|source| io_error(&path, source))?;
        temporary
            .as_file()
            .sync_all()
            .map_err(|source| io_error(&path, source))?;
        temporary
            .persist(&path)
            .map_err(|error| io_error(&path, error.error))?;

        Ok(())
    }
}

fn io_error(path: &Path, source: io::Error) -> LocalProgressStoreError {
    LocalProgressStoreError::Io {
        path: path.to_path_buf(),
        source,
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::tempdir;

    use super::{LocalProgressStore, LocalProgressStoreError};
    use crate::application::run::{
        DayFailure, DayProgress, PartProgress, PartStatus, ProgressReport,
    };
    use crate::project::Language;

    fn report(parts: Vec<PartProgress>, day_error: Option<DayFailure>) -> ProgressReport {
        ProgressReport {
            schema_version: 1,
            days: vec![DayProgress {
                year: 2025,
                day: 3,
                parts,
                day_error,
            }],
        }
    }

    #[test]
    fn merges_runs_into_the_project_snapshot() {
        let root = tempdir().unwrap();
        let store = LocalProgressStore::new(root.path(), Language::Rust);

        store
            .record(&report(
                vec![PartProgress {
                    part: 1,
                    status: PartStatus::Succeeded,
                }],
                None,
            ))
            .unwrap();
        store
            .record(&report(
                vec![PartProgress {
                    part: 2,
                    status: PartStatus::Panicked,
                }],
                None,
            ))
            .unwrap();

        let reopened = LocalProgressStore::new(root.path(), Language::Rust);
        let progress = reopened.load().unwrap();

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

    #[test]
    fn creates_no_snapshot_when_no_parts_ran() {
        let root = tempdir().unwrap();
        let store = LocalProgressStore::new(root.path(), Language::Rust);

        store
            .record(&report(Vec::new(), Some(DayFailure::Panic)))
            .unwrap();

        assert!(!root.path().join(".aoc-toolkit").exists());
    }

    #[test]
    fn preserves_an_invalid_snapshot_when_recording_fails() {
        let root = tempdir().unwrap();
        let store = LocalProgressStore::new(root.path(), Language::Rust);
        let directory = root.path().join(".aoc-toolkit").join("progress");
        let path = directory.join("rust.json");
        fs::create_dir_all(directory).unwrap();
        fs::write(&path, b"invalid JSON").unwrap();

        let result = store.record(&report(
            vec![PartProgress {
                part: 1,
                status: PartStatus::Succeeded,
            }],
            None,
        ));

        assert!(matches!(result, Err(LocalProgressStoreError::Snapshot(_))));
        assert_eq!(fs::read(path).unwrap(), b"invalid JSON");
    }
}