aoc-toolkit 0.1.0-alpha.4

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

use tempfile::NamedTempFile;

use super::{ReadmeSectionError, replace_progress_section};
use crate::ClientError;
use crate::client::cache;
use crate::project::ReadmeSettings;

#[derive(Debug, thiserror::Error)]
pub enum ReadmeWriteError {
    #[error("README progress updates are disabled; enable progress.readme.enabled in aoc.toml")]
    Disabled,

    #[error("README path must point to an existing regular file inside the project: {0}")]
    InvalidPath(PathBuf),

    #[error("Cannot update README at {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error("Cannot lock the project README: {0}")]
    Lock(#[from] ClientError),

    #[error(transparent)]
    Section(#[from] ReadmeSectionError),
}

/// Updates the managed README section and reports whether the file changed.
///
/// # Errors
///
/// Returns an error if updates are disabled, the path or markers are invalid,
/// or the file cannot be locked, read, or atomically replaced.
pub fn update_readme(
    project_root: &Path,
    settings: &ReadmeSettings,
    markdown: &str,
) -> Result<bool, ReadmeWriteError> {
    if !settings.enabled {
        return Err(ReadmeWriteError::Disabled);
    }

    let configured_path = settings
        .path
        .as_deref()
        .unwrap_or_else(|| Path::new("README.md"));
    let root = project_root
        .canonicalize()
        .map_err(|source| io_error(project_root, source))?;
    let path = resolve_readme_path(&root, configured_path)?;
    let _guard = cache::lock(&root.join(".aoc-toolkit/readme.lock"))?;

    let original = fs::read_to_string(&path).map_err(|source| io_error(&path, source))?;
    let updated = replace_progress_section(&original, markdown)?;

    if updated == original {
        return Ok(false);
    }

    replace_file(&path, &updated)?;
    Ok(true)
}

fn resolve_readme_path(root: &Path, configured_path: &Path) -> Result<PathBuf, ReadmeWriteError> {
    let invalid = || ReadmeWriteError::InvalidPath(configured_path.to_path_buf());
    if configured_path.as_os_str().is_empty()
        || !configured_path
            .components()
            .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
    {
        return Err(invalid());
    }

    let candidate = root.join(configured_path);
    let metadata =
        fs::symlink_metadata(&candidate).map_err(|source| io_error(&candidate, source))?;
    if !metadata.is_file() {
        return Err(invalid());
    }

    let path = candidate
        .canonicalize()
        .map_err(|source| io_error(&candidate, source))?;
    if !path.starts_with(root) {
        return Err(invalid());
    }

    Ok(path)
}

fn replace_file(path: &Path, content: &str) -> Result<(), ReadmeWriteError> {
    let parent = path
        .parent()
        .ok_or_else(|| ReadmeWriteError::InvalidPath(path.to_path_buf()))?;
    let permissions = fs::metadata(path)
        .map_err(|source| io_error(path, source))?
        .permissions();

    let mut temporary = NamedTempFile::new_in(parent).map_err(|source| io_error(path, source))?;
    temporary
        .write_all(content.as_bytes())
        .map_err(|source| io_error(path, source))?;
    temporary
        .as_file()
        .set_permissions(permissions)
        .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) -> ReadmeWriteError {
    ReadmeWriteError::Io {
        path: path.to_path_buf(),
        source,
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, path::PathBuf};

    use tempfile::tempdir;

    use super::{ReadmeWriteError, update_readme};
    use crate::application::progress::readme::{END_MARKER, START_MARKER};
    use crate::project::ReadmeSettings;

    #[test]
    fn updates_the_configured_file_and_skips_an_identical_write() {
        let project = tempdir().unwrap();
        let docs = project.path().join("docs");
        fs::create_dir(&docs).unwrap();
        let path = docs.join("AoC.md");
        let original = format!("# My project\n{START_MARKER}\n{END_MARKER}\nManual notes\n");
        fs::write(&path, original).unwrap();

        let settings = ReadmeSettings {
            enabled: true,
            path: Some(PathBuf::from("docs/AoC.md")),
            ..ReadmeSettings::default()
        };

        assert!(update_readme(project.path(), &settings, "New progress\n").unwrap());
        assert!(!update_readme(project.path(), &settings, "New progress\n").unwrap());
        assert_eq!(
            fs::read_to_string(path).unwrap(),
            format!("# My project\n{START_MARKER}\nNew progress\n{END_MARKER}\nManual notes\n"),
        );
    }

    #[test]
    fn refuses_disabled_export_and_paths_outside_the_project() {
        let project = tempdir().unwrap();
        let disabled = ReadmeSettings::default();

        assert!(matches!(
            update_readme(project.path(), &disabled, "Progress"),
            Err(ReadmeWriteError::Disabled),
        ));

        let outside = ReadmeSettings {
            enabled: true,
            path: Some(PathBuf::from("../README.md")),
            ..ReadmeSettings::default()
        };
        assert!(matches!(
            update_readme(project.path(), &outside, "Progress"),
            Err(ReadmeWriteError::InvalidPath(_)),
        ));
    }

    #[test]
    fn preserves_the_original_file_when_markers_are_missing() {
        let project = tempdir().unwrap();
        let path = project.path().join("README.md");
        let original = "# Project\nManual notes\n";
        fs::write(&path, original).unwrap();
        let settings = ReadmeSettings {
            enabled: true,
            ..ReadmeSettings::default()
        };

        assert!(matches!(
            update_readme(project.path(), &settings, "Progress"),
            Err(ReadmeWriteError::Section(_)),
        ));
        assert_eq!(fs::read_to_string(path).unwrap(), original);
    }
}