pathlint 0.0.24

Lint the PATH environment variable against declarative ordering rules.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! `pathlint doctor` end-to-end tests.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

const BIN: &str = env!("CARGO_BIN_EXE_pathlint");

fn run_doctor(path_value: &str) -> (i32, String, String) {
    let out = Command::new(BIN)
        .arg("doctor")
        .env("PATH", path_value)
        .env_remove("XDG_CONFIG_HOME")
        .output()
        .expect("failed to run pathlint binary");
    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    (code, stdout, stderr)
}

fn join_path(parts: &[&Path]) -> String {
    let sep = if cfg!(windows) { ";" } else { ":" };
    parts
        .iter()
        .map(|p| p.to_string_lossy().into_owned())
        .collect::<Vec<_>>()
        .join(sep)
}

#[test]
fn doctor_warns_on_duplicate_entries() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("x");
    fs::create_dir_all(&dir).unwrap();
    let path = join_path(&[&dir, &dir]);
    let (code, stdout, _) = run_doctor(&path);
    assert_eq!(code, 0, "warn-only must not fail the run");
    assert!(stdout.contains("[warn]"), "stdout: {stdout}");
    assert!(stdout.contains("duplicate"), "stdout: {stdout}");
}

#[test]
fn doctor_warns_on_missing_directory() {
    let tmp = tempfile::tempdir().unwrap();
    let exists = tmp.path().join("real");
    fs::create_dir_all(&exists).unwrap();
    let absent = tmp.path().join("definitely_does_not_exist_xyz");
    let path = join_path(&[&exists, &absent]);
    let (code, stdout, _) = run_doctor(&path);
    assert_eq!(code, 0);
    assert!(stdout.contains("does not exist"), "stdout: {stdout}");
}

#[test]
fn doctor_reports_duplicate_but_shadowed_across_path_dirs() {
    // Two PATH dirs each containing an executable with the same
    // basename. The earlier dir wins; the later one is shadowed.
    let tmp = tempfile::tempdir().unwrap();
    let dir_a = tmp.path().join("a");
    let dir_b = tmp.path().join("b");
    fs::create_dir_all(&dir_a).unwrap();
    fs::create_dir_all(&dir_b).unwrap();
    let exe_name = if cfg!(windows) {
        "dummy_cmd.exe"
    } else {
        "dummy_cmd"
    };
    for dir in [&dir_a, &dir_b] {
        let p = dir.join(exe_name);
        fs::write(&p, b"").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
        }
    }
    // Canonicalize so Windows 8.3 short-name PATH entries don't
    // create their own ShortName diagnostic alongside the one we
    // care about.
    let dir_a = fs::canonicalize(&dir_a).unwrap();
    let dir_b = fs::canonicalize(&dir_b).unwrap();
    let dir_a = strip_unc_prefix(&dir_a);
    let dir_b = strip_unc_prefix(&dir_b);
    let path = join_path(&[&dir_a, &dir_b]);
    let (code, stdout, stderr) = run_doctor(&path);
    // Quote the binary's stdout/stderr in panic messages so an OS
    // that silently fails to detect the shadow (e.g. case-sensitive
    // filesystem mismatch in 0.0.19 pre-fix) is diagnosable from the
    // CI log without a re-push for instrumentation.
    let context = format!("code={code} stdout={stdout:?} stderr={stderr:?}");
    assert_eq!(code, 0, "warn-only must not fail the run; {context}");
    assert!(stdout.contains("dummy_cmd"), "{context}");
    assert!(stdout.contains("shadows"), "{context}");
}

#[test]
fn doctor_warns_on_relative_path_entry() {
    // PATH containing "." (cwd) is the textbook security footgun
    // for relative entries; doctor should surface it.
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    fs::create_dir_all(&real).unwrap();
    let real = fs::canonicalize(&real).unwrap();
    let real = strip_unc_prefix(&real);
    // Mix one absolute entry (the tempdir) with one relative one ("."),
    // so the run isn't dominated by other warnings.
    let path = if cfg!(windows) {
        format!("{};.", real.display())
    } else {
        format!("{}:.", real.display())
    };
    let (code, stdout, stderr) = run_doctor(&path);
    let context = format!("code={code} stdout={stdout:?} stderr={stderr:?}");
    assert_eq!(code, 0, "warn-only must not fail the run; {context}");
    assert!(stdout.contains("relative PATH entry"), "{context}");
}

