Skip to main content

pedant_core/check_config/
discovery.rs

1use std::fs;
2use std::path::Path;
3
4use super::file::ConfigFile;
5
6/// Failure modes when loading `.pedant.toml`.
7#[derive(Debug, thiserror::Error)]
8pub enum ConfigError {
9    /// Disk I/O failure reading the config file.
10    #[error("failed to read config file: {0}")]
11    Read(#[from] std::io::Error),
12    /// TOML syntax or schema error in the config file.
13    #[error("failed to parse config file: {0}")]
14    Parse(#[from] toml::de::Error),
15}
16
17/// Read and deserialize a `.pedant.toml` from the given path.
18pub fn load_config_file(path: &Path) -> Result<ConfigFile, ConfigError> {
19    let content = fs::read_to_string(path)?;
20    Ok(toml::from_str(&content)?)
21}
22
23/// Search `.pedant.toml` in the project root, then `$XDG_CONFIG_HOME/pedant/config.toml`.
24pub fn find_config_file() -> Result<Option<std::path::PathBuf>, ConfigError> {
25    let project_config = find_project_config_file()?;
26    Ok(project_config.or_else(find_global_config_file))
27}
28
29fn find_project_config_file() -> Result<Option<std::path::PathBuf>, ConfigError> {
30    let config_path = std::env::current_dir()?.join(".pedant.toml");
31    Ok(config_path.exists().then_some(config_path))
32}
33
34fn find_global_config_file() -> Option<std::path::PathBuf> {
35    let config_dir = std::env::var_os("XDG_CONFIG_HOME")
36        .map(std::path::PathBuf::from)
37        .or_else(|| {
38            std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config"))
39        })?;
40    let config_path = config_dir.join("pedant").join("config.toml");
41    config_path.exists().then_some(config_path)
42}