Skip to main content

alint_rules/
file_content_matches.rs

1//! `file_content_matches` — every file in scope must match a regex.
2
3use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
4use regex::Regex;
5use serde::Deserialize;
6
7#[derive(Debug, Deserialize)]
8struct Options {
9    pattern: String,
10}
11
12#[derive(Debug)]
13pub struct FileContentMatchesRule {
14    id: String,
15    level: Level,
16    policy_url: Option<String>,
17    message: Option<String>,
18    scope: Scope,
19    pattern_src: String,
20    pattern: Regex,
21}
22
23impl Rule for FileContentMatchesRule {
24    fn id(&self) -> &str {
25        &self.id
26    }
27    fn level(&self) -> Level {
28        self.level
29    }
30    fn policy_url(&self) -> Option<&str> {
31        self.policy_url.as_deref()
32    }
33
34    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
35        let mut violations = Vec::new();
36        for entry in ctx.index.files() {
37            if !self.scope.matches(&entry.path) {
38                continue;
39            }
40            let full = ctx.root.join(&entry.path);
41            let bytes = match std::fs::read(&full) {
42                Ok(b) => b,
43                Err(e) => {
44                    violations.push(
45                        Violation::new(format!("could not read file: {e}")).with_path(&entry.path),
46                    );
47                    continue;
48                }
49            };
50            let Ok(text) = std::str::from_utf8(&bytes) else {
51                violations.push(
52                    Violation::new("file is not valid UTF-8; cannot match regex")
53                        .with_path(&entry.path),
54                );
55                continue;
56            };
57            if !self.pattern.is_match(text) {
58                let msg = self.message.clone().unwrap_or_else(|| {
59                    format!(
60                        "content does not match required pattern /{}/",
61                        self.pattern_src
62                    )
63                });
64                violations.push(Violation::new(msg).with_path(&entry.path));
65            }
66        }
67        Ok(violations)
68    }
69}
70
71pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
72    let Some(paths) = &spec.paths else {
73        return Err(Error::rule_config(
74            &spec.id,
75            "file_content_matches requires a `paths` field",
76        ));
77    };
78    let opts: Options = spec
79        .deserialize_options()
80        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
81    let pattern = Regex::new(&opts.pattern)
82        .map_err(|e| Error::rule_config(&spec.id, format!("invalid pattern: {e}")))?;
83    Ok(Box::new(FileContentMatchesRule {
84        id: spec.id.clone(),
85        level: spec.level,
86        policy_url: spec.policy_url.clone(),
87        message: spec.message.clone(),
88        scope: Scope::from_paths_spec(paths)?,
89        pattern_src: opts.pattern,
90        pattern,
91    }))
92}