alint-rules 0.10.1

Internal: built-in rule implementations for alint. Not a stable public API.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! `registry_paths_resolve` — a manifest file enumerates
//! path-like entries; each must resolve to an on-disk artefact.
//! Optional reverse "orphan" check: on-disk artefacts in a
//! declared space that no entry references.
//!
//! Cross-file: reads one manifest and resolves its entries
//! against the engine `FileIndex` (O(1) per entry via the lazy
//! path-set). Design + rationale + open-question resolutions:
//! `docs/design/v0.10/registry_paths_resolve.md`.
//!
//! ```yaml
//! - id: cargo-workspace-members-resolve
//!   kind: registry_paths_resolve
//!   source: Cargo.toml
//!   extract: { toml: "$.workspace.members[*]" }
//!   base: registry_dir          # registry_dir (default) | lint_root | "<path>"
//!   entries_are_globs: true
//!   expect: dir                 # any (default) | file | dir
//!   must_contain: Cargo.toml
//!   exclude_query: "$.workspace.exclude[*]"
//!   orphans: { space: "crates/*", unreferenced: warn }
//!   level: error
//! ```

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
use regex::Regex;
use serde::Deserialize;

use crate::extract::{Extract, ExtractSpec, extract_values, is_non_literal};

#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Expect {
    #[default]
    Any,
    File,
    Dir,
}

#[derive(Debug, Clone, Copy, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum Severity {
    #[default]
    Warn,
    Error,
    Off,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct OrphansSpec {
    /// Glob of on-disk artefacts that should each be referenced.
    space: String,
    #[serde(default)]
    unreferenced: Severity,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Options {
    source: String,
    extract: ExtractSpec,
    #[serde(default)]
    base: Option<String>,
    #[serde(default)]
    entries_are_globs: bool,
    #[serde(default)]
    expect: Expect,
    #[serde(default)]
    must_contain: Option<String>,
    #[serde(default)]
    exclude_query: Option<String>,
    #[serde(default)]
    orphans: Option<OrphansSpec>,
}

/// Resolution base for entries.
#[derive(Debug, Clone)]
enum Base {
    /// Directory containing the registry file (default; matches
    /// Cargo / npm semantics + alint's nested-manifest model).
    RegistryDir,
    /// The lint root.
    LintRoot,
    /// An explicit path, relative to the lint root.
    Explicit(PathBuf),
}

impl Base {
    fn parse(raw: Option<&str>) -> Self {
        match raw {
            None | Some("registry_dir") => Self::RegistryDir,
            Some("lint_root") => Self::LintRoot,
            Some(p) => Self::Explicit(PathBuf::from(p)),
        }
    }
}

#[derive(Debug)]
pub struct RegistryPathsResolveRule {
    id: String,
    level: Level,
    policy_url: Option<String>,
    message: Option<String>,
    source: String,
    registry_scope: Option<Scope>,
    extract: Extract,
    base: Base,
    entries_are_globs: bool,
    expect: Expect,
    must_contain: Option<String>,
    exclude_query: Option<String>,
    orphans: Option<OrphansSpec>,
}

impl Rule for RegistryPathsResolveRule {
    alint_core::rule_common_impl!();

    fn requires_full_index(&self) -> bool {
        // Cross-file: an entry's verdict depends on whether its
        // target exists anywhere in the tree, and the orphan
        // check needs the whole index — never `--changed`-scoped.
        true
    }

    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
        let mut violations = Vec::new();

        // Directory existence: build the dir path-set once per
        // eval (O(D)); per-entry lookups are then O(1), matching
        // `contains_file`'s scaling so the rule stays index-fast.
        let dir_set: HashSet<&Path> = if self.expect == Expect::Dir
            || self.expect == Expect::Any
            || self.must_contain.is_some()
        {
            ctx.index.dirs().map(|e| &*e.path).collect()
        } else {
            HashSet::new()
        };

        for registry_rel in self.registry_files(ctx) {
            let abs = ctx.root.join(&registry_rel);
            let text = match crate::io::read_capped(&abs) {
                Ok(b) => String::from_utf8_lossy(&b).into_owned(),
                Err(e) => {
                    let why = match e {
                        crate::io::ReadCapError::TooLarge(n) => {
                            format!("is too large to analyze ({n} bytes; 256 MiB cap)")
                        }
                        crate::io::ReadCapError::Io(e) => {
                            format!("could not be read: {e}")
                        }
                    };
                    violations.push(
                        Violation::new(format!("registry file {} {why}", registry_rel.display()))
                            .with_path(registry_rel.clone()),
                    );
                    continue;
                }
            };

            let (entries, skipped) = match self.extract_entries(&text) {
                Ok(v) => v,
                Err(e) => {
                    violations.push(
                        Violation::new(format!(
                            "registry file {} could not be parsed for `extract`: {e}",
                            registry_rel.display()
                        ))
                        .with_path(registry_rel.clone()),
                    );
                    continue;
                }
            };
            // Non-literal (computed/interpolated) entries are
            // intentionally skipped, not failed. The skip is
            // silent in v0.10 — `alint check` has no
            // informational-finding / `--explain` channel;
            // visibly surfacing the skip list is a tracked
            // v0.11 item (see the design doc).
            let _ = skipped;

            let excluded = self.excluded_entries(&text);
            let base_dir = self.base_dir(&registry_rel);

            let mut covered: Vec<PathBuf> = Vec::new();
            for entry in &entries {
                if excluded.contains(entry) {
                    continue;
                }
                let resolved = normalise(&base_dir.join(entry));
                if self.entries_are_globs {
                    let matches = Self::glob_matches(ctx, &resolved);
                    if matches.is_empty() {
                        violations.push(self.violation(
                            &registry_rel,
                            entry,
                            "matched no path on disk",
                        ));
                    } else {
                        covered.extend(matches);
                    }
                    continue;
                }
                covered.push(resolved.clone());
                if let Some(reason) = self.existence_problem(ctx, &resolved, &dir_set) {
                    violations.push(self.violation(&registry_rel, entry, &reason));
                }
            }

            // Globbed entries still need existence/kind checks on
            // each expansion (a `crates/*` match must satisfy
            // `must_contain`, etc.).
            if self.entries_are_globs {
                for p in &covered {
                    if let Some(reason) = self.existence_problem(ctx, p, &dir_set) {
                        violations.push(self.violation(
                            &registry_rel,
                            &p.display().to_string(),
                            &reason,
                        ));
                    }
                }
            }

            self.check_orphans(ctx, &registry_rel, &covered, &mut violations);
        }

        Ok(violations)
    }
}

