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