pathlint 0.0.27

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
//! Environment-variable expansion and slash normalization.
//!
//! Both `%VAR%` (Windows-style) and `$VAR` / `${VAR}` (POSIX-style) are
//! accepted on every OS so the same `pathlint.toml` works under
//! Windows pwsh, macOS bash, and Termux fish. Unresolved variables are
//! left verbatim — they simply fail to substring-match later.
//!
//! Slash normalization converts `\` to `/` so `mise\\shims` (TOML
//! literal) and `mise/shims` are equivalent for substring comparison.
//!
//! # Examples
//!
//! ```
//! use pathlint::expand;
//!
//! assert_eq!(expand::normalize("C:\\Users\\Me"), "c:/users/me");
//!
//! // Unresolved variables stay verbatim.
//! let raw = expand::expand_env("$THIS_VAR_DOES_NOT_EXIST_PROBABLY_XYZ/bin");
//! assert!(raw.contains("$THIS_VAR_DOES_NOT_EXIST_PROBABLY_XYZ") || raw.ends_with("/bin"));
//! ```

use std::env;

/// Expand `%VAR%`, `$VAR`, `${VAR}`, and a leading `~` against the
/// caller-supplied env lookup. Pure — every env reference is
/// resolved through `env_lookup`, never through the process
/// environment directly. `~` resolves through the closure too:
/// pathlint asks for `HOME` first, then `USERPROFILE`. Unresolved
/// variables are kept verbatim.
///
/// Production callers pass `|v| std::env::var(v).ok()` (which is
/// what [`expand_env`] does internally). Tests and lib embedders
/// pass a deterministic closure so the result is independent of
/// the host environment.
///
/// 0.0.23+: introduced as the injection-aware form. [`expand_env`]
/// is now a thin wrapper.
pub fn expand_env_with<V>(input: &str, env_lookup: V) -> String
where
    V: Fn(&str) -> Option<String>,
{
    let tilde = expand_tilde(input, &env_lookup);
    let dollar = expand_dollar(&tilde, &env_lookup);
    expand_percent(&dollar, &env_lookup)
}

/// Expand `%VAR%`, `$VAR`, `${VAR}`, and a leading `~` against the
/// process environment. Unresolved variables are kept verbatim.
///
/// 0.0.23+: thin wrapper over [`expand_env_with`] that reads the
/// live process env. The actual expansion logic lives in
/// `expand_env_with`; this entry point exists for callers (the lib
/// itself, doctests, and embedders happy to read the host env)
/// who don't need to inject a custom lookup.
pub fn expand_env(input: &str) -> String {
    expand_env_with(input, |v| env::var(v).ok())
}

/// Lowercase + slash-normalize. Use on both haystack and needle before
/// substring comparison.
pub fn normalize(input: &str) -> String {
    input.replace('\\', "/").to_ascii_lowercase()
}

/// Expand env vars then normalize, against a caller-supplied env
/// lookup. Pure — every env reference goes through `env_lookup`,
/// never through the process environment directly.
///
/// 0.0.26+: the injection-aware form. [`expand_and_normalize`] is
/// now a thin wrapper. Production callers that don't need a
/// custom oracle pass `|v| std::env::var(v).ok()`; lib embedders
/// and tests pass deterministic closures so behaviour is
/// independent of the host environment. The internal
/// `source_match::find_with` / `validate_sources_with` /
/// `names_only_with` entry points thread the closure all the way
/// through, so an embedder can resolve catalog source paths
/// without ever touching `std::env`.
pub fn expand_and_normalize_with<V>(input: &str, env_lookup: V) -> String
where
    V: Fn(&str) -> Option<String>,
{
    normalize(&expand_env_with(input, env_lookup))
}

/// Convenience: expand env vars then normalize.
///
/// 0.0.26+: thin wrapper over [`expand_and_normalize_with`] that
/// reads the live process env. The actual expansion-then-normalize
/// logic lives in `expand_and_normalize_with`; this entry point
/// exists for callers (the lib's own internal callers, doctests,
/// and embedders happy to read the host env) who don't need to
/// inject a custom lookup.
pub fn expand_and_normalize(input: &str) -> String {
    expand_and_normalize_with(input, |v| env::var(v).ok())
}

/// Read PATHEXT and split into the literal extension tokens
/// (`.EXE`, `.BAT`, …). Defaults to the standard Windows list when
/// PATHEXT is unset. Caller passes its own env lookup so tests
/// can stub it; pass `|v| std::env::var(v).ok()` for production.
/// Use `pathext_lower` instead when case-insensitive comparison
/// is needed (the doctor `duplicate_but_shadowed` detector).
pub(crate) fn pathext_raw(env_lookup: impl Fn(&str) -> Option<String>) -> Vec<String> {
    env_lookup("PATHEXT")
        .unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC".to_string())
        .split(';')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}

