use std::path::Path;
use colored::Colorize;
use indexmap::IndexSet;
use serde::de::DeserializeOwned;
mod error;
mod includes;
mod interpolate;
mod load;
mod merge;
pub use error::Error;
pub use interpolate::*;
pub use merge::{merge_config, merge_objects};
pub type Result<T> = ::core::result::Result<T, Error>;
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;
let mut wildcards = Vec::with_capacity(match_wildcards.len());
for &wc in match_wildcards {
match wildcard::Wildcard::new(wc.as_bytes()) {
Ok(wc) => wildcards.push(wc),
Err(e) => {
println!(
"{}: Keyword '{}' is invalid wildcard | {e:?}",
"ERROR".red(),
wc.bold(),
);
}
}
}
let mut all_files = IndexSet::new();
for &path in paths {
#[cfg(feature = "cicada")]
if path.starts_with("cicada:") {
let path = path.to_path_buf();
all_files.shift_remove(&path);
all_files.insert(path);
}
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();
load::load_config_files(
&mut files,
path,
&wildcards,
include_file_name,
debug_print,
);
files.sort_by(|(a_index, a_path), (b_index, b_path)| {
a_index.cmp(b_index).then(a_path.cmp(b_path))
});
all_files.extend(files.into_iter().map(|(_, path)| path));
} else if metadata.is_file() {
let path = path.to_path_buf();
all_files.shift_remove(&path);
all_files.insert(path);
}
}
if debug_print {
println!(
"{}: {}: {all_files:?}",
"DEBUG".cyan(),
"Found Files".dimmed()
);
}
load::load_parse_config_files(
&all_files.into_iter().collect::<Vec<_>>(),
merge_nested,
extend_array,
)
}
}