alint_rules/
no_empty_files.rs1use alint_core::{Context, Error, FixSpec, Fixer, Level, Result, Rule, RuleSpec, Scope, Violation};
8
9use crate::fixers::FileRemoveFixer;
10
11#[derive(Debug)]
12pub struct NoEmptyFilesRule {
13 id: String,
14 level: Level,
15 policy_url: Option<String>,
16 message: Option<String>,
17 scope: Scope,
18 fixer: Option<FileRemoveFixer>,
19}
20
21impl Rule for NoEmptyFilesRule {
22 fn id(&self) -> &str {
23 &self.id
24 }
25 fn level(&self) -> Level {
26 self.level
27 }
28 fn policy_url(&self) -> Option<&str> {
29 self.policy_url.as_deref()
30 }
31
32 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
33 let mut violations = Vec::new();
34 for entry in ctx.index.files() {
35 if !self.scope.matches(&entry.path) {
36 continue;
37 }
38 if entry.size == 0 {
39 let msg = self
40 .message
41 .clone()
42 .unwrap_or_else(|| "file is empty".to_string());
43 violations.push(Violation::new(msg).with_path(&entry.path));
44 }
45 }
46 Ok(violations)
47 }
48
49 fn fixer(&self) -> Option<&dyn Fixer> {
50 self.fixer.as_ref().map(|f| f as &dyn Fixer)
51 }
52}
53
54pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
55 let paths = spec
56 .paths
57 .as_ref()
58 .ok_or_else(|| Error::rule_config(&spec.id, "no_empty_files requires a `paths` field"))?;
59 let fixer = match &spec.fix {
60 Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
61 Some(other) => {
62 return Err(Error::rule_config(
63 &spec.id,
64 format!(
65 "fix.{} is not compatible with no_empty_files",
66 other.op_name()
67 ),
68 ));
69 }
70 None => None,
71 };
72 Ok(Box::new(NoEmptyFilesRule {
73 id: spec.id.clone(),
74 level: spec.level,
75 policy_url: spec.policy_url.clone(),
76 message: spec.message.clone(),
77 scope: Scope::from_paths_spec(paths)?,
78 fixer,
79 }))
80}