impl RegistryPathsResolveRule {
    /// The registry file(s): a literal path, or every index path
    /// matching the glob.
    fn registry_files(&self, ctx: &Context<'_>) -> Vec<PathBuf> {
        match &self.registry_scope {
            None => vec![PathBuf::from(&self.source)],
            Some(scope) => ctx
                .index
                .files()
                .filter(|e| scope.matches(&e.path, ctx.index))
                .map(|e| e.path.to_path_buf())
                .collect(),
        }
    }

    fn base_dir(&self, registry_rel: &Path) -> PathBuf {
        match &self.base {
            Base::RegistryDir => registry_rel
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_default(),
            Base::LintRoot => PathBuf::new(),
            Base::Explicit(p) => p.clone(),
        }
    }

    fn extract_entries(&self, text: &str) -> std::result::Result<(Vec<String>, usize), String> {
        let raw = extract_values(&self.extract, text)?;
        let before = raw.len();
        let kept: Vec<String> = raw.into_iter().filter(|e| !is_non_literal(e)).collect();
        let skipped = before - kept.len();
        Ok((kept, skipped))
    }

    fn excluded_entries(&self, text: &str) -> HashSet<String> {
        let Some(q) = &self.exclude_query else {
            return HashSet::new();
        };
        // exclude_query is a structured query; for line/regex
        // registries it has no meaning, so fall back to a TOML
        // read (a misconfig surfaces as an empty set, not a panic).
        let ex = match &self.extract {
            Extract::Json(_) => Extract::Json(q.clone()),
            Extract::Yaml(_) => Extract::Yaml(q.clone()),
            _ => Extract::Toml(q.clone()),
        };
        extract_values(&ex, text)
            .map(|v| v.into_iter().collect())
            .unwrap_or_default()
    }

