alint_rules/
file_content_forbidden.rs1use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
4use regex::Regex;
5use serde::Deserialize;
6
7#[derive(Debug, Deserialize)]
8struct Options {
9 pattern: String,
10}
11
12#[derive(Debug)]
13pub struct FileContentForbiddenRule {
14 id: String,
15 level: Level,
16 policy_url: Option<String>,
17 message: Option<String>,
18 scope: Scope,
19 pattern_src: String,
20 pattern: Regex,
21}
22
23impl Rule for FileContentForbiddenRule {
24 fn id(&self) -> &str {
25 &self.id
26 }
27 fn level(&self) -> Level {
28 self.level
29 }
30 fn policy_url(&self) -> Option<&str> {
31 self.policy_url.as_deref()
32 }
33
34 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
35 let mut violations = Vec::new();
36 for entry in ctx.index.files() {
37 if !self.scope.matches(&entry.path) {
38 continue;
39 }
40 let full = ctx.root.join(&entry.path);
41 let bytes = match std::fs::read(&full) {
42 Ok(b) => b,
43 Err(e) => {
44 violations.push(
45 Violation::new(format!("could not read file: {e}")).with_path(&entry.path),
46 );
47 continue;
48 }
49 };
50 let Ok(text) = std::str::from_utf8(&bytes) else {
51 continue;
54 };
55 if let Some(m) = self.pattern.find(text) {
56 let line = text[..m.start()].matches('\n').count() + 1;
57 let msg = self
58 .message
59 .clone()
60 .unwrap_or_else(|| format!("forbidden pattern /{}/ found", self.pattern_src));
61 violations.push(
62 Violation::new(msg)
63 .with_path(&entry.path)
64 .with_location(line, 1),
65 );
66 }
67 }
68 Ok(violations)
69 }
70}
71
72pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
73 let Some(paths) = &spec.paths else {
74 return Err(Error::rule_config(
75 &spec.id,
76 "file_content_forbidden requires a `paths` field",
77 ));
78 };
79 let opts: Options = spec
80 .deserialize_options()
81 .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
82 let pattern = Regex::new(&opts.pattern)
83 .map_err(|e| Error::rule_config(&spec.id, format!("invalid pattern: {e}")))?;
84 Ok(Box::new(FileContentForbiddenRule {
85 id: spec.id.clone(),
86 level: spec.level,
87 policy_url: spec.policy_url.clone(),
88 message: spec.message.clone(),
89 scope: Scope::from_paths_spec(paths)?,
90 pattern_src: opts.pattern,
91 pattern,
92 }))
93}