use std::{
collections::HashSet,
fs::File,
io::Read,
path::{Path, PathBuf},
};
use colored::Colorize;
use mogh_env_parser::{is_env_file, parse_env_file_object};
use serde::de::DeserializeOwned;
use crate::{
Error, Result,
error::{redact_serde_error, redact_toml_error, redact_yaml_error},
flat::FlatPrefixes,
includes::read_includes,
interpolate::{interpolate_value, unsupported_interpolations},
merge::merge_source,
};
pub(crate) fn is_cicada_path(path: &Path) -> bool {
path.to_string_lossy().starts_with("cicada:")
}
pub(crate) struct FoundFile {
pub(crate) path: PathBuf,
pub(crate) named: bool,
}
pub(crate) fn is_missing(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
)
}
fn metadata_if_exists(
path: &Path,
debug_print: bool,
) -> Result<Option<std::fs::Metadata>> {
match std::fs::metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(e) if is_missing(&e) => {
if debug_print {
println!(
"{}: {}: {path:?} | {e:?}",
"DEBUG".cyan(),
"Skipping missing path".dimmed()
);
}
Ok(None)
}
Err(e) => Err(Error::ReadPathMetaData {
path: path.to_path_buf(),
e,
}),
}
}
pub(crate) fn load_config_files(
files: &mut Vec<FoundFile>,
visiting: &mut HashSet<PathBuf>,
path: &Path,
keywords: &[wildcard::Wildcard],
include_file_name: &'static str,
debug_print: bool,
) -> Result<()> {
if is_cicada_path(path) {
#[cfg(not(feature = "cicada"))]
return Err(Error::CicadaFeatureDisabled {
path: path.to_path_buf(),
});
#[cfg(feature = "cicada")]
{
files.push(FoundFile {
path: path.to_path_buf(),
named: true,
});
return Ok(());
}
}
let Some(metadata) = metadata_if_exists(path, debug_print)? else {
return Ok(());
};
if metadata.is_file() {
files.push(FoundFile {
path: path.to_path_buf(),
named: true,
});
return Ok(());
}
if !metadata.is_dir() {
if debug_print {
println!(
"{}: {}: {path:?}",
"DEBUG".cyan(),
"Skipping path which is no file or directory".dimmed()
);
}
return Ok(());
}
let folder =
path.canonicalize().map_err(|e| Error::ReadPathMetaData {
path: path.to_path_buf(),
e,
})?;
if !visiting.insert(folder.clone()) {
if debug_print {
println!(
"{}: {}: {folder:?}",
"DEBUG".cyan(),
"Skipping include cycle".dimmed()
);
}
return Ok(());
}
let read_dir =
std::fs::read_dir(&folder).map_err(|e| Error::ReadDir {
path: folder.clone(),
e,
})?;
let mut dir_files = Vec::new();
for dir_entry in read_dir {
let dir_entry = dir_entry.map_err(|e| Error::DirFile {
path: folder.clone(),
e,
})?;
let path = dir_entry.path();
let file_name = dir_entry.file_name();
if file_name == include_file_name {
continue;
}
if keywords.is_empty() && is_env_file(&path) {
if debug_print {
println!(
"{}: {}: {path:?} (match it with a wildcard to load it)",
"DEBUG".cyan(),
"Skipping env file".dimmed()
);
}
continue;
}
let index = if keywords.is_empty() {
0
} else if let Some(index) = keywords
.iter()
.rposition(|wc| wc.is_match(file_name.as_encoded_bytes()))
{
index
} else {
continue;
};
let Some(metadata) = metadata_if_exists(&path, debug_print)?
else {
continue;
};
if !metadata.is_file() {
continue;
}
dir_files.push((index, path));
}
dir_files.sort();
files.extend(
dir_files
.into_iter()
.map(|(_, path)| FoundFile { path, named: false }),
);
let includes = read_includes(&folder, include_file_name)?;
if includes.is_empty() {
visiting.remove(&folder);
return Ok(());
}
if debug_print {
println!(
"{}: {}: {includes:?}",
"DEBUG".cyan(),
format_args!(
"{} {path:?} {}",
"Config Path".dimmed(),
"Includes".dimmed()
),
);
}
for path in includes {
load_config_files(
files,
visiting,
&path,
keywords,
include_file_name,
debug_print,
)?;
}
visiting.remove(&folder);
Ok(())
}
#[cfg(feature = "cicada")]
pub fn parse_cicada_path(
path: &Path,
) -> Option<(PathBuf, Vec<String>)> {
let path_str = path.to_string_lossy();
let path =
path_str.strip_prefix("cicada:")?.trim_start_matches('/');
let Some((path, query)) = path.split_once('?') else {
return Some((PathBuf::from(path), Vec::new()));
};
let environments = query
.split('&')
.filter_map(|pair| {
let (key, value) = pair.split_once('=')?;
matches!(
key.trim(),
"env" | "envs" | "environment" | "environments"
)
.then_some(value)
})
.flat_map(|value| value.split('+'))
.map(str::trim)
.filter(|env| !env.is_empty())
.map(String::from)
.collect();
Some((PathBuf::from(path), environments))
}
pub(crate) fn load_parse_config_files(
files: &[FoundFile],
merge_nested: bool,
extend_array: bool,
flat: &FlatPrefixes,
) -> Result<serde_json::Map<String, serde_json::Value>> {
let mut target = serde_json::Map::new();
for FoundFile { path: file, named } in files {
#[cfg(feature = "cicada")]
if let Some((node, environments)) = parse_cicada_path(file) {
let contents = cicada_loader::load(&node, environments)
.map_err(|e| Error::CicadaLoad {
path: file.clone(),
message: format!("{e:#}"),
})?;
let mut source: serde_json::Map<String, serde_json::Value> =
parse_config_contents(&node, &contents)?;
flat.fold(file, &mut source)?;
merge_source(
&mut target,
source,
merge_nested,
extend_array,
is_env_file(&node),
);
continue;
}
if !has_config_type(file) {
if *named {
return Err(Error::UnsupportedFileType {
path: file.clone(),
});
}
println!(
"{}: {file:?} is not loaded: it is no config file type (toml, yaml, yml, json, or an env file). Narrow the config wildcards to leave it out.",
"WARN".yellow(),
);
continue;
}
let env_file = is_env_file(file);
let source: serde_json::Map<String, serde_json::Value> =
load_parse_config_file(file)?;
let mut source = if env_file {
source
} else {
let mut source = serde_json::Value::Object(source);
for path in unsupported_interpolations(&source) {
println!(
"{}: {file:?} | '{path}' has a '$(...)' or '${{...}}' which is kept as written: only '${{VAR}}' and '$(command)' with a single command word (letters, digits, '_') are interpolated",
"WARN".yellow(),
);
}
interpolate_value(&mut source);
match source {
serde_json::Value::Object(source) => source,
_ => unreachable!("interpolation keeps the value an object"),
}
};
flat.fold(file, &mut source)?;
merge_source(
&mut target,
source,
merge_nested,
extend_array,
env_file,
);
}
Ok(target)
}
pub(crate) fn read_file(path: &Path) -> Result<String> {
let mut file = File::open(path).map_err(|e| Error::FileOpen {
e,
path: path.to_path_buf(),
})?;
let mut contents = String::new();
file.read_to_string(&mut contents).map_err(|e| {
Error::ReadFileContents {
e,
path: path.to_path_buf(),
}
})?;
Ok(contents)
}
pub(crate) fn load_parse_config_file<T: DeserializeOwned>(
file: &Path,
) -> Result<T> {
parse_config_contents(file, &read_file(file)?)
}
pub(crate) fn has_config_type(file: &Path) -> bool {
is_env_file(file)
|| file.extension().and_then(|e| e.to_str()).is_some_and(|e| {
matches!(
e.to_ascii_lowercase().as_str(),
"toml" | "yaml" | "yml" | "json"
)
})
}
pub(crate) fn parse_config_contents<T: DeserializeOwned>(
file: &Path,
contents: &str,
) -> Result<T> {
if is_env_file(file) {
let object = parse_env_file_object(contents).map_err(|e| {
Error::ParseEnvFile {
e,
path: file.to_path_buf(),
}
})?;
return serde_json::from_value(serde_json::Value::Object(object))
.map_err(|e| Error::ParseJson {
path: file.to_path_buf(),
message: redact_serde_error(&e),
});
}
let extension = file
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
let config: Option<T> = match extension.as_deref() {
Some("toml") => Some(toml::from_str(contents).map_err(|e| {
Error::ParseToml {
path: file.to_path_buf(),
message: redact_toml_error(&e, contents),
}
})?),
Some("yaml") | Some("yml") => serde_yaml_ng::from_str(contents)
.map_err(|e| Error::ParseYaml {
path: file.to_path_buf(),
message: redact_yaml_error(&e),
})?,
Some("json") if contents.trim().is_empty() => None,
Some("json") => serde_json::from_str(contents).map_err(|e| {
Error::ParseJson {
path: file.to_path_buf(),
message: redact_serde_error(&e),
}
})?,
Some(_) | None => {
return Err(Error::UnsupportedFileType {
path: file.to_path_buf(),
});
}
};
match config {
Some(config) => Ok(config),
None => serde_json::from_value(serde_json::Value::Object(
Default::default(),
))
.map_err(|e| Error::ParseJson {
path: file.to_path_buf(),
message: redact_serde_error(&e),
}),
}
}
#[cfg(all(test, feature = "cicada"))]
mod tests {
use super::*;
#[test]
fn parses_cicada_paths() {
for prefix in ["cicada:", "cicada:/", "cicada://"] {
let full = PathBuf::from(format!(
"{prefix}filesystem/path/config.yaml?env=prod+us-east"
));
let (path, envs) = parse_cicada_path(&full).unwrap();
assert_eq!(path, PathBuf::from("filesystem/path/config.yaml"));
assert_eq!(envs, vec!["prod", "us-east"]);
}
let (path, envs) = parse_cicada_path(Path::new(
"cicada://fs/config.yaml?env=a&env=b",
))
.unwrap();
assert_eq!(path, PathBuf::from("fs/config.yaml"));
assert_eq!(envs, vec!["a", "b"]);
let (path, envs) =
parse_cicada_path(Path::new("cicada://fs/config.yaml"))
.unwrap();
assert_eq!(path, PathBuf::from("fs/config.yaml"));
assert!(envs.is_empty());
assert!(
parse_cicada_path(Path::new("/etc/config.yaml")).is_none()
);
}
}