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            Some(FilePrependFixer::new(file_prepend.content.clone()))
111        }
112        Some(other) => {
113            return Err(Error::rule_config(
114                &spec.id,
115                format!("fix.{} is not compatible with file_header", other.op_name()),
116            ));
117        }
118        None => None,
119    };
120    Ok(Box::new(FileHeaderRule {
121        id: spec.id.clone(),
122        level: spec.level,
123        policy_url: spec.policy_url.clone(),
124        message: spec.message.clone(),
125        scope: Scope::from_paths_spec(paths)?,
126        pattern_src: opts.pattern,
127        pattern,
128        lines: opts.lines,
129        fixer,
130    }))
131}