pathlint 0.0.10

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
//! Built-in source catalog and merge with user-defined sources.

use std::collections::BTreeMap;
use std::sync::OnceLock;

use crate::config::{Config, Relation, SourceDef};

// Generated by build.rs from plugins/*.toml. The plugin TOMLs
// are the source of truth; do not edit the generated file.
const EMBEDDED: &str = include_str!(concat!(env!("OUT_DIR"), "/embedded_catalog.toml"));

/// Parse the embedded catalog once and reuse the result. The TOML
/// is constant for the lifetime of the process, so the three
/// public read functions below all share a single parse.
fn embedded() -> &'static Config {
    static CACHE: OnceLock<Config> = OnceLock::new();
    CACHE.get_or_init(|| Config::parse_toml(EMBEDDED).expect("embedded_catalog.toml must parse"))
}

/// Built-in source catalog. Cloned out of the cached `Config` so
/// callers can mutate the result (e.g. merge user overrides) without
/// affecting the singleton.
pub fn builtin() -> BTreeMap<String, SourceDef> {
    embedded().source.clone()
}

/// Version of the catalog embedded in this binary. Bumped whenever
/// an existing source's path or semantics changes. Defaults to `0`
/// if the embedded file forgets to declare one (which would be a
/// build bug caught at code review).
pub fn embedded_version() -> u32 {
    embedded().catalog_version.unwrap_or(0)
}

/// Pure compatibility check: does this binary's embedded catalog
/// satisfy the user's `require_catalog` directive? `Ok(())` means
/// either no requirement was set or the embedded version meets or
/// exceeds it. `Err` carries a one-line user-facing message naming
/// both versions and the recommended fix.
///
/// Pure: no I/O, no globals — both versions are passed in. Unit-
/// testable without touching the embedded catalog or stderr.
pub fn version_check(require_catalog: Option<u32>, embedded: u32) -> Result<(), String> {
    let Some(required) = require_catalog else {
        return Ok(());
    };
    if embedded >= required {
        return Ok(());
    }
    Err(format!(
        "rules require catalog_version >= {required}, but this binary embeds version {embedded}. \
         Upgrade pathlint or lower require_catalog."
    ))
}

/// Merge user-defined sources on top of the built-in catalog. User
/// entries with the same name override field-by-field; new names are
/// added.
pub fn merge_with_user(user: &BTreeMap<String, SourceDef>) -> BTreeMap<String, SourceDef> {
    let mut out = builtin();
    for (name, user_def) in user {
        let merged = match out.get(name) {
            Some(existing) => existing.merge(user_def),
            None => user_def.clone(),
        };
        out.insert(name.clone(), merged);
    }
    out
}

/// Built-in relations declared by `plugins/<name>.toml`. Returned
/// in the order they appear in the embedded catalog (which is the
/// order set by `plugins/_index.toml`).
pub fn builtin_relations() -> Vec<Relation> {
    embedded().relations.clone()
}

/// Combined relation list: built-ins followed by anything the user
/// declared in their `pathlint.toml`. No deduplication — declaring
/// the same relation twice is harmless and the user's intent should
/// not be silently dropped.
pub fn merge_with_user_relations(user: &[Relation]) -> Vec<Relation> {
    let mut out = builtin_relations();
    out.extend(user.iter().cloned());
    out
}

