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