use std::{
collections::{HashMap, HashSet},
ffi::OsString,
path::Path,
};
use colored::Colorize;
use serde::Serialize;
use crate::{Error, Result, flat::FlatPrefixes};
pub const FILE_SUFFIX: &str = "_FILE";
pub struct EnvSource {
prefix: String,
separator: String,
entries: Vec<Entry>,
without: Vec<Vec<String>>,
aliases: Vec<AliasEntry>,
file_specs: Vec<String>,
allow_empty: Vec<String>,
key_aliases: Vec<(Vec<String>, String)>,
flat_prefixes: Vec<(Vec<String>, String)>,
values: Option<Vec<(OsString, OsString)>>,
}
enum Entry {
Field(Vec<String>),
Var { name: String, path: Vec<String> },
FieldsOf(std::result::Result<serde_json::Value, String>),
}
#[derive(Debug)]
struct AliasEntry {
other: String,
name: String,
fallback: bool,
}
impl std::fmt::Debug for EnvSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EnvSource")
.field("prefix", &self.prefix)
.field("separator", &self.separator)
.field("entries", &self.entries.len())
.field("aliases", &self.aliases)
.field("file_specs", &self.file_specs)
.field("allow_empty", &self.allow_empty)
.field("key_aliases", &self.key_aliases)
.field("flat_prefixes", &self.flat_prefixes)
.field(
"values",
&self.values.as_ref().map(|values| values.len()),
)
.finish()
}
}
impl EnvSource {
pub fn new(prefix: impl Into<String>) -> EnvSource {
EnvSource {
prefix: prefix.into(),
separator: String::from("_"),
entries: Vec::new(),
without: Vec::new(),
aliases: Vec::new(),
file_specs: Vec::new(),
allow_empty: Vec::new(),
key_aliases: Vec::new(),
flat_prefixes: Vec::new(),
values: None,
}
}
pub fn nested_separator(
mut self,
separator: impl Into<String>,
) -> EnvSource {
self.separator = separator.into();
self
}
pub fn fields<'a>(
mut self,
paths: impl IntoIterator<Item = &'a str>,
) -> EnvSource {
self.entries.extend(
paths.into_iter().map(|path| Entry::Field(split(path))),
);
self
}
pub fn fields_of<T: Serialize>(mut self, config: &T) -> EnvSource {
self.entries.push(Entry::FieldsOf(
serde_json::to_value(config)
.map_err(|e| crate::error::redact_serde_error(&e)),
));
self
}
pub fn without<'a>(
mut self,
paths: impl IntoIterator<Item = &'a str>,
) -> EnvSource {
self.without.extend(paths.into_iter().map(split));
self
}
pub fn var(
mut self,
name: impl Into<String>,
path: &str,
) -> EnvSource {
self.entries.push(Entry::Var {
name: name.into(),
path: split(path),
});
self
}
pub fn alias(
mut self,
alias: impl Into<String>,
name: impl Into<String>,
) -> EnvSource {
self.aliases.push(AliasEntry {
other: alias.into(),
name: name.into(),
fallback: false,
});
self
}
pub fn fallback(
mut self,
other: impl Into<String>,
name: impl Into<String>,
) -> EnvSource {
self.aliases.push(AliasEntry {
other: other.into(),
name: name.into(),
fallback: true,
});
self
}
pub fn file_spec<'a>(
mut self,
names: impl IntoIterator<Item = &'a str>,
) -> EnvSource {
self.file_specs.extend(names.into_iter().map(String::from));
self
}
pub fn allow_empty<'a>(
mut self,
names: impl IntoIterator<Item = &'a str>,
) -> EnvSource {
self.allow_empty.extend(names.into_iter().map(String::from));
self
}
pub fn key_alias(
mut self,
path: &str,
alias: impl Into<String>,
) -> EnvSource {
self.key_aliases.push((split(path), alias.into()));
self
}
pub fn flat_prefix(
mut self,
path: &str,
prefix: impl Into<String>,
) -> EnvSource {
self.flat_prefixes.push((split(path), prefix.into()));
self
}
pub fn with_vars<K, V>(
mut self,
vars: impl IntoIterator<Item = (K, V)>,
) -> EnvSource
where
K: Into<OsString>,
V: Into<OsString>,
{
self.values = Some(
vars
.into_iter()
.map(|(name, value)| (name.into(), value.into()))
.collect(),
);
self
}
pub fn names(&self) -> Result<Vec<String>> {
Ok(self.table()?.vars.into_iter().map(|var| var.name).collect())
}
fn table(&self) -> Result<Table> {
let invalid =
|message: String| Error::InvalidEnvSource { message };
let mut vars = Vec::<Var>::new();
let mut push = |name: String, path: Vec<String>| {
vars.push(Var {
name: name.to_ascii_uppercase(),
path,
file_spec: false,
allow_empty: false,
})
};
for entry in &self.entries {
match entry {
Entry::Field(path) => push(self.name_of(path), path.clone()),
Entry::Var { name, path } => push(name.clone(), path.clone()),
Entry::FieldsOf(config) => {
let config = config.as_ref().map_err(|message| {
invalid(format!(
"the config of fields_of doesn't serialize | {message}"
))
})?;
let mut paths = Vec::new();
leaf_paths(config, &mut Vec::new(), &mut paths);
if paths.is_empty() {
return Err(invalid(String::from(
"the config of fields_of has no fields (it serializes as no object, or an empty one)",
)));
}
for path in paths {
if self
.without
.iter()
.any(|without| path.starts_with(without))
{
continue;
}
push(self.name_of(&path), path);
}
}
}
}
for var in &vars {
if var.name.is_empty() || has_empty_segment(&var.path) {
return Err(invalid(format!(
"the variable '{}' (config path '{}') has an empty name or path segment",
var.name,
var.path.join(".")
)));
}
}
for (index, var) in vars.iter().enumerate() {
for other in &vars[index + 1..] {
if var.name == other.name {
return Err(invalid(format!(
"the variable '{}' is in the table twice",
var.name
)));
}
if var.path.starts_with(&other.path)
|| other.path.starts_with(&var.path)
{
return Err(invalid(format!(
"'{}' sets '{}', which '{}' sets with '{}'",
var.name,
var.path.join("."),
other.name,
other.path.join(".")
)));
}
}
}
let index_of = |vars: &[Var], name: &str, what: &str| {
let name = name.to_ascii_uppercase();
vars.iter().position(|var| var.name == name).ok_or_else(|| {
invalid(format!(
"{what} '{name}', which is no variable of the table"
))
})
};
let mut aliases = Vec::<Alias>::new();
for AliasEntry {
other,
name,
fallback,
} in &self.aliases
{
let other = other.to_ascii_uppercase();
let index =
index_of(&vars, name, &format!("the alias '{other}' is of"))?;
if other.is_empty()
|| vars.iter().any(|var| var.name == other)
|| aliases.iter().any(|alias| alias.name == other)
{
return Err(invalid(format!(
"the alias '{other}' (of '{name}') is empty, a variable of the table, or another alias"
)));
}
aliases.push(Alias {
name: other,
index,
fallback: *fallback,
});
}
for name in &self.file_specs {
let index = index_of(&vars, name, "file_spec names")?;
vars[index].file_spec = true;
}
for name in &self.allow_empty {
let index = index_of(&vars, name, "allow_empty names")?;
vars[index].allow_empty = true;
}
for (path, alias) in &self.key_aliases {
if alias.is_empty() || has_empty_segment(path) {
return Err(invalid(format!(
"the key alias '{alias}' of '{}' has an empty key or path segment",
path.join(".")
)));
}
}
for (index, (path, prefix)) in self.flat_prefixes.iter().enumerate()
{
if prefix.is_empty() || has_empty_segment(path) {
return Err(invalid(format!(
"the flat prefix '{prefix}' of '{}' has an empty prefix or path segment",
path.join(".")
)));
}
if self.flat_prefixes[index + 1..]
.iter()
.any(|(_, other)| other == prefix)
{
return Err(invalid(format!(
"the flat prefix '{prefix}' is declared twice"
)));
}
}
Ok(Table { vars, aliases })
}
pub(crate) fn flat_prefixes(&self) -> Result<FlatPrefixes> {
let table = self.table()?;
let mut fields = HashSet::new();
for var in &table.vars {
if let Some(first) = var.path.first() {
fields.insert(first.clone());
}
}
for (path, _) in &self.flat_prefixes {
if let Some(first) = path.first() {
fields.insert(first.clone());
}
}
Ok(FlatPrefixes::new(self.flat_prefixes.clone(), fields))
}
pub fn fold_flat_keys(
&self,
file: &Path,
source: &mut serde_json::Map<String, serde_json::Value>,
) -> Result<()> {
self.flat_prefixes()?.fold(file, source)
}
fn name_of(&self, path: &[String]) -> String {
format!(
"{}{}",
self.prefix,
path.join(&self.separator).to_ascii_uppercase()
)
}
pub(crate) fn read(&self, debug_print: bool) -> Result<EnvValues> {
let table = self.table()?;
let mut names = HashMap::<String, Read>::new();
for (index, var) in table.vars.iter().enumerate() {
names.insert(var.name.clone(), Read::plain(index, None));
}
for (position, alias) in table.aliases.iter().enumerate() {
names.insert(
alias.name.clone(),
Read::plain(alias.index, Some(position)),
);
}
let named = names.clone();
for (name, read) in named {
let fallback = read
.alias
.is_some_and(|position| table.aliases[position].fallback);
if fallback {
continue;
}
names
.entry(format!("{name}{FILE_SUFFIX}"))
.or_insert(Read { file: true, ..read });
}
let mut set = HashMap::<usize, Vec<SetVar>>::new();
let environment = match &self.values {
Some(values) => values.clone(),
None => std::env::vars_os().collect(),
};
for (name, value) in environment {
let Some(name) = name.to_str() else {
continue;
};
let Some(read) = names.get(&name.to_ascii_uppercase()) else {
continue;
};
let value =
value.into_string().map_err(|_| Error::EnvNotUnicode {
variable: name.to_string(),
})?;
if is_blank(&value)
&& (read.file || !table.vars[read.index].allow_empty)
{
continue;
}
set.entry(read.index).or_default().push(SetVar {
name: name.to_string(),
read: *read,
value,
});
}
let mut values = Vec::new();
for (index, var) in table.vars.iter().enumerate() {
let Some(mut candidates) = set.remove(&index) else {
continue;
};
candidates.sort_by_key(|candidate| {
(
candidate.read.alias.is_some(),
candidate.read.alias,
!candidate.read.file,
)
});
for (position, candidate) in candidates.iter().enumerate() {
if let Some(other) = candidates[position + 1..]
.iter()
.find(|other| other.read == candidate.read)
{
return Err(Error::EnvVarSetTwice {
variable: candidate.name.clone(),
other: other.name.clone(),
});
}
}
let mut unset = Vec::new();
let mut chosen = None;
for (position, candidate) in candidates.iter().enumerate() {
let value = match (candidate.read.file, var.file_spec) {
(true, true) => format!("file:{}", candidate.value),
(true, false) => {
read_file(&candidate.name, Path::new(&candidate.value))?
}
(false, _) => candidate.value.clone(),
};
if !is_blank(&value) {
chosen = Some((candidate, value));
break;
}
if var.allow_empty {
chosen = Some((candidate, String::new()));
break;
}
unset.push(position);
}
let Some((chosen, value)) = chosen else {
continue;
};
for (position, other) in candidates.iter().enumerate() {
if unset.contains(&position)
|| other.read.alias == chosen.read.alias
|| other
.read
.alias
.is_some_and(|alias| table.aliases[alias].fallback)
{
continue;
}
println!(
"{}: {} is ignored, as {} is set too. Remove {}, an old name of {}.",
"WARN".yellow(),
other.name,
chosen.name,
other.name,
var.name,
);
}
values.push(EnvValue {
path: var.path.clone(),
variable: chosen.name.clone(),
value,
});
}
if debug_print {
println!(
"{}: {}: {:?}",
"DEBUG".cyan(),
"Environment overrides".dimmed(),
values
.iter()
.map(|value| value.variable.as_str())
.collect::<Vec<_>>()
);
}
Ok(EnvValues {
values,
key_aliases: self.key_aliases.clone(),
})
}
}
struct Table {
vars: Vec<Var>,
aliases: Vec<Alias>,
}
struct Var {
name: String,
path: Vec<String>,
file_spec: bool,
allow_empty: bool,
}
struct Alias {
name: String,
index: usize,
fallback: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Read {
index: usize,
alias: Option<usize>,
file: bool,
}
impl Read {
fn plain(index: usize, alias: Option<usize>) -> Read {
Read {
index,
alias,
file: false,
}
}
}
struct SetVar {
name: String,
read: Read,
value: String,
}
struct EnvValue {
path: Vec<String>,
variable: String,
value: String,
}
pub(crate) struct EnvValues {
values: Vec<EnvValue>,
key_aliases: Vec<(Vec<String>, String)>,
}
impl EnvValues {
pub(crate) fn apply(
&self,
config: &mut serde_json::Map<String, serde_json::Value>,
) {
for EnvValue { path, value, .. } in &self.values {
let mut object = &mut *config;
for (depth, segment) in path.iter().enumerate() {
let leaf = depth + 1 == path.len();
for (alias_path, alias) in &self.key_aliases {
if alias_path.len() != depth + 1
|| alias_path[..depth] != path[..depth]
|| alias_path[depth] != *segment
{
continue;
}
if !object.contains_key(segment) {
if let Some(moved) = object.remove(alias) {
object.insert(segment.clone(), moved);
}
} else if leaf {
object.remove(alias);
}
}
if leaf {
object.insert(
segment.clone(),
serde_json::Value::String(value.clone()),
);
break;
}
let entry =
object.entry(segment.clone()).or_insert_with(|| {
serde_json::Value::Object(Default::default())
});
if !entry.is_object() {
*entry = serde_json::Value::Object(Default::default());
}
object = entry.as_object_mut().expect("an object");
}
}
}
pub(crate) fn variable_at(
&self,
path: &serde_path_to_error::Path,
) -> Option<&str> {
use serde_path_to_error::Segment;
let keys = path
.iter()
.map_while(|segment| match segment {
Segment::Map { key } | Segment::Enum { variant: key } => {
Some(key.as_str())
}
Segment::Seq { .. } | Segment::Unknown => None,
})
.collect::<Vec<_>>();
self
.values
.iter()
.find(|value| {
keys.len() >= value.path.len()
&& value.path.iter().zip(&keys).all(|(a, b)| a == b)
})
.map(|value| value.variable.as_str())
}
}
fn is_blank(value: &str) -> bool {
value.chars().all(|c| c.is_whitespace() || c == ',')
}
fn read_file(variable: &str, path: &Path) -> Result<String> {
std::fs::read_to_string(path)
.map(|contents| contents.trim().to_string())
.map_err(|e| Error::EnvFile {
variable: variable.to_string(),
path: path.to_path_buf(),
e,
})
}
fn split(path: &str) -> Vec<String> {
path.split('.').map(str::to_string).collect()
}
fn has_empty_segment(path: &[String]) -> bool {
path.is_empty() || path.iter().any(String::is_empty)
}
fn leaf_paths(
value: &serde_json::Value,
path: &mut Vec<String>,
paths: &mut Vec<Vec<String>>,
) {
match value {
serde_json::Value::Object(object) => {
for (key, value) in object {
path.push(key.clone());
leaf_paths(value, path, paths);
path.pop();
}
}
_ if !path.is_empty() => paths.push(path.clone()),
_ => {}
}
}