use super::*;
pub(crate) fn is_valid_key(key: &str) -> bool {
let bytes: &[u8] = key.as_bytes();
if bytes.is_empty() || !(bytes[0].is_ascii_alphabetic() || bytes[0] == b'_') {
return false;
}
bytes
.iter()
.all(|b: &u8| b.is_ascii_alphanumeric() || *b == b'_')
}
pub(crate) fn interpolate(raw: &str, parsed: &BTreeMap<String, String>) -> String {
if !raw.as_bytes().contains(&b'$') || !raw.contains("${") {
return raw.to_owned();
}
let mut out: String = String::with_capacity(raw.len());
let mut rest: &str = raw;
while let Some(idx) = rest.find("${") {
out.push_str(&rest[..idx]);
let after: &str = &rest[idx + 2..];
if let Some(close) = after.find('}') {
let key: &str = after[..close].trim();
if let Some(val) = parsed.get(key) {
out.push_str(val);
} else if let Ok(val) = env::var(key) {
out.push_str(&val);
}
rest = &after[close + 1..];
} else {
out.push_str("${");
rest = after;
}
}
out.push_str(rest);
out
}
pub(crate) fn parse_double_quoted(raw: &str, line: usize) -> Result<String, EnvError> {
let mut out: String = String::with_capacity(raw.len());
let mut chars: Chars<'_> = raw.chars();
while let Some(ch) = chars.next() {
if ch == '"' {
return Ok(out);
}
if ch == '\\' {
let Some(esc) = chars.next() else {
return Err(EnvError::Syntax {
line,
reason: ERR_UNCLOSED_QUOTE.to_owned(),
});
};
match esc {
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'"' => out.push('"'),
'\\' => out.push('\\'),
other => {
out.push('\\');
out.push(other);
}
}
} else {
out.push(ch);
}
}
Err(EnvError::Syntax {
line,
reason: ERR_UNCLOSED_QUOTE.to_owned(),
})
}
pub fn parse_dotenv(content: &str) -> Result<BTreeMap<String, String>, EnvError> {
let mut out: BTreeMap<String, String> = BTreeMap::new();
for (idx, raw_line) in content.lines().enumerate() {
let line_no: usize = idx + 1;
let trimmed: &str = raw_line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let body: &str = trimmed
.strip_prefix(EXPORT_PREFIX)
.unwrap_or(trimmed)
.trim_start();
let Some((key_raw, val_raw)) = body.split_once('=') else {
return Err(EnvError::Syntax {
line: line_no,
reason: ERR_MISSING_EQ.to_owned(),
});
};
let key: &str = key_raw.trim();
if !is_valid_key(key) {
return Err(EnvError::Syntax {
line: line_no,
reason: ERR_INVALID_KEY.to_owned(),
});
}
let val_trim: &str = val_raw.trim();
let value: String = if let Some(after_sq) = val_trim.strip_prefix('\'') {
let Some(end) = after_sq.find('\'') else {
return Err(EnvError::Syntax {
line: line_no,
reason: ERR_UNCLOSED_QUOTE.to_owned(),
});
};
after_sq[..end].to_owned()
} else if let Some(after_dq) = val_trim.strip_prefix('"') {
let unescaped: String = parse_double_quoted(after_dq, line_no)?;
interpolate(&unescaped, &out)
} else {
let no_comment: &str = match val_trim.find(" #") {
Some(pos) => val_trim[..pos].trim_end(),
None => val_trim,
};
interpolate(no_comment, &out)
};
let _: Option<String> = out.insert(key.to_owned(), value);
}
Ok(out)
}