use std::{
ffi::OsString,
path::{Path, PathBuf},
};
use colored::Colorize;
use indexmap::IndexMap;
use serde::de::DeserializeOwned;
mod env;
mod error;
mod flat;
mod includes;
mod interpolate;
mod load;
mod loader_env;
mod merge;
mod unknown;
#[cfg(feature = "cicada")]
pub use cicada_loader;
pub use env::{EnvSource, FILE_SUFFIX};
pub use error::{Error, deserialize_final};
pub use interpolate::interpolate_env_and_shell;
pub use loader_env::{LoaderDebug, LoaderEnv, LoaderSettings};
pub use merge::{merge_config, merge_objects};
pub use unknown::UnknownKey;
pub use mogh_env_parser::{
EnvFileEntry, EnvFileError, EnvFileSerializeError,
normalize_env_description, parse_env_file, representable_env_name,
serialize_env_file,
};
pub type Result<T> = ::core::result::Result<T, Error>;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
fn warn_unknown_keys(unknown_keys: &[UnknownKey]) {
for key in unknown_keys {
println!("{}: {key}", "WARN".yellow());
}
}
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 Default for ConfigLoader<'_, '_> {
fn default() -> Self {
Self {
paths: &[],
match_wildcards: &["*config*"],
include_file_name: ".include",
merge_nested: false,
extend_array: false,
debug_print: false,
}
}
}
impl ConfigLoader<'static, 'static> {
pub fn from_env() -> Result<Self> {
Ok(Self::leaked(default_loader_env().read()?))
}
pub fn from_vars<K, V>(
vars: impl IntoIterator<Item = (K, V)>,
) -> Result<Self>
where
K: Into<OsString>,
V: Into<OsString>,
{
Ok(Self::leaked(default_loader_env().read_vars(vars)?))
}
fn leaked(settings: LoaderSettings) -> Self {
let LoaderSettings {
config_paths,
config_keywords,
merge_nested_config,
extend_config_arrays,
config_debug,
} = settings;
let paths: &'static [PathBuf] = Vec::leak(config_paths);
let paths = paths
.iter()
.map(PathBuf::as_path)
.collect::<Vec<&'static Path>>();
let match_wildcards: &'static [String] =
Vec::leak(config_keywords);
let match_wildcards = match_wildcards
.iter()
.map(String::as_str)
.collect::<Vec<&'static str>>();
ConfigLoader {
paths: Vec::leak(paths),
match_wildcards: Vec::leak(match_wildcards),
merge_nested: merge_nested_config,
extend_array: extend_config_arrays,
debug_print: config_debug,
..ConfigLoader::default()
}
}
}
fn default_loader_env() -> LoaderEnv {
let ConfigLoader {
paths,
match_wildcards,
merge_nested,
extend_array,
..
} = ConfigLoader::default();
LoaderEnv::new("")
.default_paths(paths.iter().copied())
.default_keywords(match_wildcards.iter().copied())
.default_merge_nested(merge_nested)
.default_extend_arrays(extend_array)
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Loaded<T> {
pub config: T,
pub unknown_keys: Vec<UnknownKey>,
}
impl ConfigLoader<'_, '_> {
pub fn load<T: DeserializeOwned>(self) -> Result<T> {
let (config, unknown_keys) = self.load_tracked(None)?;
warn_unknown_keys(&unknown_keys);
config
}
pub fn load_with_env<T: DeserializeOwned>(
self,
env: &EnvSource,
) -> Result<T> {
let (config, unknown_keys) = self.load_tracked(Some(env))?;
warn_unknown_keys(&unknown_keys);
config
}
pub fn load_reporting<T: DeserializeOwned>(
self,
) -> Result<Loaded<T>> {
let (config, unknown_keys) = self.load_tracked(None)?;
Ok(Loaded {
config: config?,
unknown_keys,
})
}
pub fn load_with_env_reporting<T: DeserializeOwned>(
self,
env: &EnvSource,
) -> Result<Loaded<T>> {
let (config, unknown_keys) = self.load_tracked(Some(env))?;
Ok(Loaded {
config: config?,
unknown_keys,
})
}
fn load_tracked<T: DeserializeOwned>(
self,
env: Option<&EnvSource>,
) -> Result<(Result<T>, Vec<UnknownKey>)> {
let (sources, env) = match env {
Some(env) => {
let flat = env.flat_prefixes()?;
let env = env.read(self.debug_print)?;
let mut sources = self.load_sources(&flat)?;
env.apply(&mut sources.merged);
(sources, Some(env))
}
None => {
(self.load_sources(&flat::FlatPrefixes::default())?, None)
}
};
let (config, ignored) = error::deserialize_final_tracked(
&serde_json::Value::Object(sources.merged),
env.as_ref(),
);
Ok((config, unknown::unknown_keys(&sources.checked, &ignored)))
}
fn load_sources(
self,
flat: &flat::FlatPrefixes,
) -> Result<load::LoadedSources> {
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, load::FoundFile>::new();
let mut push = |key: PathBuf, file: load::FoundFile| {
let file = match all_files.shift_remove(&key) {
Some(prev) => load::FoundFile {
path: if !load::has_config_type(&file.path)
&& load::has_config_type(&prev.path)
{
prev.path
} else {
file.path
},
named: prev.named || file.named,
},
None => file,
};
all_files.insert(key, file);
};
for &path in paths {
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 file in files {
push(dedupe_key(&file.path), file);
}
}
let all_files = all_files.into_values().collect::<Vec<_>>();
if debug_print {
println!(
"{}: {}: {:?}",
"DEBUG".cyan(),
"Found Files".dimmed(),
all_files.iter().map(|file| &file.path).collect::<Vec<_>>()
);
}
load::load_parse_config_files(
&all_files,
merge_nested,
extend_array,
flat,
)
}
}