#[cfg(unix)]
#[test]
fn doctor_warns_on_writeable_path_dir() {
    // Create a tempdir, chmod it 0o777 (others-write), and put it on
    // PATH. doctor should surface writeable_path_dir. Windows is
    // skipped because winapi mock for ACL is impractical at the
    // integration-test layer; the unit tests cover the closure
    // contract and is_writable_dir_real has its own smoke covered
    // by the public_api callability check.
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let writable = tmp.path().join("writable");
    fs::create_dir_all(&writable).unwrap();
    fs::set_permissions(&writable, fs::Permissions::from_mode(0o777)).unwrap();
    let writable = fs::canonicalize(&writable).unwrap();
    let writable = strip_unc_prefix(&writable);
    let path = join_path(&[&writable]);
    let (code, stdout, stderr) = run_doctor(&path);
    let context = format!("code={code} stdout={stdout:?} stderr={stderr:?}");
    assert_eq!(code, 0, "warn-only must not fail the run; {context}");
    assert!(stdout.contains("writable by other users"), "{context}");
}

#[test]
fn doctor_clean_path_emits_nothing() {
    // The temp dir on Windows lives under %LocalAppData%, which would
    // trigger the "shortenable" warning even on an otherwise clean
    // PATH. Wipe the obvious env vars so the run is genuinely empty.
    //
    // Also canonicalize the path: GitHub's `windows-latest` runner
    // resolves $TEMP via `C:\Users\RUNNER~1\...` (8.3 short name for
    // `runneradmin`), which would otherwise trip the doctor's
    // ShortName check. canonicalize expands that to the long name.
    let tmp = tempfile::tempdir().unwrap();
    let only = tmp.path().join("clean");
    fs::create_dir_all(&only).unwrap();
    let only_canonical = fs::canonicalize(&only).unwrap();
    let only_clean = strip_unc_prefix(&only_canonical);
    let path = join_path(&[&only_clean]);
    let mut cmd = Command::new(BIN);
    cmd.arg("doctor")
        .env("PATH", &path)
        .env_remove("XDG_CONFIG_HOME")
        .env_remove("HOME")
        .env_remove("USERPROFILE")
        .env_remove("LocalAppData")
        .env_remove("AppData")
        .env_remove("ProgramFiles")
        .env_remove("ProgramFiles(x86)")
        .env_remove("ProgramData")
        .env_remove("SystemRoot");
    let out = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0);
    assert!(stdout.is_empty(), "expected silence, got: {stdout}");
}

/// On Windows, `fs::canonicalize` returns paths prefixed with `\\?\`
/// (the Win32 file-namespace prefix). PATH entries don't use that
/// prefix in the wild, so strip it for tests that compare output.
fn strip_unc_prefix(p: &Path) -> PathBuf {
    let s = p.to_string_lossy();
    if let Some(rest) = s.strip_prefix(r"\\?\") {
        PathBuf::from(rest)
    } else {
        p.to_path_buf()
    }
}

#[test]
fn doctor_warns_on_trailing_slash() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("slashy");
    fs::create_dir_all(&dir).unwrap();
    let with_slash = format!(
        "{}{}",
        dir.display(),
        if cfg!(windows) { "\\" } else { "/" }
    );
    let (code, stdout, _) = run_doctor(&with_slash);
    assert_eq!(code, 0);
    assert!(stdout.contains("trailing slash"), "stdout: {stdout}");
}

#[test]
#[cfg(windows)]
fn doctor_errors_on_illegal_chars_on_windows() {
    // Pipe char is illegal in NTFS filenames and would never resolve
    // as a directory; doctor escalates this to error severity.
    let path = "C:\\foo|bar";
    let (code, stdout, _) = run_doctor(path);
    assert_eq!(code, 1, "malformed entries must yield exit 1");
    assert!(stdout.contains("[ERR]"), "stdout: {stdout}");
    assert!(stdout.contains("malformed"), "stdout: {stdout}");
}

#[test]
fn doctor_quiet_hides_warnings_but_keeps_errors() {
    // We can only stage a malformed entry on Windows (the kinds of
    // illegal chars differ on Unix). On Unix this test still asserts
    // that --quiet silences a clean warn-only run.
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("dup");
    fs::create_dir_all(&dir).unwrap();
    let path = join_path(&[&dir, &dir]);
    let out = Command::new(BIN)
        .arg("--quiet")
        .arg("doctor")
        .env("PATH", &path)
        .env_remove("XDG_CONFIG_HOME")
        .output()
        .unwrap();
    assert!(out.status.success(), "duplicate-only must exit 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("[warn]"),
        "quiet mode must hide warns: {stdout}"
    );
}

// ---- --include / --exclude (0.0.6+) -------------------------

fn run_doctor_args(path_value: &str, extra: &[&str]) -> (i32, String, String) {
    let mut cmd = Command::new(BIN);
    cmd.arg("doctor")
        .args(extra)
        .env("PATH", path_value)
        .env_remove("XDG_CONFIG_HOME");
    let out = cmd.output().expect("failed to run pathlint binary");
    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    (code, stdout, stderr)
}

