Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/configuration/
environment.rs

1//! Explicit-input counterpart of KiCadEnvironment's user configuration discovery.
2
3use std::path::{Path, PathBuf};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub enum Platform {
7    Windows,
8    Linux,
9    Macos,
10}
11
12/// APPDATA on Windows, HOME on Linux/macOS. No additional environment-variable
13/// precedence is introduced. Callers capture the selected process inputs.
14pub fn config_base(
15    platform: Platform,
16    app_data: Option<&Path>,
17    home: Option<&Path>,
18) -> Option<PathBuf> {
19    match platform {
20        Platform::Windows => app_data
21            .filter(|path| !path.as_os_str().is_empty())
22            .map(|path| path.join("kicad")),
23        Platform::Linux => home.map(|path| path.join(".config/kicad")),
24        Platform::Macos => home.map(|path| path.join("Library/Preferences/kicad")),
25    }
26}
27
28/// A version directory has exactly two nonempty decimal components.
29pub fn version_pair(name: &str) -> Option<(String, String)> {
30    let (major, minor) = name.split_once('.')?;
31    if major.is_empty()
32        || minor.is_empty()
33        || !major.bytes().all(|v| v.is_ascii_digit())
34        || !minor.bytes().all(|v| v.is_ascii_digit())
35    {
36        return None;
37    }
38    Some((digits(major), digits(minor)))
39}
40
41fn digits(value: &str) -> String {
42    let value = value.trim_start_matches('0');
43    if value.is_empty() {
44        "0".into()
45    } else {
46        value.into()
47    }
48}
49
50fn compare(left: &str, right: &str) -> std::cmp::Ordering {
51    left.len().cmp(&right.len()).then_with(|| left.cmp(right))
52}
53
54/// Return existing version directories in numeric order. Missing base is empty;
55/// an unreadable base is an error, never evidence that no configuration exists.
56pub fn config_paths(base: &Path, min_major: u64) -> std::io::Result<Vec<PathBuf>> {
57    let entries = match std::fs::read_dir(base) {
58        Ok(entries) => entries,
59        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
60        Err(error) => return Err(error),
61    };
62    let mut paths = Vec::new();
63    for entry in entries {
64        let entry = entry?;
65        let name = entry.file_name();
66        let Some(version) = name.to_str().and_then(version_pair) else {
67            continue;
68        };
69        if compare(&version.0, &min_major.to_string()).is_ge() && entry.path().is_dir() {
70            paths.push((version, entry.path()));
71        }
72    }
73    paths.sort_by(|(left, _), (right, _)| {
74        compare(&left.0, &right.0).then_with(|| compare(&left.1, &right.1))
75    });
76    Ok(paths.into_iter().map(|(_, path)| path).collect())
77}