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