#[test]
fn doctor_include_filters_to_named_kinds_only() {
    // PATH carries one missing dir AND one duplicate. With
    // `--include duplicate` the missing entry must be silenced.
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    fs::create_dir_all(&real).unwrap();
    let absent = tmp.path().join("definitely_does_not_exist_xyz");
    let path = join_path(&[&real, &real, &absent]);
    let (code, stdout, _) = run_doctor_args(&path, &["--include", "duplicate"]);
    assert_eq!(code, 0);
    assert!(stdout.contains("duplicate"), "stdout: {stdout}");
    assert!(!stdout.contains("does not exist"), "stdout: {stdout}");
}

#[test]
fn doctor_exclude_drops_diagnostics_and_affects_exit_code() {
    // Force a malformed (Error severity) entry on Windows + a
    // duplicate. Without --exclude this exits 1; with
    // --exclude malformed the Error is suppressed and the run
    // passes.
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("d");
    fs::create_dir_all(&dir).unwrap();
    if !cfg!(windows) {
        // Unix doesn't have a comparably easy malformed staging.
        return;
    }
    let path = format!("{};C:\\foo|bar", dir.display());

    let (default_code, default_stdout, _) = run_doctor_args(&path, &[]);
    assert_eq!(default_code, 1, "stdout: {default_stdout}");
    assert!(default_stdout.contains("[ERR]"), "stdout: {default_stdout}");

    let (filtered_code, filtered_stdout, _) = run_doctor_args(&path, &["--exclude", "malformed"]);
    assert_eq!(filtered_code, 0, "stdout: {filtered_stdout}");
    assert!(
        !filtered_stdout.contains("[ERR]"),
        "stdout: {filtered_stdout}"
    );
}

#[test]
fn doctor_unknown_kind_is_a_config_error_with_exit_2() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("d");
    fs::create_dir_all(&dir).unwrap();
    let (code, _stdout, stderr) = run_doctor_args(&join_path(&[&dir]), &["--include", "nope"]);
    assert_eq!(code, 2);
    assert!(stderr.contains("unknown doctor kind"), "stderr: {stderr}");
    assert!(stderr.contains("nope"), "stderr: {stderr}");
}

#[test]
fn doctor_include_and_exclude_together_is_a_clap_error() {
    // clap's conflicts_with annotation should make the parse fail
    // with exit 2 and a usage message before pathlint even runs.
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path().join("d");
    fs::create_dir_all(&dir).unwrap();
    let (code, _stdout, stderr) = run_doctor_args(
        &join_path(&[&dir]),
        &["--include", "duplicate", "--exclude", "missing"],
    );
    assert_eq!(code, 2, "stderr: {stderr}");
    assert!(
        stderr.to_ascii_lowercase().contains("cannot be used"),
        "stderr: {stderr}"
    );
}