    /// Reverse-completeness: on-disk artefacts under `orphans.space`
    /// that no (post-expansion) entry covered.
    fn check_orphans(
        &self,
        ctx: &Context<'_>,
        registry_rel: &Path,
        covered: &[PathBuf],
        out: &mut Vec<Violation>,
    ) {
        let Some(orph) = &self.orphans else {
            return;
        };
        if orph.unreferenced == Severity::Off {
            return;
        }
        let covered_set: HashSet<&Path> = covered.iter().map(PathBuf::as_path).collect();
        let Ok(space) = Scope::from_patterns(std::slice::from_ref(&orph.space)) else {
            return;
        };
        for e in ctx.index.files() {
            if space.matches(&e.path, ctx.index) && !covered_set.contains(&*e.path) {
                out.push(
                    Violation::new(format!(
                        "{} is under `{}` but no entry in {} references it",
                        e.path.display(),
                        orph.space,
                        registry_rel.display(),
                    ))
                    .with_path(e.path.clone()),
                );
            }
        }
    }

    fn glob_matches(ctx: &Context<'_>, pattern: &Path) -> Vec<PathBuf> {
        let pat = pattern.to_string_lossy().into_owned();
        let Ok(scope) = Scope::from_patterns(&[pat]) else {
            return Vec::new();
        };
        ctx.index
            .files()
            .filter(|e| scope.matches(&e.path, ctx.index))
            .map(|e| e.path.to_path_buf())
            .chain(
                ctx.index
                    .dirs()
                    .filter(|e| scope.matches(&e.path, ctx.index))
                    .map(|e| e.path.to_path_buf()),
            )
            .collect()
    }

    /// `None` => the resolved path is fine. `Some(reason)` => a
    /// violation message fragment.
    fn existence_problem(
        &self,
        ctx: &Context<'_>,
        path: &Path,
        dir_set: &HashSet<&Path>,
    ) -> Option<String> {
        let is_file = ctx.index.contains_file(path);
        let is_dir = dir_set.contains(path);
        match self.expect {
            Expect::File => {
                if !is_file {
                    return Some("does not resolve to a file on disk".into());
                }
            }
            Expect::Dir => {
                if !is_dir {
                    return Some("does not resolve to a directory on disk".into());
                }
            }
            Expect::Any => {
                if !is_file && !is_dir {
                    return Some("does not resolve to any path on disk".into());
                }
            }
        }
        if let Some(mc) = &self.must_contain {
            // Only meaningful when the entry is a directory.
            if is_dir && !ctx.index.contains_file(&path.join(mc)) {
                return Some(format!("resolves to a directory missing `{mc}`"));
            }
        }
        None
    }

    fn violation(&self, registry: &Path, entry: &str, reason: &str) -> Violation {
        let msg = self
            .message
            .clone()
            .unwrap_or_else(|| format!("{}: entry {entry:?} {reason}", registry.display()));
        Violation::new(msg).with_path(registry.to_path_buf())
    }
}

/// Collapse `a/./b` and `a/b/../c` so index lookups (which key on
/// the walked relative path) match. Does not touch the
/// filesystem.
fn normalise(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for comp in p.components() {
        use std::path::Component::{CurDir, Normal, ParentDir, Prefix, RootDir};
        match comp {
            CurDir => {}
            ParentDir => {
                out.pop();
            }
            Normal(c) => out.push(c),
            RootDir | Prefix(_) => out.push(comp.as_os_str()),
        }
    }
    out
}

pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
    alint_core::reject_scope_filter_on_cross_file(spec, "registry_paths_resolve")?;
    let opts: Options = spec
        .deserialize_options()
        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;

    if opts.source.trim().is_empty() {
        return Err(Error::rule_config(
            &spec.id,
            "registry_paths_resolve `source` must not be empty",
        ));
    }
    // A glob source is resolved against the index; a literal one
    // is read directly. `is_glob` mirrors the structured-path /
    // file_exists literal test.
    let is_glob = opts
        .source
        .chars()
        .any(|c| matches!(c, '*' | '?' | '[' | ']' | '{' | '}'));
    let registry_scope = if is_glob {
        Some(
            Scope::from_patterns(std::slice::from_ref(&opts.source))
                .map_err(|e| Error::rule_config(&spec.id, format!("invalid `source` glob: {e}")))?,
        )
    } else {
        None
    };
    let extract = opts
        .extract
        .resolve()
        .map_err(|e| Error::rule_config(&spec.id, format!("invalid `extract`: {e}")))?;
    if let Extract::Regex(p) = &extract {
        Regex::new(p)
            .map_err(|e| Error::rule_config(&spec.id, format!("invalid `extract.regex`: {e}")))?;
    }

    Ok(Box::new(RegistryPathsResolveRule {
        id: spec.id.clone(),
        level: spec.level,
        policy_url: spec.policy_url.clone(),
        message: spec.message.clone(),
        source: opts.source,
        registry_scope,
        extract,
        base: Base::parse(opts.base.as_deref()),
        entries_are_globs: opts.entries_are_globs,
        expect: opts.expect,
        must_contain: opts.must_contain,
        exclude_query: opts.exclude_query,
        orphans: opts.orphans,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extract::LinesOpts;
    use alint_core::{FileEntry, FileIndex};

    fn index(files: &[&str], dirs: &[&str]) -> FileIndex {
        let mut e: Vec<FileEntry> = files
            .iter()
            .map(|p| FileEntry {
                path: Path::new(p).into(),
                is_dir: false,
                size: 1,
            })
            .collect();
        e.extend(dirs.iter().map(|p| FileEntry {
            path: Path::new(p).into(),
            is_dir: true,
            size: 0,
        }));
        FileIndex::from_entries(e)
    }

    fn rule(opts: Options) -> RegistryPathsResolveRule {
        RegistryPathsResolveRule {
            id: "t".into(),
            level: Level::Error,
            policy_url: None,
            message: None,
            source: opts.source,
            registry_scope: None,
            extract: opts.extract.resolve().expect("test extract valid"),
            base: Base::parse(opts.base.as_deref()),
            entries_are_globs: opts.entries_are_globs,
            expect: opts.expect,
            must_contain: opts.must_contain,
            exclude_query: opts.exclude_query,
            orphans: opts.orphans,
        }
    }

    fn opts(source: &str, extract: Extract) -> Options {
        Options {
            source: source.into(),
            extract: extract.into(),
            base: None,
            entries_are_globs: false,
            expect: Expect::Any,
            must_contain: None,
            exclude_query: None,
            orphans: None,
        }
    }

    fn eval(r: &RegistryPathsResolveRule, root: &Path, idx: &FileIndex) -> Vec<Violation> {
        let ctx = Context {
            root,
            index: idx,
            registry: None,
            facts: None,
            vars: None,
            git_tracked: None,
            git_blame: None,
        };
        r.evaluate(&ctx).unwrap()
    }

    #[test]
    fn lines_entries_resolve_pass_and_fail() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("MANIFEST"),
            "src/a.rs\nsrc/b.rs\n# a comment\n",
        )
        .unwrap();
        let r = rule(opts("MANIFEST", Extract::Lines(LinesOpts::default())));
        // Both present -> pass.
        let v = eval(
            &r,
            dir.path(),
            &index(&["src/a.rs", "src/b.rs", "MANIFEST"], &[]),
        );
        assert!(v.is_empty(), "{v:?}");
        // b.rs missing -> one violation.
        let v = eval(&r, dir.path(), &index(&["src/a.rs", "MANIFEST"], &[]));
        assert_eq!(v.len(), 1);
        assert!(v[0].message.contains("src/b.rs"));
    }

    #[test]
    fn toml_workspace_members_expect_dir_must_contain() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\n",
        )
        .unwrap();
        let mut o = opts("Cargo.toml", Extract::Toml("$.workspace.members[*]".into()));
        o.expect = Expect::Dir;
        o.must_contain = Some("Cargo.toml".into());
        let r = rule(o);
        // Both crate dirs exist and contain Cargo.toml -> pass.
        let idx = index(
            &[
                "crates/core/Cargo.toml",
                "crates/cli/Cargo.toml",
                "Cargo.toml",
            ],
            &["crates/core", "crates/cli"],
        );
        assert!(eval(&r, dir.path(), &idx).is_empty());
        // cli dir missing its Cargo.toml -> must_contain violation.
        let idx = index(
            &["crates/core/Cargo.toml", "Cargo.toml"],
            &["crates/core", "crates/cli"],
        );
        let v = eval(&r, dir.path(), &idx);
        assert_eq!(v.len(), 1, "{v:?}");
        assert!(v[0].message.contains("crates/cli"));
    }

    #[test]
    fn non_literal_entries_are_skipped_not_failed() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("pkgs.nix"),
            "callPackage ./pkgs/real {}\ncallPackage ${pkgs.x}/lib {}\n",
        )
        .unwrap();
        let r = rule(opts(
            "pkgs.nix",
            Extract::Regex(r"callPackage\s+(\S+)".into()),
        ));
        // Only the literal `./pkgs/real` is checked; the
        // genuinely interpolated `${pkgs.x}/lib` entry is
        // skipped (not a violation). Narrowed is_non_literal:
        // the captured token must carry a real `${`/`$(`/`{{`/
        // `+ ` marker — a bare `(.`/`$` no longer over-skips a
        // real literal path (v0.10 post-audit P2).
        let idx = index(&["pkgs.nix"], &["pkgs/real"]);
        let v = eval(&r, dir.path(), &idx);
        assert!(v.is_empty(), "non-literal must be skipped, got {v:?}");
    }

    #[test]
    fn entries_are_globs_zero_match_is_a_violation() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/*\"]\n",
        )
        .unwrap();
        let mut o = opts("Cargo.toml", Extract::Toml("$.workspace.members[*]".into()));
        o.entries_are_globs = true;
        let r = rule(o);
        // No crates/* on disk -> the glob matched nothing.
        let v = eval(&r, dir.path(), &index(&["Cargo.toml"], &[]));
        assert_eq!(v.len(), 1, "{v:?}");
        assert!(v[0].message.contains("no path"));
    }

    #[test]
    fn orphans_flags_unreferenced_dir() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/a\"]\n",
        )
        .unwrap();
        let mut o = opts("Cargo.toml", Extract::Toml("$.workspace.members[*]".into()));
        o.orphans = Some(OrphansSpec {
            space: "crates/*/Cargo.toml".into(),
            unreferenced: Severity::Error,
        });
        let r = rule(o);
        // crates/b exists on disk but isn't a member -> orphan.
        let idx = index(
            &["crates/a/Cargo.toml", "crates/b/Cargo.toml", "Cargo.toml"],
            &["crates/a", "crates/b"],
        );
        let v = eval(&r, dir.path(), &idx);
        assert!(
            v.iter().any(|x| x.message.contains("crates/b/Cargo.toml")),
            "expected crates/b flagged as orphan, got {v:?}"
        );
    }

    #[test]
    fn exclude_query_subtracts_before_checking() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"a\", \"b\"]\nexclude = [\"b\"]\n",
        )
        .unwrap();
        let mut o = opts("Cargo.toml", Extract::Toml("$.workspace.members[*]".into()));
        o.exclude_query = Some("$.workspace.exclude[*]".into());
        o.expect = Expect::Dir;
        let r = rule(o);
        // `b` is excluded, so its absence must not fail; `a` exists.
        let idx = index(&["Cargo.toml"], &["a"]);
        assert!(eval(&r, dir.path(), &idx).is_empty());
    }
}