Skip to main content

serenade_config/
packages.rs

1//! Bundle package loader for `config/packages/*`.
2
3use std::path::{Path, PathBuf};
4
5use crate::{Config, ConfigError};
6
7/// Loads and merges YAML/TOML files from a packages directory (sorted by file name).
8///
9/// Only files directly in `dir` are loaded; subdirectories are ignored.
10/// Prefer [`load_packages_for_env`] when an environment overlay is needed.
11///
12/// # Errors
13///
14/// Returns [`ConfigError`] when the directory cannot be read or a file fails to parse.
15pub fn load_packages(dir: impl AsRef<Path>) -> Result<Config, ConfigError> {
16    load_package_files(dir.as_ref())
17}
18
19/// Loads base packages then merges `packages/{environment}/` when that directory exists.
20///
21/// # Errors
22///
23/// Returns [`ConfigError`] when a packages directory cannot be read or a file fails to parse.
24pub fn load_packages_for_env(
25    dir: impl AsRef<Path>,
26    environment: &str,
27) -> Result<Config, ConfigError> {
28    let dir = dir.as_ref();
29    let mut merged = load_package_files(dir)?;
30    let env = environment.trim();
31    if env.is_empty() {
32        return Ok(merged);
33    }
34    let overlay = dir.join(env);
35    if overlay.is_dir() {
36        merged = merged.merged(&load_package_files(&overlay)?);
37    }
38    Ok(merged)
39}
40
41fn load_package_files(dir: &Path) -> Result<Config, ConfigError> {
42    let mut entries = list_package_files(dir)?;
43    entries.sort();
44    let mut merged = Config::empty();
45    for path in entries {
46        merged = merged.merged(&Config::from_path(&path)?);
47    }
48    Ok(merged)
49}
50
51fn list_package_files(dir: &Path) -> Result<Vec<PathBuf>, ConfigError> {
52    let mut entries = Vec::new();
53    let read = std::fs::read_dir(dir).map_err(|source| ConfigError::Io {
54        path: dir.to_path_buf(),
55        source,
56    })?;
57    for entry in read.flatten() {
58        let path = entry.path();
59        if !path.is_file() {
60            continue;
61        }
62        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
63            continue;
64        };
65        if name.starts_with('.') {
66            continue;
67        }
68        let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else {
69            continue;
70        };
71        if !matches!(ext.to_ascii_lowercase().as_str(), "yaml" | "yml" | "toml") {
72            continue;
73        }
74        entries.push(path);
75    }
76    Ok(entries)
77}