alint_rules/
file_shebang.rs1use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
19use regex::Regex;
20use serde::Deserialize;
21
22#[derive(Debug, Deserialize)]
23struct Options {
24 #[serde(default = "default_shebang")]
25 shebang: String,
26}
27
28fn default_shebang() -> String {
29 "^#!".to_string()
30}
31
32#[derive(Debug)]
33pub struct FileShebangRule {
34 id: String,
35 level: Level,
36 policy_url: Option<String>,
37 message: Option<String>,
38 scope: Scope,
39 pattern_src: String,
40 pattern: Regex,
41}
42
43impl Rule for FileShebangRule {
44 fn id(&self) -> &str {
45 &self.id
46 }
47 fn level(&self) -> Level {
48 self.level
49 }
50 fn policy_url(&self) -> Option<&str> {
51 self.policy_url.as_deref()
52 }
53
54 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
55 let mut violations = Vec::new();
56 for entry in ctx.index.files() {
57 if !self.scope.matches(&entry.path) {
58 continue;
59 }
60 let full = ctx.root.join(&entry.path);
61 let Ok(bytes) = std::fs::read(&full) else {
62 continue;
63 };
64 let first_line = match std::str::from_utf8(&bytes) {
65 Ok(text) => text.split('\n').next().unwrap_or(""),
66 Err(_) => "",
67 };
68 if !self.pattern.is_match(first_line) {
69 let msg = self.message.clone().unwrap_or_else(|| {
70 format!(
71 "first line {first_line:?} does not match required shebang /{}/",
72 self.pattern_src
73 )
74 });
75 violations.push(
76 Violation::new(msg)
77 .with_path(&entry.path)
78 .with_location(1, 1),
79 );
80 }
81 }
82 Ok(violations)
83 }
84}
85
86pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
87 let Some(paths) = &spec.paths else {
88 return Err(Error::rule_config(
89 &spec.id,
90 "file_shebang requires a `paths` field",
91 ));
92 };
93 let opts: Options = spec
94 .deserialize_options()
95 .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
96 let pattern = Regex::new(&opts.shebang)
97 .map_err(|e| Error::rule_config(&spec.id, format!("invalid shebang regex: {e}")))?;
98 Ok(Box::new(FileShebangRule {
99 id: spec.id.clone(),
100 level: spec.level,
101 policy_url: spec.policy_url.clone(),
102 message: spec.message.clone(),
103 scope: Scope::from_paths_spec(paths)?,
104 pattern_src: opts.shebang,
105 pattern,
106 }))
107}