Skip to main content

alint_rules/
file_starts_with.rs

1//! `file_starts_with` — every file in scope must begin with the
2//! configured prefix (byte-level).
3//!
4//! Useful for SPDX headers (when `file_header`'s line-oriented
5//! matching is too loose), magic bytes on binary formats, or a
6//! required "do not edit — generated" banner. Works on any byte
7//! content, not just UTF-8.
8//!
9//! Check-only: the correct fix is to call `file_prepend` with
10//! the same content, and having the rule do it implicitly would
11//! silently duplicate the prefix on files that start with a
12//! similar but non-matching string.
13
14use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
15use serde::Deserialize;
16
17#[derive(Debug, Deserialize)]
18#[serde(deny_unknown_fields)]
19struct Options {
20    /// The required prefix. Matched byte-for-byte.
21    prefix: String,
22}
23
24#[derive(Debug)]
25pub struct FileStartsWithRule {
26    id: String,
27    level: Level,
28    policy_url: Option<String>,
29    message: Option<String>,
30    scope: Scope,
31    prefix: Vec<u8>,
32}
33
34impl Rule for FileStartsWithRule {
35    fn id(&self) -> &str {
36        &self.id
37    }
38    fn level(&self) -> Level {
39        self.level
40    }
41    fn policy_url(&self) -> Option<&str> {
42        self.policy_url.as_deref()
43    }
44
45    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
46        let mut violations = Vec::new();
47        for entry in ctx.index.files() {
48            if !self.scope.matches(&entry.path) {
49                continue;
50            }
51            let full = ctx.root.join(&entry.path);
52            let Ok(bytes) = std::fs::read(&full) else {
53                continue;
54            };
55            if !bytes.starts_with(&self.prefix) {
56                let msg = self
57                    .message
58                    .clone()
59                    .unwrap_or_else(|| "file does not start with the required prefix".to_string());
60                violations.push(
61                    Violation::new(msg)
62                        .with_path(&entry.path)
63                        .with_location(1, 1),
64                );
65            }
66        }
67        Ok(violations)
68    }
69}
70
71pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
72    let paths = spec
73        .paths
74        .as_ref()
75        .ok_or_else(|| Error::rule_config(&spec.id, "file_starts_with requires a `paths` field"))?;
76    let opts: Options = spec
77        .deserialize_options()
78        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
79    if opts.prefix.is_empty() {
80        return Err(Error::rule_config(
81            &spec.id,
82            "file_starts_with.prefix must not be empty",
83        ));
84    }
85    if spec.fix.is_some() {
86        return Err(Error::rule_config(
87            &spec.id,
88            "file_starts_with has no fix op — pair with an explicit `file_prepend` rule if you \
89             want auto-prepend (avoids silently duplicating near-matching prefixes).",
90        ));
91    }
92    Ok(Box::new(FileStartsWithRule {
93        id: spec.id.clone(),
94        level: spec.level,
95        policy_url: spec.policy_url.clone(),
96        message: spec.message.clone(),
97        scope: Scope::from_paths_spec(paths)?,
98        prefix: opts.prefix.into_bytes(),
99    }))
100}