limitless-cli 1.0.0

A beginner-friendly environment diagnostic tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Env-file auditor for Limitless CLI.
//!
//! Compares a project's `.env` against its `.env.example` template, flags
//! empty or missing critical configuration, and suggests concrete next steps.
//!
//! # Scenarios
//!
//! - `.env.example` present, `.env` missing → **Warn** with a copy hint.
//! - Both present → keys are compared; critical variables that the template
//!   requires but the `.env` leaves empty or omits → **Fail**.
//! - `.env` present without a template → the well-known critical variables
//!   are checked directly.
//! - Neither present → **Pass** (some projects need no environment).

use std::collections::HashMap;
use std::path::Path;

use crate::models::{CheckStatus, DiagnosticResult};
use crate::modules::stack_detector::read_clean;

/// Variable names treated as critical. When the template uses one of these,
/// the `.env` must carry it with a non-empty value.
pub const CRITICAL_VARS: &[&str] = &["API_KEY", "DATABASE_URL", "SECRET", "PORT"];

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Parses `.env`-style content into a `key -> value` map.
///
/// Rules: blank lines and lines starting with `#` are skipped; an optional
/// `export` prefix is ignored; values have surrounding quotes stripped and a
/// trailing ` # comment` removed.
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
}

/// Strips surrounding quotes and a trailing ` # comment` from an env value.
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()
}

// ---------------------------------------------------------------------------
// Auditing
// ---------------------------------------------------------------------------

/// Audits the `.env` configuration of a repository root.
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.",
        ),
    }
}

/// Both files exist: the template defines the required keys, so missing or
/// empty critical variables are hard failures; other missing keys warn.
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()
        ),
    )
}

/// Only `.env` exists: check the well-known critical variables directly.
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()),
    )
}

/// Reads and parses an env file, treating unreadable files as empty.
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};

    /// A self-cleaning temporary directory for mock `.env` fixtures.
    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);
        }
    }

    // --- Parsing ----------------------------------------------------------

    #[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"));
    }

    // --- Scenarios --------------------------------------------------------

    #[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() {
        // SECRET is not in the template, so its absence in `.env` is fine.
        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);
    }

    // --- Example outputs --------------------------------------------------

    #[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}");
            }
        }
    }
}