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 merge;
#[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 merge::{merge_config, merge_objects};
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 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,
}
}
}
#[derive(serde::Deserialize)]
#[serde(default)]
struct LoaderEnv {
paths: Vec<PathBuf>,
match_wildcards: Vec<String>,
include_file_name: String,
merge_nested: bool,
extend_array: bool,
debug_print: bool,
}
impl Default for LoaderEnv {
fn default() -> Self {
let ConfigLoader {
paths,
match_wildcards,
include_file_name,
merge_nested,
extend_array,
debug_print,
} = ConfigLoader::default();
LoaderEnv {
paths: paths.iter().map(|path| path.to_path_buf()).collect(),
match_wildcards: match_wildcards
.iter()
.map(|wildcard| wildcard.to_string())
.collect(),
include_file_name: include_file_name.to_string(),
merge_nested,
extend_array,
debug_print,
}
}
}
fn loader_env_source() -> EnvSource {
EnvSource::new("CONFIG_").fields([
"paths",
"match_wildcards",
"include_file_name",
"merge_nested",
"extend_array",
"debug_print",
])
}
impl ConfigLoader<'static, 'static> {
pub fn from_env() -> Result<Self> {
Self::read_env(&loader_env_source())
}
pub fn from_vars<K, V>(
vars: impl IntoIterator<Item = (K, V)>,
) -> Result<Self>
where
K: Into<OsString>,
V: Into<OsString>,
{
Self::read_env(&loader_env_source().with_vars(vars))
}
fn read_env(env: &EnvSource) -> Result<Self> {
let LoaderEnv {
paths,
match_wildcards,
include_file_name,
merge_nested,
extend_array,
debug_print,
} = ConfigLoader {
paths: &[],
match_wildcards: &[],
include_file_name: "",
merge_nested: false,
extend_array: false,
debug_print: false,
}
.load_with_env(env)?;
let paths: &'static [PathBuf] = Vec::leak(paths);
let paths = paths
.iter()
.map(PathBuf::as_path)
.collect::<Vec<&'static Path>>();
let match_wildcards: &'static [String] =
Vec::leak(match_wildcards);
let match_wildcards = match_wildcards
.iter()
.map(String::as_str)
.collect::<Vec<&'static str>>();
Ok(ConfigLoader {
paths: Vec::leak(paths),
match_wildcards: Vec::leak(match_wildcards),
include_file_name: String::leak(include_file_name),
merge_nested,
extend_array,
debug_print,
})
}
}
impl ConfigLoader<'_, '_> {
pub fn load<T: DeserializeOwned>(self) -> Result<T> {
let config = self.load_sources(&flat::FlatPrefixes::default())?;
error::deserialize_final(&serde_json::Value::Object(config))
}
pub fn load_with_env<T: DeserializeOwned>(
self,
env: &EnvSource,
) -> Result<T> {
let flat = env.flat_prefixes()?;
let env = env.read(self.debug_print)?;
let mut config = self.load_sources(&flat)?;
env.apply(&mut config);
error::deserialize_final_with_env(
&serde_json::Value::Object(config),
Some(&env),
)
}
fn load_sources(
self,
flat: &flat::FlatPrefixes,
) -> Result<serde_json::Map<String, serde_json::Value>> {
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,
)
}
}