/// PATHEXT entries lowercase. Convenience for case-insensitive
/// suffix matching on Windows.
pub(crate) fn pathext_lower(env_lookup: impl Fn(&str) -> Option<String>) -> Vec<String> {
    pathext_raw(env_lookup)
        .into_iter()
        .map(|s| s.to_ascii_lowercase())
        .collect()
}

fn expand_tilde<V>(s: &str, env_lookup: &V) -> String
where
    V: Fn(&str) -> Option<String>,
{
    if let Some(rest) = s.strip_prefix('~') {
        if let Some(home) = env_lookup("HOME") {
            return format!("{home}{rest}");
        }
        if let Some(profile) = env_lookup("USERPROFILE") {
            return format!("{profile}{rest}");
        }
    }
    s.to_string()
}

fn expand_dollar<V>(s: &str, env_lookup: &V) -> String
where
    V: Fn(&str) -> Option<String>,
{
    let mut out = String::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'$' && i + 1 < bytes.len() {
            if bytes[i + 1] == b'{' {
                if let Some(end) = s[i + 2..].find('}') {
                    let name = &s[i + 2..i + 2 + end];
                    match env_lookup(name) {
                        Some(val) => out.push_str(&val),
                        None => out.push_str(&s[i..i + 2 + end + 1]),
                    }
                    i += 2 + end + 1;
                    continue;
                }
            } else if is_ident_start(bytes[i + 1]) {
                let mut j = i + 1;
                while j < bytes.len() && is_ident_cont(bytes[j]) {
                    j += 1;
                }
                let name = &s[i + 1..j];
                match env_lookup(name) {
                    Some(val) => out.push_str(&val),
                    None => out.push_str(&s[i..j]),
                }
                i = j;
                continue;
            }
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

fn expand_percent<V>(s: &str, env_lookup: &V) -> String
where
    V: Fn(&str) -> Option<String>,
{
    let mut out = String::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if let Some(rel_end) = s[i + 1..].find('%') {
                let name = &s[i + 1..i + 1 + rel_end];
                if !name.is_empty() && name.chars().all(is_ident_char) {
                    match env_lookup(name) {
                        Some(val) => out.push_str(&val),
                        None => out.push_str(&s[i..i + 1 + rel_end + 1]),
                    }
                    i += 1 + rel_end + 1;
                    continue;
                }
            }
        }
        out.push(bytes[i] as char);
        i += 1;
    }
    out
}

fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