/// Verify that relations forming a directed acyclic graph (DAG)
/// actually do. Today this checks `served_by_via` (host →
/// guest_provider) and `depends_on` (source → target). Other kinds
/// (`alias_of`, `conflicts_when_both_in_path`) are symmetric and
/// have no direction; they are ignored here.
///
/// Pure: takes a relation slice, returns `Err(message)` listing the
/// cycle on first detection. The expensive case is rare (relations
/// are at most a few dozen), so a straightforward visited-set DFS
/// is plenty.
pub fn check_acyclic(relations: &[Relation]) -> Result<(), String> {
    use std::collections::BTreeSet;

    let mut edges: Vec<(String, String)> = Vec::new();
    for rel in relations {
        match rel {
            Relation::ServedByVia {
                host,
                guest_provider,
                ..
            } => edges.push((host.clone(), guest_provider.clone())),
            Relation::DependsOn { source, target } => edges.push((source.clone(), target.clone())),
            Relation::PreferOrderOver { earlier, later } => {
                edges.push((earlier.clone(), later.clone()))
            }
            // alias_of / conflicts_when_both_in_path: symmetric / set
            // semantics, no direction to check.
            _ => {}
        }
    }
    let mut adj: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (from, to) in &edges {
        adj.entry(from.clone()).or_default().push(to.clone());
    }

    // White / gray / black DFS for cycle detection.
    let mut color: BTreeMap<String, u8> = BTreeMap::new();
    fn visit(
        node: &str,
        adj: &BTreeMap<String, Vec<String>>,
        color: &mut BTreeMap<String, u8>,
        stack: &mut Vec<String>,
    ) -> Result<(), String> {
        let entry = color.entry(node.to_string()).or_insert(0);
        match *entry {
            1 => {
                // gray — back edge → cycle.
                let cycle_start = stack.iter().position(|n| n == node).unwrap_or(0);
                let mut cycle = stack[cycle_start..].join(" -> ");
                cycle.push_str(&format!(" -> {node}"));
                return Err(format!("relation cycle: {cycle}"));
            }
            2 => return Ok(()), // already finished
            _ => {}
        }
        *entry = 1;
        stack.push(node.to_string());
        let neighbours: Vec<String> = adj.get(node).cloned().unwrap_or_default();
        for next in neighbours {
            visit(&next, adj, color, stack)?;
        }
        stack.pop();
        color.insert(node.to_string(), 2);
        Ok(())
    }

    let nodes: BTreeSet<String> = edges
        .iter()
        .flat_map(|(a, b)| [a.clone(), b.clone()])
        .collect();
    for node in &nodes {
        let mut stack = Vec::new();
        visit(node, &adj, &mut color, &mut stack)?;
    }
    Ok(())
}

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

    #[test]
    fn embedded_catalog_parses() {
        let cat = builtin();
        assert!(cat.contains_key("cargo"));
        assert!(cat.contains_key("winget"));
        assert!(cat.contains_key("brew_arm"));
        assert!(cat.contains_key("pkg"));
    }

    #[test]
    fn cargo_has_per_os_paths() {
        let cat = builtin();
        let cargo = &cat["cargo"];
        assert!(cargo.path_for(Os::Windows).is_some());
        assert!(cargo.path_for(Os::Linux).is_some());
        assert!(cargo.path_for(Os::Macos).is_some());
        assert!(cargo.path_for(Os::Termux).is_some()); // unix fallback
    }

    #[test]
    fn user_override_replaces_only_specified_field() {
        let mut user = BTreeMap::new();
        user.insert(
            "mise".to_string(),
            SourceDef {
                windows: Some("D:/tools/mise".into()),
                ..Default::default()
            },
        );
        let merged = merge_with_user(&user);
        let mise = &merged["mise"];
        assert_eq!(mise.path_for(Os::Windows), Some("D:/tools/mise"));
        // unix fallback from the built-in survives.
        assert!(mise.path_for(Os::Linux).is_some());
    }

    #[test]
    fn user_can_add_new_source() {
        let mut user = BTreeMap::new();
        user.insert(
            "my_dotfiles_bin".to_string(),
            SourceDef {
                unix: Some("$HOME/dotfiles/bin".into()),
                ..Default::default()
            },
        );
        let merged = merge_with_user(&user);
        assert!(merged.contains_key("my_dotfiles_bin"));
    }

    #[test]
    fn linux_only_source_is_none_on_windows() {
        let cat = builtin();
        let apt = &cat["apt"];
        assert!(apt.path_for(Os::Linux).is_some());
        assert!(apt.path_for(Os::Windows).is_none());
        assert!(apt.path_for(Os::Macos).is_none());
        assert!(apt.path_for(Os::Termux).is_none());
    }

    #[test]
    fn user_override_can_replace_all_known_fields() {
        let mut user = BTreeMap::new();
        user.insert(
            "cargo".to_string(),
            SourceDef {
                description: Some("user-overridden".into()),
                windows: Some("X:/cargo".into()),
                unix: Some("/x/cargo".into()),
                ..Default::default()
            },
        );
        let merged = merge_with_user(&user);
        let cargo = &merged["cargo"];
        assert_eq!(cargo.description.as_deref(), Some("user-overridden"));
        assert_eq!(cargo.path_for(Os::Windows), Some("X:/cargo"));
        assert_eq!(cargo.path_for(Os::Linux), Some("/x/cargo"));
    }

    #[test]
    fn embedded_version_is_at_least_one() {
        // Bumping catalog_version is a deliberate act; default of 0
        // would mean somebody removed the declaration. Guard the
        // floor at 1 — the version we shipped in 0.0.3.
        assert!(embedded_version() >= 1);
    }

    #[test]
    fn version_check_passes_when_no_requirement_set() {
        assert!(version_check(None, 0).is_ok());
        assert!(version_check(None, 9999).is_ok());
    }

    #[test]
    fn version_check_passes_when_embedded_meets_required() {
        assert!(version_check(Some(2), 2).is_ok());
        assert!(version_check(Some(2), 3).is_ok());
    }

    #[test]
    fn version_check_fails_when_embedded_below_required() {
        let err = version_check(Some(7), 3).unwrap_err();
        assert!(err.contains("7"), "error must name required: {err}");
        assert!(err.contains("3"), "error must name embedded: {err}");
        assert!(
            err.contains("Upgrade") || err.contains("require_catalog"),
            "error must hint at fix: {err}"
        );
    }

    #[test]
    fn mise_layered_sources_are_present() {
        let cat = builtin();
        assert!(cat.contains_key("mise"));
        assert!(cat.contains_key("mise_shims"));
        assert!(cat.contains_key("mise_installs"));
    }

    #[test]
    fn builtin_relations_includes_mise_alias_and_conflict() {
        let rels = builtin_relations();
        // Catalog declares at least the mise alias_of and the
        // mise_activate_both conflict.
        assert!(
            rels.iter().any(|r| matches!(
                r,
                Relation::AliasOf { parent, .. } if parent == "mise"
            )),
            "alias_of mise missing: {rels:?}"
        );
        assert!(
            rels.iter().any(|r| matches!(
                r,
                Relation::ConflictsWhenBothInPath { diagnostic, .. }
                    if diagnostic == "mise_activate_both"
            )),
            "mise_activate_both conflict missing: {rels:?}"
        );
    }

    #[test]
    fn merge_user_relations_appends_after_builtin() {
        let user = vec![Relation::DependsOn {
            source: "paru".into(),
            target: "pacman".into(),
        }];
        let merged = merge_with_user_relations(&user);
        // user relation must be at the end.
        let last = merged.last().unwrap();
        assert!(matches!(
            last,
            Relation::DependsOn { source, target }
                if source == "paru" && target == "pacman"
        ));
    }

    #[test]
    fn check_acyclic_accepts_simple_chain() {
        let rels = vec![
            Relation::DependsOn {
                source: "a".into(),
                target: "b".into(),
            },
            Relation::DependsOn {
                source: "b".into(),
                target: "c".into(),
            },
        ];
        assert!(check_acyclic(&rels).is_ok());
    }

    #[test]
    fn check_acyclic_rejects_two_node_cycle() {
        let rels = vec![
            Relation::DependsOn {
                source: "a".into(),
                target: "b".into(),
            },
            Relation::DependsOn {
                source: "b".into(),
                target: "a".into(),
            },
        ];
        let err = check_acyclic(&rels).unwrap_err();
        assert!(err.contains("cycle"), "{err}");
    }

    #[test]
    fn check_acyclic_rejects_three_node_cycle_through_served_by_via() {
        let rels = vec![
            Relation::ServedByVia {
                host: "a".into(),
                guest_pattern: "*".into(),
                guest_provider: "b".into(),
                installer_token: None,
            },
            Relation::ServedByVia {
                host: "b".into(),
                guest_pattern: "*".into(),
                guest_provider: "c".into(),
                installer_token: None,
            },
            Relation::ServedByVia {
                host: "c".into(),
                guest_pattern: "*".into(),
                guest_provider: "a".into(),
                installer_token: None,
            },
        ];
        assert!(check_acyclic(&rels).is_err());
    }

    #[test]
    fn check_acyclic_rejects_cycle_through_prefer_order_over() {
        let rels = vec![
            Relation::PreferOrderOver {
                earlier: "a".into(),
                later: "b".into(),
            },
            Relation::PreferOrderOver {
                earlier: "b".into(),
                later: "a".into(),
            },
        ];
        assert!(check_acyclic(&rels).is_err());
    }

    #[test]
    fn check_acyclic_ignores_alias_of_and_conflicts() {
        // These kinds have no direction; even self-referential
        // shape (parent == child) does not count as a cycle here.
        let rels = vec![
            Relation::AliasOf {
                parent: "a".into(),
                children: vec!["a".into(), "b".into()],
            },
            Relation::ConflictsWhenBothInPath {
                sources: vec!["a".into(), "b".into()],
                diagnostic: "x".into(),
            },
        ];
        assert!(check_acyclic(&rels).is_ok());
    }

    #[test]
    fn builtin_relations_form_a_dag() {
        // The catalog itself must not contain cycles. Guard against
        // a future plugin author accidentally introducing one.
        check_acyclic(&builtin_relations()).expect("built-in relations must be acyclic");
    }

    #[test]
    fn mise_shims_path_is_a_subdirectory_of_mise() {
        let cat = builtin();
        let mise = cat["mise"].path_for(Os::Linux).unwrap();
        let shims = cat["mise_shims"].path_for(Os::Linux).unwrap();
        let installs = cat["mise_installs"].path_for(Os::Linux).unwrap();
        // mise_shims and mise_installs must each live inside the
        // mise root, so any binary path that matches a subordinate
        // source automatically also matches the parent `mise`.
        assert!(shims.starts_with(mise), "{shims} not under {mise}");
        assert!(installs.starts_with(mise), "{installs} not under {mise}");
    }
}