use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use serde_json::Value;
use super::declaration::{Choices, ChosenAt, Declaration, Keys, Kind, Node, Rules, Setting, Shape, did_you_mean};
use super::explain::Origin;
use super::files::{Picked, Walked, walk_entries};
use super::rules;
use crate::typos::meant;
const MOST_BYTES: usize = 16 << 10;
const MOST_DOTENV: usize = 1 << 20;
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Env {
prefix: String,
names: Vec<(String, String)>,
files: Vec<Dotenv>,
from: Option<Vec<(String, String)>>,
sent: Option<Texts>,
}
#[derive(Clone, PartialEq, Eq)]
enum Dotenv {
Path(PathBuf),
#[cfg_attr(
not(all(feature = "config", any(test, feature = "wire", feature = "records"))),
expect(dead_code, reason = "only an SDK over the wire and a store's logger send it")
)]
Sent {
name: String,
text: String,
},
}
impl std::fmt::Debug for Env {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let from: Option<Vec<&String>> = self.from.as_ref().map(|from| from.iter().map(|(name, _)| name).collect());
f.debug_struct("Env")
.field("prefix", &self.prefix)
.field("names", &self.names)
.field("files", &self.files)
.field("from", &from)
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for Dotenv {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Dotenv::Path(path) => std::fmt::Debug::fmt(path, f),
Dotenv::Sent { name, .. } => std::fmt::Debug::fmt(name, f),
}
}
}
impl Env {
pub fn prefix(prefix: impl Into<String>) -> Env {
Env { prefix: prefix.into(), ..Env::default() }
}
pub fn var(mut self, path: &str, name: &str) -> Env {
self.names.push((path.to_owned(), name.to_owned()));
self
}
pub fn files<P: Into<PathBuf>>(mut self, files: impl IntoIterator<Item = P>) -> Env {
self.files.extend(files.into_iter().map(|file| Dotenv::Path(file.into())));
self
}
pub fn from<K: Into<String>, V: Into<String>>(mut self, variables: impl IntoIterator<Item = (K, V)>) -> Env {
self.from = Some(variables.into_iter().map(|(name, value)| (name.into(), value.into())).collect());
self
}
}
impl Env {
#[cfg_attr(
not(all(feature = "config", any(test, feature = "wire", feature = "records"))),
expect(dead_code, reason = "only an SDK over the wire and a store's logger send it")
)]
pub(super) fn sent(mut self, variables: Vec<(String, String)>, files: Texts, dotenv: Vec<(String, String)>) -> Env {
self.files = dotenv.into_iter().map(|(name, text)| Dotenv::Sent { name, text }).collect();
self.from = Some(variables);
self.sent = Some(files);
self
}
pub(super) fn name_of(&self, path: &str) -> String {
let given = self.names.iter().rev().find(|(named, _)| named == path);
given.map_or_else(|| prefixed(&self.prefix, path), |(_, name)| name.clone())
}
}
impl From<&str> for Env {
fn from(prefix: &str) -> Env {
Env::prefix(prefix)
}
}
#[derive(Debug, Default)]
pub(super) struct Read {
pub(super) given: Vec<(String, Value, Origin)>,
pub(super) picked: Vec<(Picked, Origin)>,
pub(super) entries: Vec<(String, String)>,
pub(super) unused: Vec<Unused>,
}
#[derive(Clone, Debug)]
pub(super) struct Unused {
pub(super) name: String,
meant: Option<String>,
}
impl std::fmt::Display for Unused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let near = did_you_mean(self.meant.clone());
write!(f, "{}: a variable with the prefix that names no setting{near}", self.name)
}
}
pub(super) type Texts = HashMap<String, String>;
type Variables = HashMap<String, (String, Option<String>)>;
pub(super) fn read(env: &Env, declaration: &Declaration, keys: &Keys, before: &Choices) -> Result<Read, Vec<String>> {
let variables = variables(env)?;
let mut read = Read::default();
let mut problems = Vec::new();
let mut keys = keys.clone();
let mut maps = Vec::new();
for (path, entries) in declaration.entries() {
let name = env.name_of(&path);
match variable(env, &variables, &name, &WHOLE_MAP) {
Ok(None) => {}
Ok(Some((Value::Object(map), from))) => {
let mut walked = Walked::after(before);
walk_entries(entries, &map, &path, &mut walked);
problems.extend(walked.problems.into_iter().map(|problem| format!("{from}: {problem}")));
read.given.extend(walked.given.into_iter().map(|(path, value)| (path, value, from.clone())));
read.picked.extend(walked.picked.into_iter().map(|picked| (picked, from.clone())));
for (path, key) in walked.entries {
keys.entry(path.clone()).or_default().insert(key.clone());
read.entries.push((path, key));
}
}
Ok(Some(_)) => problems.push(format!("{name}: a map of entries is given as JSON")),
Err(problem) => problems.push(problem),
}
maps.push(name);
}
let here = Here { env, variables: &variables, given: &read.given };
let chosen = chosen_here(declaration, &keys, before, &here);
let shape = Shape { entries: keys, chosen };
let names = names(env, declaration, &shape)?;
for (path, (name, setting)) in &names {
match variable(env, &variables, name, setting) {
Ok(None) => {}
Ok(Some((value, from))) => read.take(&shape.chosen, path, value, from),
Err(problem) => problems.push(problem),
}
}
read.unused = unused(env, &variables, &names, &maps);
if problems.is_empty() { Ok(read) } else { Err(problems) }
}
struct Here<'a> {
env: &'a Env,
variables: &'a Variables,
given: &'a [(String, Value, Origin)],
}
impl Here<'_> {
fn value(&self, declaration: &Declaration, path: &str) -> Option<Value> {
let setting = declaration.setting(path)?;
let own = variable(self.env, self.variables, &self.env.name_of(path), setting).ok().flatten();
let from_map = || self.given.iter().rev().find(|(given, ..)| given == path).map(|(_, value, _)| value.clone());
own.map(|(value, _)| value).or_else(from_map)
}
}
fn chosen_here(declaration: &Declaration, keys: &Keys, before: &Choices, here: &Here<'_>) -> Choices {
let picked = |at: &ChosenAt<'_>| match here.value(declaration, &at.chooser) {
Some(value) => at.chosen.named(Some(&value)).map(|(name, _)| name.to_owned()),
None => before.get(&at.path).cloned().or_else(|| at.default.map(str::to_owned)),
};
declaration.chosen(keys).into_iter().filter_map(|at| Some((at.path.clone(), picked(&at)?))).collect()
}
impl Read {
fn take(&mut self, chosen: &Choices, path: &str, value: Value, from: Origin) {
let under = |node: &String| path.strip_prefix(node.as_str()).is_some_and(|rest| rest.starts_with('.'));
match chosen.iter().find(|(node, _)| under(node)) {
Some((node, group)) => {
let picked = Picked { node: node.clone(), group: group.clone(), path: path.to_owned(), value };
self.picked.push((picked, from));
}
None => self.given.push((path.to_owned(), value, from)),
}
}
}
static WHOLE_MAP: Setting = Setting {
kind: Kind::Object,
rules: Rules { min: None, max: None, one_of: None },
default: None,
required: false,
live: false,
secret: false,
};
fn parsed(setting: &Setting, text: &str) -> Result<Value, String> {
if text.len() > MOST_BYTES {
return Err(format!("{} bytes, past the {MOST_BYTES} a setting takes", text.len()));
}
rules::parse(setting, text).map_err(|why| if setting.secret { "its text does not read".to_owned() } else { why })
}
fn names<'a>(
env: &Env,
declaration: &'a Declaration,
shape: &Shape,
) -> Result<BTreeMap<String, (String, &'a Setting)>, Vec<String>> {
let mut problems = Vec::new();
let mut names = BTreeMap::new();
for (path, setting) in declaration.settings_of(shape) {
names.insert(path.clone(), (env.name_of(&path), setting));
}
for (path, _) in &env.names {
if declaration.setting(path).is_none() && !matches!(declaration.node(path), Some(Node::Entries(_))) {
let near = meant(path, declaration.settings().into_iter().map(|(path, _)| path));
problems.push(format!("a variable is named for {path}, which is no setting{}", did_you_mean(near)));
}
}
let mut taken: HashMap<String, &str> = HashMap::new();
for (path, (name, _)) in &names {
for read in [name.clone(), format!("{name}_FILE")] {
if let Some(other) = taken.insert(key(&read), path)
&& other != path.as_str()
{
problems.push(format!("{read} would give both {other} and {path}"));
break;
}
}
}
if problems.is_empty() { Ok(names) } else { Err(problems) }
}
pub(super) fn prefixed(prefix: &str, path: &str) -> String {
let name = upper_snake(path);
if prefix.is_empty() { name } else { format!("{prefix}_{name}") }
}
pub(super) fn upper_snake(path: &str) -> String {
let chars: Vec<char> = path.chars().collect();
let mut name = String::with_capacity(path.len() + 4);
for (at, &c) in chars.iter().enumerate() {
if c == '.' || c == '-' {
name.push('_');
continue;
}
if at > 0 && crate::text::starts_word(&chars, at) {
name.push('_');
}
name.extend(c.to_uppercase());
}
name
}
fn read_at_most(path: &std::path::Path, most: usize) -> std::io::Result<String> {
use std::io::Read;
let mut text = String::new();
std::fs::File::open(path)?.take(most as u64 + 1).read_to_string(&mut text)?;
if text.len() > most {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("past the {most} bytes it may hold")));
}
Ok(text)
}
fn key(name: &str) -> String {
if cfg!(windows) { name.to_uppercase() } else { name.to_owned() }
}
fn variables(env: &Env) -> Result<Variables, Vec<String>> {
let mut variables = Variables::new();
for file in &env.files {
let (shown, text) = match file {
Dotenv::Sent { name, text } => (name.clone(), text.clone()),
Dotenv::Path(path) => match read_at_most(path, MOST_DOTENV) {
Ok(text) => (path.display().to_string(), text),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => return Err(vec![format!("{}: {error}", path.display())]),
},
};
let read = dotenv(&text).map_err(|why| vec![format!("{shown}: {why}")])?;
variables.extend(read.into_iter().map(|(name, value)| (key(&name), (value, Some(shown.clone())))));
}
let process: Vec<(String, String)> = match &env.from {
Some(given) => given.clone(),
None => std::env::vars_os()
.filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
.collect(),
};
variables.extend(process.into_iter().map(|(name, value)| (key(&name), (value, None))));
Ok(variables)
}
fn variable(
env: &Env,
variables: &Variables,
name: &str,
setting: &Setting,
) -> Result<Option<(Value, Origin)>, String> {
let file_name = format!("{name}_FILE");
let given = |variable: &str, text: &str, dotenv: Option<&String>, file: Option<&String>| {
let value = parsed(setting, text).map_err(|why| format!("{variable}: {why}"))?;
let from = Origin::Env { variable: variable.to_owned(), dotenv: dotenv.cloned(), file: file.cloned() };
Ok(Some((value, from)))
};
match (variables.get(&key(name)), variables.get(&key(&file_name))) {
(Some(_), Some(_)) => Err(format!("{name} and {file_name} are both set")),
(Some((text, dotenv)), None) => given(name, text, dotenv.as_ref(), None),
(None, Some((path, _))) => {
let text = match &env.sent {
Some(sent) => sent
.get(path)
.cloned()
.ok_or_else(|| format!("{file_name}: {path}: the program could not read it"))?,
None => {
read_at_most(path.as_ref(), MOST_BYTES).map_err(|error| format!("{file_name}: {path}: {error}"))?
}
};
given(&file_name, &without_newline(text), None, Some(path))
}
(None, None) => Ok(None),
}
}
fn without_newline(mut text: String) -> String {
if text.ends_with('\n') {
text.pop();
if text.ends_with('\r') {
text.pop();
}
}
text
}
fn unused(
env: &Env,
variables: &Variables,
names: &BTreeMap<String, (String, &Setting)>,
maps: &[String],
) -> Vec<Unused> {
if env.prefix.is_empty() {
return Vec::new();
}
let start = key(&format!("{}_", env.prefix));
let named = names.values().map(|(name, _)| name).chain(maps);
let read: Vec<String> = named.flat_map(|name| [key(name), key(&format!("{name}_FILE"))]).collect();
let mut unused: Vec<String> = variables
.iter()
.filter(|(name, _)| name.starts_with(&start) && !read.contains(name))
.map(|(name, _)| name.clone())
.collect();
unused.sort();
unused
.into_iter()
.map(|name| Unused { meant: meant(&name, names.values().map(|(name, _)| name.as_str())), name })
.collect()
}
pub(super) fn dotenv(text: &str) -> Result<Vec<(String, String)>, String> {
let mut values = Vec::new();
let (mut rest, mut line) = (text, 1);
while !rest.is_empty() {
let (assigned, after) = assignment(rest).map_err(|why| format!("line {line}: {why}"))?;
line += rest[..rest.len() - after.len()].matches('\n').count();
if let Some(pair) = assigned {
values.retain(|(name, _): &Assigned| *name != pair.0);
values.push(pair);
}
rest = after;
}
Ok(values)
}
type Assigned = (String, String);
fn assignment(text: &str) -> Result<(Option<Assigned>, &str), String> {
let (line, rest) = text.split_once('\n').unwrap_or((text, ""));
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
return Ok((None, rest));
}
let equals = line.find('=').ok_or_else(|| "not NAME=value".to_owned())?;
let name = line[..equals].trim();
let name = name.strip_prefix("export ").map_or(name, str::trim);
if !is_variable_name(name) {
return Err("what stands before its = is no variable's name".to_owned());
}
let value_start =
equals + 1 + (line[equals + 1..].len() - line[equals + 1..].trim_start_matches([' ', '\t']).len());
let opening = line.as_bytes().get(value_start).copied();
if let Some(quote @ (b'"' | b'\'')) = opening {
let (value, after) = quoted(&text[value_start..], quote)?;
return Ok((Some((name.to_owned(), value)), after));
}
let mut value = &line[value_start..];
if let Some(comment) = value.find(" #") {
value = &value[..comment];
}
Ok((Some((name.to_owned(), value.trim_end_matches([' ', '\t', '\r']).to_owned())), rest))
}
fn quoted(text: &str, quote: u8) -> Result<(String, &str), String> {
let bytes = text.as_bytes();
let mut value = Vec::new();
let mut at = 1;
while at < bytes.len() {
match bytes[at] {
byte if byte == quote => {
let after = text[at + 1..].split_once('\n').map_or("", |(_, after)| after);
return Ok((String::from_utf8_lossy(&value).into_owned(), after));
}
b'\\' if quote == b'"' && at + 1 < bytes.len() => {
at += 1;
match bytes[at] {
b'n' | b'r' | b't' | b'"' | b'\\' => value.push(unescaped(bytes[at])),
other => value.extend([b'\\', other]),
}
}
byte => value.push(byte),
}
at += 1;
}
Err(format!("a value opened with {} is never closed", quote as char))
}
fn unescaped(byte: u8) -> u8 {
match byte {
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
other => other,
}
}
fn is_variable_name(name: &str) -> bool {
!name.is_empty()
&& name.chars().enumerate().all(|(at, c)| c == '_' || c.is_alphabetic() || (at > 0 && c.is_ascii_digit()))
}
#[cfg(test)]
#[path = "env_tests.rs"]
mod tests;