fn is_ident_cont(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

#[cfg(test)]
mod tests {
    use super::*;

    fn with_var<F: FnOnce()>(key: &str, value: &str, body: F) {
        // Tests that touch process env vars must not run in parallel.
        // cargo test by default parallelizes; callers should use a unique
        // var name per test to avoid cross-test interference.
        // SAFETY: single-threaded scope per unique variable name.
        unsafe { env::set_var(key, value) };
        body();
        unsafe { env::remove_var(key) };
    }

    #[test]
    fn dollar_brace_expansion() {
        with_var("PATHLINT_TEST_BRACE", "ok", || {
            assert_eq!(expand_env("a/${PATHLINT_TEST_BRACE}/b"), "a/ok/b");
        });
    }

    #[test]
    fn dollar_bare_expansion() {
        with_var("PATHLINT_TEST_BARE", "ok", || {
            assert_eq!(expand_env("a/$PATHLINT_TEST_BARE/b"), "a/ok/b");
        });
    }

    #[test]
    fn percent_expansion() {
        with_var("PATHLINT_TEST_PCT", "ok", || {
            assert_eq!(expand_env("a/%PATHLINT_TEST_PCT%/b"), "a/ok/b");
        });
    }

    #[test]
    fn missing_var_is_kept_verbatim() {
        // Use a name that is exceedingly unlikely to be set.
        let s = "x/$PATHLINT_NOT_DEFINED_XYZ/y";
        assert_eq!(expand_env(s), s);
        let s2 = "x/%PATHLINT_NOT_DEFINED_XYZ%/y";
        assert_eq!(expand_env(s2), s2);
    }

    #[test]
    fn normalize_lowers_and_unifies_slashes() {
        assert_eq!(normalize("Foo\\Bar/Baz"), "foo/bar/baz");
    }

    #[test]
    fn lone_dollar_is_literal() {
        assert_eq!(expand_env("a$/b"), "a$/b");
    }

    #[test]
    fn mixed_percent_and_dollar_in_one_string() {
        with_var("PATHLINT_TEST_MIX_A", "AA", || {
            with_var("PATHLINT_TEST_MIX_B", "BB", || {
                let s = "%PATHLINT_TEST_MIX_A%/$PATHLINT_TEST_MIX_B/x";
                assert_eq!(expand_env(s), "AA/BB/x");
            });
        });
    }

    #[test]
    fn empty_input_is_empty() {
        assert_eq!(expand_env(""), "");
        assert_eq!(normalize(""), "");
    }

    #[test]
    fn unclosed_brace_is_kept_verbatim() {
        // `${FOO` (no closing brace) must not crash and must be left
        // alone.
        let s = "abc/${FOO/def";
        assert_eq!(expand_env(s), s);
    }

    #[test]
    fn percent_with_non_ident_inside_is_left_alone() {
        // `%not an ident%` is not a valid env-var name, must stay literal.
        let s = "50% off";
        assert_eq!(expand_env(s), s);
    }

    #[test]
    fn expand_and_normalize_combines_both_steps() {
        with_var("PATHLINT_TEST_COMBO", "C:/Users/U", || {
            assert_eq!(
                expand_and_normalize("$PATHLINT_TEST_COMBO\\.cargo\\bin"),
                "c:/users/u/.cargo/bin",
            );
        });
    }

    #[test]
    fn pathext_raw_uses_user_value_when_set() {
        let raw = pathext_raw(|v| {
            if v == "PATHEXT" {
                Some(".EXE;.BAT".to_string())
            } else {
                None
            }
        });
        assert_eq!(raw, vec![".EXE".to_string(), ".BAT".to_string()]);
    }

    #[test]
    fn pathext_raw_falls_back_to_default_when_unset() {
        let raw = pathext_raw(|_| None);
        assert!(raw.contains(&".EXE".to_string()));
        assert!(raw.contains(&".CMD".to_string()));
    }

    #[test]
    fn pathext_lower_normalizes_case() {
        let lower = pathext_lower(|v| {
            if v == "PATHEXT" {
                Some(".EXE;.Bat".to_string())
            } else {
                None
            }
        });
        assert_eq!(lower, vec![".exe".to_string(), ".bat".to_string()]);
    }

    // ---- 0.0.23: env_lookup injection through expand_env_with --------

    #[test]
    fn expand_env_with_calls_lookup_for_dollar_var() {
        // The injected closure is the only env source — process env
        // is not consulted. Pin both the call shape and that
        // unresolved tails stay verbatim.
        let out = expand_env_with("/x/$FOO/bin", |k| {
            (k == "FOO").then(|| "/replaced".to_string())
        });
        assert_eq!(out, "/x//replaced/bin");
    }

    #[test]
    fn expand_env_with_keeps_unresolved_var_verbatim() {
        let out = expand_env_with(
            "/x/$DEFINITELY_NOT_DEFINED_XYZ/bin",
            |_| -> Option<String> { None },
        );
        assert_eq!(out, "/x/$DEFINITELY_NOT_DEFINED_XYZ/bin");
    }

    #[test]
    fn expand_env_with_does_not_touch_process_env() {
        // Set a process env var that the closure does NOT report,
        // and confirm the result keeps the variable verbatim — the
        // closure is the only oracle expand_env_with consults.
        with_var("PATHLINT_TEST_INJECTION_LEAK", "leaked", || {
            let out = expand_env_with("x/$PATHLINT_TEST_INJECTION_LEAK/y", |_| -> Option<String> {
                None
            });
            assert_eq!(out, "x/$PATHLINT_TEST_INJECTION_LEAK/y");
        });
    }

    #[test]
    fn expand_env_with_handles_percent_and_brace_through_lookup() {
        let lookup = |k: &str| match k {
            "A" => Some("AA".to_string()),
            "B" => Some("BB".to_string()),
            _ => None,
        };
        assert_eq!(expand_env_with("%A%/${B}/c", lookup), "AA/BB/c");
    }

    // ---- 0.0.26: expand_and_normalize_with closure injection -------

    /// 0.0.26: pin that `expand_and_normalize_with` runs the input
    /// through `expand_env_with` (so `$VAR` resolves through the
    /// closure) and then through `normalize` (so backslashes flip
    /// to forward slashes and ASCII letters lowercase).
    #[test]
    fn expand_and_normalize_with_uses_closure_only() {
        let lookup = |k: &str| (k == "ROOT").then(|| "/Var".to_string());
        let out = expand_and_normalize_with(r"$ROOT\BIN", lookup);
        assert_eq!(out, "/var/bin");
    }

    /// 0.0.26: pin that `expand_and_normalize_with` does *not*
    /// fall back to the live process env when the closure says
    /// `None`. Without this guard the wrapper-vs-non-wrapper
    /// distinction collapses.
    #[test]
    fn expand_and_normalize_with_does_not_leak_process_env() {
        with_var("PATHLINT_TEST_NORMALIZE_LEAK", "leaked", || {
            let out = expand_and_normalize_with(
                "$PATHLINT_TEST_NORMALIZE_LEAK/x",
                |_| -> Option<String> { None },
            );
            // Closure returned None, so the variable stays verbatim
            // through expand_env_with and only normalize touches it.
            assert_eq!(out, "$pathlint_test_normalize_leak/x");
        });
    }
}