use std::path::{Path, PathBuf};
use colored::Colorize;
use indexmap::IndexMap;
use serde::de::DeserializeOwned;
mod env_file;
mod error;
mod includes;
mod interpolate;
pub mod lenient;
mod load;
mod merge;
pub use env_file::{
EnvFileError, is_env_file, parse_env_file, parse_env_file_object,
};
pub use error::{
Error, deserialize_final, redact_serde_error, value_type,
};
pub use interpolate::*;
pub use merge::{merge_config, merge_objects};
#[cfg(feature = "cicada")]
pub use cicada_loader as cicada;
pub type Result<T> = ::core::result::Result<T, Error>;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
fn dedupe_key(path: &Path) -> PathBuf {
if load::is_cicada_path(path) {
return path.to_path_buf();
}
path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}
pub struct ConfigLoader<'outer, 'inner> {
pub paths: &'outer [&'inner Path],
pub match_wildcards: &'outer [&'inner str],
pub include_file_name: &'static str,
pub merge_nested: bool,
pub extend_array: bool,
pub debug_print: bool,
}
impl ConfigLoader<'_, '_> {
pub fn load<T: DeserializeOwned>(self) -> Result<T> {
let ConfigLoader {
paths,
match_wildcards,
include_file_name,
merge_nested,
extend_array,
debug_print,
} = self;
if debug_print {
println!(
"{}: {}: {paths:?}",
"DEBUG".cyan(),
"Config paths".dimmed()
);
}
let wildcards = match_wildcards
.iter()
.map(|&wc| {
wildcard::Wildcard::new(wc.as_bytes()).map_err(|e| {
Error::InvalidWildcard {
pattern: wc.to_string(),
message: e.to_string(),
}
})
})
.collect::<Result<Vec<_>>>()?;
if debug_print {
println!(
"{}: {}: {match_wildcards:?}",
"DEBUG".cyan(),
"Config wildcards".dimmed()
);
}
let mut all_files = IndexMap::<PathBuf, PathBuf>::new();
let mut push = |key: PathBuf, path: PathBuf| {
let path = match all_files.shift_remove(&key) {
Some(prev)
if !load::has_config_type(&path)
&& load::has_config_type(&prev) =>
{
prev
}
_ => path,
};
all_files.insert(key, path);
};
for &path in paths {
#[cfg(feature = "cicada")]
if load::is_cicada_path(path) {
push(path.to_path_buf(), path.to_path_buf());
continue;
}
#[cfg(not(feature = "cicada"))]
if load::is_cicada_path(path) {
return Err(Error::CicadaFeatureDisabled {
path: path.to_path_buf(),
});
}
let metadata = match std::fs::metadata(path) {
Ok(metadata) => metadata,
Err(e) => {
if debug_print {
println!(
"{}: {}: {path:?} | {e:?}",
"DEBUG".cyan(),
"Skipping Path".dimmed()
);
}
continue;
}
};
if metadata.is_dir() {
let mut files = Vec::new();
let mut visiting = std::collections::HashSet::new();
load::load_config_files(
&mut files,
&mut visiting,
path,
&wildcards,
include_file_name,
debug_print,
)?;
for path in files {
push(dedupe_key(&path), path);
}
} else if metadata.is_file() {
push(dedupe_key(path), path.to_path_buf());
}
}
let all_files = all_files.into_values().collect::<Vec<_>>();
if debug_print {
println!(
"{}: {}: {all_files:?}",
"DEBUG".cyan(),
"Found Files".dimmed()
);
}
load::load_parse_config_files(
&all_files,
merge_nested,
extend_array,
)
}
}