#[test]
fn doctor_json_emits_array_with_kind_discriminator() {
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    fs::create_dir_all(&real).unwrap();
    let absent = tmp.path().join("definitely_does_not_exist_xyz");
    let path = join_path(&[&real, &real, &absent]);
    let (code, stdout, _) = run_doctor_args(&path, &["--json"]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect(&stdout);
    assert!(v.is_array(), "stdout: {stdout}");

    let kinds: Vec<&str> = v
        .as_array()
        .unwrap()
        .iter()
        .map(|d| d["kind"].as_str().unwrap())
        .collect();
    assert!(kinds.contains(&"duplicate"), "kinds: {kinds:?}");
    assert!(kinds.contains(&"missing"), "kinds: {kinds:?}");
    // Each diagnostic carries the four common fields.
    for d in v.as_array().unwrap() {
        assert!(d["index"].is_number(), "{d}");
        assert!(d["entry"].is_string(), "{d}");
        assert!(d["severity"].is_string(), "{d}");
        assert!(d["kind"].is_string(), "{d}");
    }
}

#[test]
fn doctor_json_respects_include_filter() {
    let tmp = tempfile::tempdir().unwrap();
    let real = tmp.path().join("real");
    fs::create_dir_all(&real).unwrap();
    let absent = tmp.path().join("definitely_does_not_exist_xyz");
    let path = join_path(&[&real, &real, &absent]);
    // Same setup as the human-view filter test, but in JSON.
    let (code, stdout, _) = run_doctor_args(&path, &["--include", "duplicate", "--json"]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect(&stdout);
    let arr = v.as_array().unwrap();
    assert!(!arr.is_empty(), "expected at least one diagnostic");
    for d in arr {
        assert_eq!(
            d["kind"], "duplicate",
            "include filter should keep duplicate-only: {d}"
        );
    }
}

#[test]
fn doctor_warns_when_mise_shim_and_install_coexist() {
    // 0.0.11: doctor reads ConflictsWhenBothInPath from the merged
    // catalog. The built-in relation references mise_shims and
    // mise_installs source paths under $HOME, but the tests must
    // not depend on the runner's $HOME, so we pass an explicit
    // pathlint.toml that overrides those two sources to point at
    // the temp-dir layout the test creates. The built-in relation
    // (mise_activate_both) still fires because the relation table
    // is identified by source name, not path.
    let tmp = tempfile::tempdir().unwrap();
    let mise_root = tmp.path().join("mise");
    let shims = mise_root.join("shims");
    let installs_python = mise_root
        .join("installs")
        .join("python")
        .join("3.14")
        .join("bin");
    fs::create_dir_all(&shims).unwrap();
    fs::create_dir_all(&installs_python).unwrap();
    let installs_dir = mise_root.join("installs");

    let key = if cfg!(windows) { "windows" } else { "unix" };
    let body = format!(
        r#"
[source.mise_shims]
{key} = "{shims}"

[source.mise_installs]
{key} = "{installs}"
"#,
        shims = shims.display().to_string().replace('\\', "/"),
        installs = installs_dir.display().to_string().replace('\\', "/"),
    );
    let rules = tmp.path().join("pathlint.toml");
    fs::write(&rules, body).unwrap();

    let path = join_path(&[&shims, &installs_python]);
    let out = Command::new(BIN)
        .arg("--config")
        .arg(&rules)
        .arg("doctor")
        .env("PATH", &path)
        .env_remove("XDG_CONFIG_HOME")
        .output()
        .expect("failed to run pathlint binary");
    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
    assert_eq!(code, 0, "warn-only must exit 0; stderr: {stderr}");
    assert!(
        stdout.contains("mise activate exposes both shim and install layers"),
        "stdout: {stdout}"
    );
    // Both conflict groups should appear (0.0.11+: groups, not
    // shims/installs sections).
    assert!(stdout.contains("group #0:"), "stdout: {stdout}");
    assert!(stdout.contains("group #1:"), "stdout: {stdout}");
}

#[test]
fn doctor_include_accepts_user_defined_diagnostic() {
    // 0.0.13: a user [[relation]] kind = "conflicts_when_both_in_path"
    // declares an arbitrary diagnostic name; --include must accept
    // it instead of failing the typo check (Z17a-M2).
    let tmp = tempfile::tempdir().unwrap();
    let rules = tmp.path().join("pathlint.toml");
    fs::write(
        &rules,
        r#"
[[relation]]
kind = "conflicts_when_both_in_path"
sources = ["a", "b"]
diagnostic = "foo_overlap"
"#,
    )
    .unwrap();

    // Empty PATH so no built-in diagnostic fires either.
    let out = Command::new(BIN)
        .arg("--config")
        .arg(&rules)
        .arg("doctor")
        .arg("--include")
        .arg("foo_overlap")
        .env("PATH", "/usr/bin")
        .env_remove("XDG_CONFIG_HOME")
        .output()
        .expect("failed to run pathlint binary");
    let code = out.status.code().unwrap_or(-1);
    let stderr = String::from_utf8_lossy(&out.stderr);
    // Acceptance test: must NOT exit 2 (config error). The actual
    // doctor run might exit 0 (no match) or 1 (a match found); the
    // load-bearing assertion is "validate_filter_names did not
    // reject the name as unknown".
    assert_ne!(
        code, 2,
        "--include foo_overlap was rejected: stderr: {stderr}"
    );
    assert!(!stderr.contains("unknown doctor kind"), "stderr: {stderr}");
}

#[test]
fn doctor_include_still_rejects_unknown_typos() {
    // 0.0.13: even with user-defined diagnostics accepted, a name
    // that is neither built-in nor user-declared still fails.
    let tmp = tempfile::tempdir().unwrap();
    let rules = tmp.path().join("pathlint.toml");
    fs::write(&rules, "").unwrap();

    let out = Command::new(BIN)
        .arg("--config")
        .arg(&rules)
        .arg("doctor")
        .arg("--include")
        .arg("duplicat") // typo of "duplicate"
        .env("PATH", "/usr/bin")
        .env_remove("XDG_CONFIG_HOME")
        .output()
        .expect("failed to run pathlint binary");
    let code = out.status.code().unwrap_or(-1);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(code, 2, "stderr: {stderr}");
    assert!(stderr.contains("unknown doctor kind"), "stderr: {stderr}");
}