use std::collections::HashMap;
use std::path::Path;
use crate::models::{CheckStatus, DiagnosticResult};
use crate::modules::stack_detector::read_clean;
pub const CRITICAL_VARS: &[&str] = &["API_KEY", "DATABASE_URL", "SECRET", "PORT"];
pub fn parse_env(content: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
for line in content.lines() {
let mut line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(rest) = line.strip_prefix("export") {
line = rest.trim();
}
let (key, raw_value) = match line.split_once('=') {
Some(pair) => pair,
None => continue,
};
let key = key.trim();
if key.is_empty() {
continue;
}
out.insert(key.to_string(), clean_value(raw_value));
}
out
}
fn clean_value(raw: &str) -> String {
let mut value = raw.trim();
if let Some(stripped) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
value = stripped;
} else if let Some(stripped) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
value = stripped;
}
if let Some(idx) = value.find(" #") {
value = value[..idx].trim_end();
}
value.to_string()
}
pub fn audit_env_files(repo_path: &str) -> DiagnosticResult {
let root = Path::new(repo_path);
let env_file = root.join(".env");
let example_file = root.join(".env.example");
let has_env = env_file.is_file();
let has_example = example_file.is_file();
match (has_env, has_example) {
(true, true) => audit_both(&env_file, &example_file),
(true, false) => audit_env_only(&env_file),
(false, true) => DiagnosticResult::new(
"Env Audit",
CheckStatus::Warn,
".env file missing! Found .env.example template.",
)
.with_remediation("Copy .env.example to .env and fill in the values"),
(false, false) => DiagnosticResult::new(
"Env Audit",
CheckStatus::Pass,
"No .env or .env.example found; this project may not need environment variables.",
),
}
}
fn audit_both(env_file: &Path, example_file: &Path) -> DiagnosticResult {
let env = read_env(env_file);
let example = read_env(example_file);
let mut critical_problems: Vec<&str> = Vec::new();
for var in CRITICAL_VARS {
if !example.contains_key(*var) {
continue;
}
match env.get(*var) {
None => critical_problems.push(var),
Some(value) if value.is_empty() => critical_problems.push(var),
Some(_) => {}
}
}
let mut missing_keys: Vec<&String> = example
.keys()
.filter(|key| !env.contains_key(*key))
.collect();
missing_keys.sort();
if !critical_problems.is_empty() {
return DiagnosticResult::new(
"Env Audit",
CheckStatus::Fail,
format!(
"Critical variables missing or empty in .env: {}",
critical_problems.join(", ")
),
)
.with_remediation(format!(
"Copy and fill from .env.example: {}",
critical_problems.join(", ")
));
}
if !missing_keys.is_empty() {
return DiagnosticResult::new(
"Env Audit",
CheckStatus::Warn,
format!(
"{} keys from .env.example are missing in .env: {}",
missing_keys.len(),
missing_keys
.iter()
.map(|k| k.as_str())
.collect::<Vec<_>>()
.join(", ")
),
)
.with_remediation(format!(
"Add the missing keys to .env: {}",
missing_keys
.iter()
.map(|k| k.as_str())
.collect::<Vec<_>>()
.join(", ")
));
}
let present = example.keys().filter(|key| env.contains_key(*key)).count();
DiagnosticResult::new(
"Env Audit",
CheckStatus::Pass,
format!(
"{present}/{} keys from .env.example are present in .env",
example.len()
),
)
}
fn audit_env_only(env_file: &Path) -> DiagnosticResult {
let env = read_env(env_file);
let mut missing: Vec<&str> = Vec::new();
let mut empty: Vec<&str> = Vec::new();
for var in CRITICAL_VARS {
match env.get(*var) {
None => missing.push(var),
Some(value) if value.is_empty() => empty.push(var),
Some(_) => {}
}
}
if !missing.is_empty() {
return DiagnosticResult::new(
"Env Audit",
CheckStatus::Fail,
format!(
"Critical variables missing from .env: {}",
missing.join(", ")
),
)
.with_remediation(format!("Add them to .env: {}", missing.join(", ")));
}
if !empty.is_empty() {
return DiagnosticResult::new(
"Env Audit",
CheckStatus::Fail,
format!("Critical variables empty in .env: {}", empty.join(", ")),
)
.with_remediation(format!("Fill in values for: {}", empty.join(", ")));
}
DiagnosticResult::new(
"Env Audit",
CheckStatus::Pass,
format!("Critical variables are set in .env ({} keys)", env.len()),
)
}
fn read_env(path: &Path) -> HashMap<String, String> {
read_clean(path)
.map(|content| parse_env(&content))
.unwrap_or_default()
}
#[doc(hidden)]
pub fn status_label(status: CheckStatus) -> &'static str {
match status {
CheckStatus::Pass => "PASS",
CheckStatus::Warn => "WARN",
CheckStatus::Fail => "FAIL",
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_nanos();
let path = std::env::temp_dir().join(format!("limitless_env_{label}_{stamp}"));
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn path(&self) -> &Path {
&self.path
}
fn write(self, relative: &str, content: &str) -> Self {
let full = self.path.join(relative);
if let Some(parent) = full.parent() {
fs::create_dir_all(parent).expect("create parent dirs");
}
fs::write(full, content).expect("write fixture file");
self
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn parse_env_skips_comments_and_blank_lines() {
let content = "# top comment\n\nAPI_KEY=abc\nDATABASE_URL = postgres://host/db\n\
# another comment\nPORT=8080 # dev default\n";
let env = parse_env(content);
assert_eq!(env.get("API_KEY").map(String::as_str), Some("abc"));
assert_eq!(
env.get("DATABASE_URL").map(String::as_str),
Some("postgres://host/db")
);
assert_eq!(env.get("PORT").map(String::as_str), Some("8080"));
assert_eq!(env.len(), 3);
}
#[test]
fn parse_env_strips_quotes_and_export_prefix() {
let content = "SECRET=\"s p a c e\"\nexport TOKEN='quoted value'\nOPEN=#c1f\n";
let env = parse_env(content);
assert_eq!(env.get("SECRET").map(String::as_str), Some("s p a c e"));
assert_eq!(env.get("TOKEN").map(String::as_str), Some("quoted value"));
assert_eq!(env.get("OPEN").map(String::as_str), Some("#c1f"));
}
#[test]
fn parse_env_skips_malformed_lines() {
let content = "JUST_A_KEY\n=orphan\nOK=1\n";
let env = parse_env(content);
assert_eq!(env.len(), 1);
assert_eq!(env.get("OK").map(String::as_str), Some("1"));
}
#[test]
fn example_present_env_missing_warns() {
let dir =
TempDir::new("example_only").write(".env.example", "API_KEY=change-me\nPORT=3000\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.check_name, "Env Audit");
assert_eq!(result.status, CheckStatus::Warn);
assert!(result.message.contains(".env.example"));
assert_eq!(
result.remediation.as_deref(),
Some("Copy .env.example to .env and fill in the values")
);
}
#[test]
fn no_env_files_passes() {
let dir = TempDir::new("neither");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Pass);
}
#[test]
fn critical_var_missing_from_env_fails() {
let dir = TempDir::new("both_missing_critical")
.write(
".env.example",
"API_KEY=abc\nDATABASE_URL=postgres://db\nSECRET=s\nPORT=3000\n",
)
.write(".env", "API_KEY=abc\nPORT=3000\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Fail);
assert!(result.message.contains("DATABASE_URL"));
assert!(result.message.contains("SECRET"));
assert!(result.remediation.is_some());
}
#[test]
fn critical_var_empty_in_env_fails() {
let dir = TempDir::new("both_empty_critical")
.write(".env.example", "API_KEY=abc\n")
.write(".env", "API_KEY=\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Fail);
assert!(result.message.contains("API_KEY"));
}
#[test]
fn template_conditionals_skipped_when_not_required() {
let dir = TempDir::new("both_unrequired")
.write(".env.example", "PORT=3000\n")
.write(".env", "PORT=8080\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Pass);
}
#[test]
fn missing_non_critical_key_warns() {
let dir = TempDir::new("both_missing_key")
.write(".env.example", "API_KEY=abc\nLOG_LEVEL=info\n")
.write(".env", "API_KEY=abc\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Warn);
assert!(result.message.contains("LOG_LEVEL"));
}
#[test]
fn matching_env_passes() {
let dir = TempDir::new("both_match")
.write(
".env.example",
"API_KEY=change-me\nDATABASE_URL=postgres://db\nPORT=3000\n",
)
.write(
".env",
"API_KEY=real\nDATABASE_URL=postgres://prod\nPORT=8080\nEXTRA=ignored\n",
);
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Pass);
}
#[test]
fn env_only_missing_critical_fails() {
let dir = TempDir::new("env_only_missing").write(".env", "API_KEY=abc\n");
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Fail);
assert!(result.message.contains("DATABASE_URL"));
assert!(result.message.contains("SECRET"));
}
#[test]
fn env_only_complete_passes() {
let dir = TempDir::new("env_only_complete").write(
".env",
"API_KEY=abc\nDATABASE_URL=pg://db\nSECRET=s\nPORT=5432\n",
);
let result = audit_env_files(dir.path().to_str().unwrap());
assert_eq!(result.status, CheckStatus::Pass);
}
#[test]
fn examples_of_env_audit_scenarios() {
let write_only =
TempDir::new("ex_example_only").write(".env.example", "API_KEY=change-me\nPORT=3000\n");
let both_ok = TempDir::new("ex_both_ok")
.write(".env.example", "API_KEY=x\nPORT=3000\n")
.write(".env", "API_KEY=real\nPORT=8080\n");
let both_bad = TempDir::new("ex_both_bad")
.write(".env.example", "API_KEY=x\nSECRET=s\n")
.write(".env", "API_KEY=\n");
let env_only = TempDir::new("ex_env_only").write(".env", "PORT=8080\n");
let none = TempDir::new("ex_none");
for (_, child) in [
("template only", write_only.path()),
("all keys present", both_ok.path()),
("critical var empty", both_bad.path()),
("env only, missing critical", env_only.path()),
("no env files", none.path()),
] {
let result = audit_env_files(child.to_str().unwrap());
eprintln!(
" {} Env Audit — {}",
status_label(result.status),
result.message
);
if let Some(remediation) = result.remediation {
eprintln!(" Fix: {remediation}");
}
}
}
}