Skip to main content

aoc_toolkit/project/
discovery.rs

1use std::fs;
2use std::io::ErrorKind;
3use std::path::Path;
4
5use super::config::SCHEMA_VERSION;
6use super::{Project, ProjectConfig, ProjectError};
7
8const CONFIG_FILENAME: &str = "aoc.toml";
9
10impl Project {
11    /// Discovers the nearest Advent of Code project.
12    ///
13    /// # Errors
14    ///
15    /// Returns an error if the starting directory is invalid,
16    /// no configuration is found, or the configuration
17    /// cannot be read, parsed, or has an unsupported version.
18    pub fn discover(start: &Path) -> Result<Self, ProjectError> {
19        let start = start
20            .canonicalize()
21            .map_err(|source| ProjectError::InvalidStartDirectory {
22                path: start.to_path_buf(),
23                source,
24            })?;
25
26        if !start.is_dir() {
27            return Err(ProjectError::NotDirectory { path: start });
28        }
29
30        for directory in start.ancestors() {
31            let config_path = directory.join(CONFIG_FILENAME);
32
33            let content = match fs::read_to_string(&config_path) {
34                Ok(content) => content,
35
36                Err(error) if error.kind() == ErrorKind::NotFound => {
37                    continue;
38                }
39
40                Err(source) => {
41                    return Err(ProjectError::ReadConfig {
42                        path: config_path,
43                        source,
44                    });
45                }
46            };
47
48            let config: ProjectConfig =
49                toml::from_str(&content).map_err(|source| ProjectError::ParseConfig {
50                    path: config_path,
51                    source,
52                })?;
53
54            if config.schema_version != SCHEMA_VERSION {
55                return Err(ProjectError::UnsupportedSchemaVersion {
56                    found: config.schema_version,
57                    expected: SCHEMA_VERSION,
58                });
59            }
60
61            return Ok(Self {
62                root: directory.to_path_buf(),
63                config,
64            });
65        }
66
67        Err(ProjectError::NotFound { start })
68    }
69}