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            let source = alint_core::resolve_content_source(
93                &spec.id,
94                "file_append",
95                &file_append.content,
96                &file_append.content_from,
97            )?;
98            Some(FileAppendFixer::new(source))
99        }
100        Some(other) => {
101            return Err(Error::rule_config(
102                &spec.id,
103                format!(
104                    "fix.{} is not compatible with file_content_matches",
105                    other.op_name()
106                ),
107            ));
108        }
109        None => None,
110    };
111    Ok(Box::new(FileContentMatchesRule {
112        id: spec.id.clone(),
113        level: spec.level,
114        policy_url: spec.policy_url.clone(),
115        message: spec.message.clone(),
116        scope: Scope::from_paths_spec(paths)?,
117        pattern_src: opts.pattern,
118        pattern,
119        fixer,
120    }))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
127
128    #[test]
129    fn build_rejects_missing_paths_field() {
130        let spec = spec_yaml(
131            "id: t\n\
132             kind: file_content_matches\n\
133             pattern: \".*\"\n\
134             level: error\n",
135        );
136        assert!(build(&spec).is_err());
137    }
138
139    #[test]
140    fn build_rejects_invalid_regex() {
141        let spec = spec_yaml(
142            "id: t\n\
143             kind: file_content_matches\n\
144             paths: \"**/*\"\n\
145             pattern: \"[unterminated\"\n\
146             level: error\n",
147        );
148        assert!(build(&spec).is_err());
149    }
150
151    #[test]
152    fn evaluate_passes_when_pattern_matches() {
153        let spec = spec_yaml(
154            "id: t\n\
155             kind: file_content_matches\n\
156             paths: \"LICENSE\"\n\
157             pattern: \"Apache License\"\n\
158             level: error\n",
159        );
160        let rule = build(&spec).unwrap();
161        let (tmp, idx) =
162            tempdir_with_files(&[("LICENSE", b"Apache License Version 2.0, January 2004\n")]);
163        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
164        assert!(v.is_empty(), "pattern should match: {v:?}");
165    }
166
167    #[test]
168    fn evaluate_fires_when_pattern_missing() {
169        let spec = spec_yaml(
170            "id: t\n\
171             kind: file_content_matches\n\
172             paths: \"LICENSE\"\n\
173             pattern: \"Apache License\"\n\
174             level: error\n",
175        );
176        let rule = build(&spec).unwrap();
177        let (tmp, idx) = tempdir_with_files(&[("LICENSE", b"MIT License\n\nCopyright ...\n")]);
178        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
179        assert_eq!(v.len(), 1);
180    }
181
182    #[test]
183    fn evaluate_skips_files_outside_scope() {
184        let spec = spec_yaml(
185            "id: t\n\
186             kind: file_content_matches\n\
187             paths: \"LICENSE\"\n\
188             pattern: \"Apache\"\n\
189             level: error\n",
190        );
191        let rule = build(&spec).unwrap();
192        let (tmp, idx) = tempdir_with_files(&[("README.md", b"no apache here")]);
193        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
194        assert!(v.is_empty(), "out-of-scope shouldn't fire: {v:?}");
195    }
196
197    #[test]
198    fn evaluate_fires_with_clear_message_on_non_utf8() {
199        // file_content_matches needs to read text to apply the
200        // regex; non-UTF-8 input surfaces an explicit violation
201        // rather than silently skipping (so a binary commit
202        // doesn't accidentally hide a missing-pattern policy).
203        let spec = spec_yaml(
204            "id: t\n\
205             kind: file_content_matches\n\
206             paths: \"img.bin\"\n\
207             pattern: \"never matches\"\n\
208             level: error\n",
209        );
210        let rule = build(&spec).unwrap();
211        let (tmp, idx) = tempdir_with_files(&[("img.bin", &[0xff, 0xfe, 0xfd])]);
212        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
213        assert_eq!(v.len(), 1, "non-UTF-8 should report one violation");
214        assert!(
215            v[0].message.contains("UTF-8"),
216            "message should mention UTF-8: {}",
217            v[0].message
218        );
219    }
220}