aoc-toolkit 0.1.0-alpha.1

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

use super::error::ScaffoldError;

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

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

impl ScaffoldPlan {
    pub fn add_file(
        &mut self,
        path: impl Into<PathBuf>,
        content: impl Into<String>,
    ) -> Result<(), ScaffoldError> {
        let path = path.into();

        if path.as_os_str().is_empty()
            || !path
                .components()
                .all(|component| matches!(component, Component::Normal(_)))
        {
            return Err(ScaffoldError::InvalidPath(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: content.into(),
        });

        Ok(())
    }

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

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

            match destination.symlink_metadata() {
                Ok(_) => {
                    return Err(ScaffoldError::FileExists(destination));
                }
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    // File does not exist.
                }
                Err(source) => {
                    return Err(ScaffoldError::Io {
                        path: destination,
                        source,
                    });
                }
            }

            let mut current = root.to_path_buf();

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

                    match current.symlink_metadata() {
                        Ok(metadata) => {
                            if metadata.file_type().is_symlink() {
                                return Err(ScaffoldError::SymbolicLink(current));
                            }

                            if !metadata.is_dir() {
                                return Err(ScaffoldError::NotDirectory(current));
                            }
                        }
                        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                        Err(source) => {
                            return Err(ScaffoldError::Io {
                                path: current,
                                source,
                            });
                        }
                    }
                }
            }
        }

        Ok(())
    }

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

        let mut created = Vec::new();

        for file in &self.files {
            let destination = root.join(&file.path);

            if let Some(parent) = destination.parent() {
                fs::create_dir_all(parent).map_err(|source| ScaffoldError::Io {
                    path: parent.to_path_buf(),
                    source,
                })?;
            }

            let mut output = OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&destination)
                .map_err(|source| ScaffoldError::Io {
                    path: destination.clone(),
                    source,
                })?;

            output
                .write_all(file.content.as_bytes())
                .map_err(|source| ScaffoldError::Io {
                    path: destination.clone(),
                    source,
                })?;

            created.push(destination);
        }

        Ok(created)
    }
}

#[cfg(test)]
mod tests;