aoc-toolkit 0.1.0-alpha.3

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

use super::error::ScaffoldError;

#[derive(Debug)]
pub enum FileOperation {
    Create,
    Update { expected: String },
}

#[derive(Debug)]
pub struct PlannedFile {
    pub path: PathBuf,
    pub content: String,
    pub operation: FileOperation,
}

#[derive(Debug, Default)]
pub struct ScaffoldPlan {
    files: Vec<PlannedFile>,
}

#[derive(Debug, Default)]
pub struct ScaffoldReport {
    pub created: Vec<PathBuf>,
    pub updated: Vec<PathBuf>,
}

impl ScaffoldPlan {
    pub fn add_file(
        &mut self,
        path: impl Into<PathBuf>,
        content: impl Into<String>,
    ) -> Result<(), ScaffoldError> {
        self.add_operation(path.into(), content.into(), FileOperation::Create)
    }

    pub fn update_file(
        &mut self,
        path: impl Into<PathBuf>,
        expected: impl Into<String>,
        content: impl Into<String>,
    ) -> Result<(), ScaffoldError> {
        self.add_operation(
            path.into(),
            content.into(),
            FileOperation::Update {
                expected: expected.into(),
            },
        )
    }

    fn add_operation(
        &mut self,
        path: PathBuf,
        content: String,
        operation: FileOperation,
    ) -> Result<(), ScaffoldError> {
        validate_relative_path(&path)?;

        if self
            .files
            .iter()
            .any(|file| file.path.starts_with(&path) || path.starts_with(&file.path))
        {
            return Err(ScaffoldError::PathConflict(path));
        }

        self.files.push(PlannedFile {
            path,
            content,
            operation,
        });

        Ok(())
    }

    #[must_use]
    pub fn files(&self) -> &[PlannedFile] {
        &self.files
    }

    pub fn validate(&self, root: &Path) -> Result<(), ScaffoldError> {
        for file in self.files() {
            validate_parents(root, &file.path)?;

            let destination = root.join(&file.path);

            match &file.operation {
                FileOperation::Create => {
                    validate_new_file(&destination)?;
                }
                FileOperation::Update { expected } => {
                    validate_existing_file(&destination, expected)?;
                }
            }
        }

        Ok(())
    }
    pub fn apply(&self, root: &Path) -> Result<ScaffoldReport, ScaffoldError> {
        self.validate(root)?;

        let mut report = ScaffoldReport::default();

        for file in self.files() {
            validate_parents(root, &file.path)?;

            let destination = root.join(&file.path);

            match &file.operation {
                FileOperation::Create => {
                    create_file(&destination, &file.content)?;
                    report.created.push(destination);
                }

                FileOperation::Update { expected } => {
                    replace_file(&destination, expected, &file.content)?;

                    report.updated.push(destination);
                }
            }
        }

        Ok(report)
    }
}

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

fn validate_new_file(path: &Path) -> Result<(), ScaffoldError> {
    match path.symlink_metadata() {
        Ok(_) => Err(ScaffoldError::FileExists(path.to_path_buf())),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(source) => Err(io_error(path, source)),
    }
}

fn validate_existing_file(path: &Path, expected: &str) -> Result<fs::Metadata, ScaffoldError> {
    let metadata = regular_file_metadata(path)?;

    let actual = fs::read_to_string(path).map_err(|source| io_error(path, source))?;

    if actual != expected {
        return Err(ScaffoldError::FileChanged(path.to_path_buf()));
    }

    Ok(metadata)
}

fn regular_file_metadata(path: &Path) -> Result<fs::Metadata, ScaffoldError> {
    let metadata = match path.symlink_metadata() {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == ErrorKind::NotFound => {
            return Err(ScaffoldError::FileNotFound(path.to_path_buf()));
        }
        Err(source) => return Err(io_error(path, source)),
    };

    if metadata.file_type().is_symlink() {
        return Err(ScaffoldError::SymbolicLink(path.to_path_buf()));
    }

    if !metadata.is_file() {
        return Err(ScaffoldError::NotFile(path.to_path_buf()));
    }

    Ok(metadata)
}

fn validate_directory(path: &Path) -> Result<(), ScaffoldError> {
    match path.symlink_metadata() {
        Ok(metadata) => {
            if metadata.file_type().is_symlink() {
                return Err(ScaffoldError::SymbolicLink(path.to_path_buf()));
            }

            if !metadata.is_dir() {
                return Err(ScaffoldError::NotDirectory(path.to_path_buf()));
            }

            Ok(())
        }
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(source) => Err(io_error(path, source)),
    }
}

fn validate_parents(root: &Path, relative: &Path) -> Result<(), ScaffoldError> {
    validate_directory(root)?;

    let mut current = root.to_path_buf();

    if let Some(parent) = relative.parent() {
        for component in parent.components() {
            current.push(component.as_os_str());

            validate_directory(&current)?;
        }
    }

    Ok(())
}

fn create_file(path: &Path, content: &str) -> Result<(), ScaffoldError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;
    }

    let mut output = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|source| io_error(path, source))?;

    output
        .write_all(content.as_bytes())
        .map_err(|source| io_error(path, source))
}

fn replace_file(path: &Path, expected: &str, content: &str) -> Result<(), ScaffoldError> {
    let metadata = validate_existing_file(path, expected)?;

    let parent = path
        .parent()
        .ok_or_else(|| ScaffoldError::InvalidPath(path.to_path_buf()))?;

    let mut temporary =
        tempfile::NamedTempFile::new_in(parent).map_err(|source| io_error(parent, source))?;

    temporary
        .write_all(content.as_bytes())
        .map_err(|source| io_error(path, source))?;

    temporary
        .as_file()
        .set_permissions(metadata.permissions())
        .map_err(|source| io_error(path, source))?;

    temporary
        .as_file()
        .sync_all()
        .map_err(|source| io_error(path, source))?;

    validate_existing_file(path, expected)?;

    temporary
        .persist(path)
        .map_err(|error| io_error(path, error.error))?;

    Ok(())
}

fn validate_relative_path(path: &Path) -> Result<(), ScaffoldError> {
    if path.as_os_str().is_empty()
        || !path
            .components()
            .all(|component| matches!(component, Component::Normal(_)))
    {
        return Err(ScaffoldError::InvalidPath(path.to_path_buf()));
    }

    Ok(())
}

pub(crate) fn read_file(root: &Path, relative: &Path) -> Result<String, ScaffoldError> {
    validate_relative_path(relative)?;
    validate_parents(root, relative)?;

    let destination = root.join(relative);

    regular_file_metadata(&destination)?;

    fs::read_to_string(&destination).map_err(|source| io_error(&destination, source))
}

#[cfg(test)]
mod tests;