Skip to main content

agent_config/toml/
directory.rs

1use std::path::{Path, PathBuf};
2
3use serde::de::DeserializeOwned;
4
5use crate::{error::ConfigError, toml::file::read_toml};
6
7/// Read TOML files from a directory in deterministic path order.
8///
9/// Non-TOML entries are ignored. An empty directory produces an empty vector;
10/// callers decide whether an empty configuration set is valid for their domain.
11pub fn read_toml_dir<T: DeserializeOwned>(
12    directory: impl AsRef<Path>,
13) -> Result<Vec<(PathBuf, T)>, ConfigError> {
14    let directory = directory.as_ref();
15    let entries = std::fs::read_dir(directory).map_err(|source| ConfigError::Io {
16        path: directory.to_path_buf(),
17        source,
18    })?;
19
20    let mut paths = entries
21        .map(|entry| {
22            entry
23                .map(|entry| entry.path())
24                .map_err(|source| ConfigError::Io {
25                    path: directory.to_path_buf(),
26                    source,
27                })
28        })
29        .collect::<Result<Vec<_>, _>>()?;
30
31    paths.retain(|path| path.extension().and_then(|extension| extension.to_str()) == Some("toml"));
32    paths.sort();
33
34    paths
35        .into_iter()
36        .map(|path| read_toml(&path).map(|config| (path, config)))
37        .collect()
38}