Skip to main content

alint_rules/
file_header.rs

1//! `file_header` — first N lines of each file in scope must match a pattern.
2
3use alint_core::{Context, Error, FixSpec, Fixer, Level, Result, Rule, RuleSpec, Scope, Violation};
4use regex::Regex;
5use serde::Deserialize;
6
7use crate::fixers::FilePrependFixer;
8
9#[derive(Debug, Deserialize)]
10struct Options {
11    pattern: String,
12    #[serde(default = "default_lines")]
13    lines: usize,
14}
15
16fn default_lines() -> usize {
17    20
18}
19
20#[derive(Debug)]
21pub struct FileHeaderRule {
22    id: String,
23    level: Level,
24    policy_url: Option<String>,
25    message: Option<String>,
26    scope: Scope,
27    pattern_src: String,
28    pattern: Regex,
29    lines: usize,
30    fixer: Option<FilePrependFixer>,
31}
32
33impl Rule for FileHeaderRule {
34    fn id(&self) -> &str {
35        &self.id
36    }
37    fn level(&self) -> Level {
38        self.level
39    }
40    fn policy_url(&self) -> Option<&str> {
41        self.policy_url.as_deref()
42    }
43
44    fn fixer(&self) -> Option<&dyn Fixer> {
45        self.fixer.as_ref().map(|f| f as &dyn Fixer)
46    }
47
48    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
49        let mut violations = Vec::new();
50        for entry in ctx.index.files() {
51            if !self.scope.matches(&entry.path) {
52                continue;
53            }
54            let full = ctx.root.join(&entry.path);
55            let bytes = match std::fs::read(&full) {
56                Ok(b) => b,
57                Err(e) => {
58                    violations.push(
59                        Violation::new(format!("could not read file: {e}")).with_path(&entry.path),
60                    );
61                    continue;
62                }
63            };
64            let Ok(text) = std::str::from_utf8(&bytes) else {
65                violations.push(
66                    Violation::new("file is not valid UTF-8; cannot match header")
67                        .with_path(&entry.path),
68                );
69                continue;
70            };
71            let header: String = text.split_inclusive('\n').take(self.lines).collect();
72            if !self.pattern.is_match(&header) {
73                let msg = self.message.clone().unwrap_or_else(|| {
74                    format!(
75                        "first {} line(s) do not match required header /{}/",
76                        self.lines, self.pattern_src
77                    )
78                });
79                violations.push(
80                    Violation::new(msg)
81                        .with_path(&entry.path)
82                        .with_location(1, 1),
83                );
84            }
85        }
86        Ok(violations)
87    }
88}
89
90pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
91    let Some(paths) = &spec.paths else {
92        return Err(Error::rule_config(
93            &spec.id,
94            "file_header requires a `paths` field",
95        ));
96    };
97    let opts: Options = spec
98        .deserialize_options()
99        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
100    if opts.lines == 0 {
101        return Err(Error::rule_config(
102            &spec.id,
103            "file_header `lines` must be > 0",
104        ));
105    }
106    let pattern = Regex::new(&opts.pattern)
107        .map_err(|e| Error::rule_config(&spec.id, format!("invalid pattern: {e}")))?;
108    let fixer = match &spec.fix {
109        Some(FixSpec::FilePrepend { file_prepend }) => {
110            let source = alint_core::resolve_content_source(
111                &spec.id,
112                "file_prepend",
113                &file_prepend.content,
114                &file_prepend.content_from,
115            )?;
116            Some(FilePrependFixer::new(source))
117        }
118        Some(other) => {
119            return Err(Error::rule_config(
120                &spec.id,
121                format!("fix.{} is not compatible with file_header", other.op_name()),
122            ));
123        }
124        None => None,
125    };
126    Ok(Box::new(FileHeaderRule {
127        id: spec.id.clone(),
128        level: spec.level,
129        policy_url: spec.policy_url.clone(),
130        message: spec.message.clone(),
131        scope: Scope::from_paths_spec(paths)?,
132        pattern_src: opts.pattern,
133        pattern,
134        lines: opts.lines,
135        fixer,
136    }))
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
143
144    #[test]
145    fn build_rejects_missing_paths_field() {
146        let spec = spec_yaml(
147            "id: t\n\
148             kind: file_header\n\
149             pattern: \"^// SPDX\"\n\
150             level: error\n",
151        );
152        assert!(build(&spec).is_err());
153    }
154
155    #[test]
156    fn build_rejects_zero_lines() {
157        let spec = spec_yaml(
158            "id: t\n\
159             kind: file_header\n\
160             paths: \"src/**/*.rs\"\n\
161             pattern: \"^// SPDX\"\n\
162             lines: 0\n\
163             level: error\n",
164        );
165        let err = build(&spec).unwrap_err().to_string();
166        assert!(err.contains("lines"), "unexpected: {err}");
167    }
168
169    #[test]
170    fn build_rejects_invalid_regex() {
171        let spec = spec_yaml(
172            "id: t\n\
173             kind: file_header\n\
174             paths: \"src/**/*.rs\"\n\
175             pattern: \"[unterminated\"\n\
176             level: error\n",
177        );
178        assert!(build(&spec).is_err());
179    }
180
181    #[test]
182    fn evaluate_passes_when_header_matches() {
183        let spec = spec_yaml(
184            "id: t\n\
185             kind: file_header\n\
186             paths: \"src/**/*.rs\"\n\
187             pattern: \"SPDX-License-Identifier: Apache-2.0\"\n\
188             level: error\n",
189        );
190        let rule = build(&spec).unwrap();
191        let (tmp, idx) = tempdir_with_files(&[(
192            "src/main.rs",
193            b"// SPDX-License-Identifier: Apache-2.0\n\nfn main() {}\n",
194        )]);
195        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
196        assert!(v.is_empty(), "header should match: {v:?}");
197    }
198
199    #[test]
200    fn evaluate_fires_when_header_missing() {
201        let spec = spec_yaml(
202            "id: t\n\
203             kind: file_header\n\
204             paths: \"src/**/*.rs\"\n\
205             pattern: \"SPDX-License-Identifier:\"\n\
206             level: error\n",
207        );
208        let rule = build(&spec).unwrap();
209        let (tmp, idx) = tempdir_with_files(&[("src/main.rs", b"fn main() {}\n")]);
210        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
211        assert_eq!(v.len(), 1);
212    }
213
214    #[test]
215    fn evaluate_only_inspects_first_n_lines() {
216        // Pattern only on line 30, but `lines: 5` only looks at
217        // lines 1-5 → rule fires.
218        let spec = spec_yaml(
219            "id: t\n\
220             kind: file_header\n\
221             paths: \"src/**/*.rs\"\n\
222             pattern: \"NEEDLE\"\n\
223             lines: 5\n\
224             level: error\n",
225        );
226        let rule = build(&spec).unwrap();
227        let mut content = String::new();
228        for _ in 0..30 {
229            content.push_str("filler\n");
230        }
231        content.push_str("NEEDLE\n");
232        let (tmp, idx) = tempdir_with_files(&[("src/main.rs", content.as_bytes())]);
233        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
234        assert_eq!(v.len(), 1);
235    }
236}