alint_rules/
file_is_text.rs1use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
8
9use crate::io::{Classification, classify_bytes, read_prefix};
10
11#[derive(Debug)]
12pub struct FileIsTextRule {
13 id: String,
14 level: Level,
15 policy_url: Option<String>,
16 message: Option<String>,
17 scope: Scope,
18}
19
20impl Rule for FileIsTextRule {
21 fn id(&self) -> &str {
22 &self.id
23 }
24 fn level(&self) -> Level {
25 self.level
26 }
27 fn policy_url(&self) -> Option<&str> {
28 self.policy_url.as_deref()
29 }
30
31 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
32 let mut violations = Vec::new();
33 for entry in ctx.index.files() {
34 if !self.scope.matches(&entry.path) {
35 continue;
36 }
37 if entry.size == 0 {
38 continue;
40 }
41 let full = ctx.root.join(&entry.path);
42 let bytes = match read_prefix(&full) {
43 Ok(b) => b,
44 Err(e) => {
45 violations.push(
46 Violation::new(format!("could not read file: {e}")).with_path(&entry.path),
47 );
48 continue;
49 }
50 };
51 if classify_bytes(&bytes) == Classification::Binary {
52 let msg = self.message.clone().unwrap_or_else(|| {
53 "file is detected as binary; text is required here".to_string()
54 });
55 violations.push(Violation::new(msg).with_path(&entry.path));
56 }
57 }
58 Ok(violations)
59 }
60}
61
62pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
63 let Some(paths) = &spec.paths else {
64 return Err(Error::rule_config(
65 &spec.id,
66 "file_is_text requires a `paths` field",
67 ));
68 };
69 Ok(Box::new(FileIsTextRule {
70 id: spec.id.clone(),
71 level: spec.level,
72 policy_url: spec.policy_url.clone(),
73 message: spec.message.clone(),
74 scope: Scope::from_paths_spec(paths)?,
75 }))
76}