use std::ffi::OsString;
use std::fmt;
use std::io;
use std::path::Path;
use crumbkit::{Failure, Recovery};
use starmap::{Name, Source, Spec};
use zeroize::Zeroizing;
use crate::codes::{DOTENV_SECRET, DOTENV_SYNTAX, DOTENV_UNREADABLE};
use crate::files;
#[cfg(test)]
mod tests;
pub(crate) const MAX_BYTES: usize = 256 * 1024;
#[derive(Debug, Default)]
pub(crate) struct DotEnv {
pub(crate) values: Vec<(OsString, OsString)>,
pub(crate) undeclared: Vec<String>,
}
#[derive(Debug, Failure)]
pub(crate) enum DotEnvFailure {
#[failure(
code = DOTENV_UNREADABLE,
hint = "make {file} a readable text file of at most 256 KiB",
alternative = Recovery::Hint(format!("remove {file}")),
field(at = file.as_str()),
)]
Unreadable {
file: String,
error: io::Error,
},
#[failure(
code = DOTENV_SYNTAX,
hint = "write the line as NAME=value on one line, and put a value that holds spaces, # or quotes in single quotes, without escapes",
field(at = at.as_str()),
)]
Syntax {
at: String,
},
#[failure(
code = DOTENV_SECRET,
hint = "remove {name} from {file}, and give it a bind in starmap.toml, such as {{ one-password = \"op://vault/item/field\" }}",
alternative = Recovery::Hint(format!(
"remove {name} from {file}, and let starmap run ask for it and save it to the Keychain"
)),
field(key = name.as_str()),
field(at = file.as_str()),
)]
Secret {
name: Name,
file: String,
},
}
impl fmt::Display for DotEnvFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unreadable { file, .. } => write!(formatter, "{file} cannot be read"),
Self::Syntax { at } => write!(formatter, "{at} is not a line of the .env format"),
Self::Secret { name, file } => write!(
formatter,
"{file} sets {name}, which starmap.toml declares as a secret"
),
}
}
}
impl std::error::Error for DotEnvFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Unreadable { error, .. } => Some(error),
Self::Syntax { .. } | Self::Secret { .. } => None,
}
}
}
pub(crate) fn read(file: &Path, spec: &Spec) -> Result<DotEnv, Vec<DotEnvFailure>> {
let shown = file.display().to_string();
let bytes = match files::read_capped(file, MAX_BYTES + 1) {
Ok(bytes) => Zeroizing::new(bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(DotEnv::default()),
Err(error) => return Err(vec![DotEnvFailure::Unreadable { file: shown, error }]),
};
if bytes.len() > MAX_BYTES {
let error = io::Error::other("the file is over 256 KiB");
return Err(vec![DotEnvFailure::Unreadable { file: shown, error }]);
}
let Ok(text) = std::str::from_utf8(&bytes) else {
let error = io::Error::other("the file is not UTF-8 text");
return Err(vec![DotEnvFailure::Unreadable { file: shown, error }]);
};
let mut dotenv = DotEnv::default();
let mut secrets = Vec::new();
for (number, line) in text.lines().enumerate() {
let Some((key, value)) = entry(line).map_err(|()| {
let at = format!("{shown}:{}", number + 1);
vec![DotEnvFailure::Syntax { at }]
})?
else {
continue;
};
let key = key.to_owned();
let value = Zeroizing::new(value.to_owned());
let declared = key.parse::<Name>().ok().and_then(|name| {
let secret = matches!(
spec.declared(&name)?.variable().source(),
Source::Secret { .. } | Source::Generated { .. }
);
Some((name, secret))
});
match declared {
None => dotenv.undeclared.push(key),
Some((name, true)) => secrets.push(DotEnvFailure::Secret {
name,
file: shown.clone(),
}),
Some((_, false)) => dotenv
.values
.push((OsString::from(key), OsString::from(value.as_str()))),
}
}
if secrets.is_empty() {
Ok(dotenv)
} else {
Err(secrets)
}
}
fn entry(line: &str) -> Result<Option<(&str, &str)>, ()> {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return Ok(None);
}
let line = line.strip_prefix("export ").unwrap_or(line);
let (key, raw) = line.split_once('=').ok_or(())?;
let key = key.trim();
let named = key
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !named {
return Err(());
}
let raw = raw.trim();
let quoted = ['\'', '"']
.into_iter()
.find_map(|quote| raw.strip_prefix(quote).map(|inner| (quote, inner)));
let value = match quoted {
Some((quote, inner)) => {
let (value, rest) = inner.split_once(quote).ok_or(())?;
let rest = rest.trim_start();
if (quote == '"' && value.contains('\\')) || !(rest.is_empty() || rest.starts_with('#'))
{
return Err(());
}
value
}
None => {
let comment = raw.char_indices().find(|&(at, c)| {
c == '#'
&& raw
.get(..at)
.is_some_and(|before| before.ends_with(char::is_whitespace))
});
let value = comment
.and_then(|(at, _)| raw.get(..at))
.unwrap_or(raw)
.trim_end();
if value.contains(['\'', '"']) {
return Err(());
}
value
}
};
Ok(Some((key, value)))
}