aoc-toolkit 0.1.0-alpha.1

A toolkit for solving Advent of Code problems
Documentation
use std::fs;
use std::io::ErrorKind;
use std::path::Path;

use super::config::SCHEMA_VERSION;
use super::{Project, ProjectConfig, ProjectError};

const CONFIG_FILENAME: &str = "aoc.toml";

impl Project {
    /// Discovers the nearest Advent of Code project.
    ///
    /// # Errors
    ///
    /// Returns an error if the starting directory is invalid,
    /// no configuration is found, or the configuration
    /// cannot be read, parsed, or has an unsupported version.
    pub fn discover(start: &Path) -> Result<Self, ProjectError> {
        let start = start
            .canonicalize()
            .map_err(|source| ProjectError::InvalidStartDirectory {
                path: start.to_path_buf(),
                source,
            })?;

        if !start.is_dir() {
            return Err(ProjectError::NotDirectory { path: start });
        }

        for directory in start.ancestors() {
            let config_path = directory.join(CONFIG_FILENAME);

            let content = match fs::read_to_string(&config_path) {
                Ok(content) => content,

                Err(error) if error.kind() == ErrorKind::NotFound => {
                    continue;
                }

                Err(source) => {
                    return Err(ProjectError::ReadConfig {
                        path: config_path,
                        source,
                    });
                }
            };

            let config: ProjectConfig =
                toml::from_str(&content).map_err(|source| ProjectError::ParseConfig {
                    path: config_path,
                    source,
                })?;

            if config.schema_version != SCHEMA_VERSION {
                return Err(ProjectError::UnsupportedSchemaVersion {
                    found: config.schema_version,
                    expected: SCHEMA_VERSION,
                });
            }

            return Ok(Self {
                root: directory.to_path_buf(),
                config,
            });
        }

        Err(ProjectError::NotFound { start })
    }
}