Skip to main content

alint_rules/
file_shebang.rs

1//! `file_shebang` — first line of each file in scope must
2//! match a shebang regex.
3//!
4//! Pairs naturally with [`crate::executable_has_shebang`]
5//! (which checks shebang *presence* on `+x` files) and
6//! [`crate::shebang_has_executable`] (which checks the
7//! reverse, that a shebang file is `+x`). `file_shebang`
8//! checks shebang *shape*: enforce a specific interpreter
9//! pinning, ban `#!/usr/bin/env <foo>` in favour of an
10//! absolute path, require `set -euo pipefail` immediately
11//! after, etc.
12//!
13//! The default `shebang:` regex (when the user omits the
14//! field) is just `^#!`, which only enforces presence.
15//! Most useful configs supply a tighter regex like
16//! `^#!/usr/bin/env bash$` or `^#!/bin/bash -euo pipefail$`.
17
18use 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.clone())
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}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::test_support::{ctx, spec_yaml, tempdir_with_files};
113
114    #[test]
115    fn build_rejects_missing_paths_field() {
116        let spec = spec_yaml(
117            "id: t\n\
118             kind: file_shebang\n\
119             shebang: \"^#!/bin/sh\"\n\
120             level: error\n",
121        );
122        assert!(build(&spec).is_err());
123    }
124
125    #[test]
126    fn build_rejects_invalid_regex() {
127        let spec = spec_yaml(
128            "id: t\n\
129             kind: file_shebang\n\
130             paths: \"**/*.sh\"\n\
131             shebang: \"[unterminated\"\n\
132             level: error\n",
133        );
134        assert!(build(&spec).is_err());
135    }
136
137    #[test]
138    fn evaluate_passes_when_shebang_matches() {
139        let spec = spec_yaml(
140            "id: t\n\
141             kind: file_shebang\n\
142             paths: \"**/*.sh\"\n\
143             shebang: \"^#!/(usr/)?bin/(env )?(ba)?sh\"\n\
144             level: error\n",
145        );
146        let rule = build(&spec).unwrap();
147        let (tmp, idx) = tempdir_with_files(&[("a.sh", b"#!/usr/bin/env bash\necho hi\n")]);
148        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
149        assert!(v.is_empty(), "shebang should match: {v:?}");
150    }
151
152    #[test]
153    fn evaluate_fires_when_shebang_missing() {
154        let spec = spec_yaml(
155            "id: t\n\
156             kind: file_shebang\n\
157             paths: \"**/*.sh\"\n\
158             shebang: \"^#!\"\n\
159             level: error\n",
160        );
161        let rule = build(&spec).unwrap();
162        let (tmp, idx) = tempdir_with_files(&[("a.sh", b"echo hi\n")]);
163        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
164        assert_eq!(v.len(), 1);
165    }
166
167    #[test]
168    fn evaluate_only_inspects_first_line() {
169        // A shebang on line 5 must NOT satisfy the rule —
170        // shebangs are line-1-only.
171        let spec = spec_yaml(
172            "id: t\n\
173             kind: file_shebang\n\
174             paths: \"**/*.sh\"\n\
175             shebang: \"^#!/bin/sh\"\n\
176             level: error\n",
177        );
178        let rule = build(&spec).unwrap();
179        let (tmp, idx) = tempdir_with_files(&[("a.sh", b"echo first\n#!/bin/sh\n")]);
180        let v = rule.evaluate(&ctx(tmp.path(), &idx)).unwrap();
181        assert_eq!(v.len(), 1, "shebang on line 2 shouldn't satisfy");
182    }
183}