Skip to main content

alint_rules/
no_empty_files.rs

1//! `no_empty_files` — flag zero-byte files in scope.
2//!
3//! Empty files usually indicate placeholders forgotten in a
4//! branch or generator output that lost its content. Fixable
5//! via `file_remove`, which deletes the empty file.
6
7use 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.clone()));
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}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use crate::test_support::{ctx, spec_yaml};
86    use alint_core::{FileEntry, FileIndex};
87    use std::path::Path;
88
89    fn idx(entries: &[(&str, u64)]) -> FileIndex {
90        FileIndex {
91            entries: entries
92                .iter()
93                .map(|(p, sz)| FileEntry {
94                    path: std::path::Path::new(p).into(),
95                    is_dir: false,
96                    size: *sz,
97                })
98                .collect(),
99        }
100    }
101
102    #[test]
103    fn build_rejects_missing_paths_field() {
104        let spec = spec_yaml(
105            "id: t\n\
106             kind: no_empty_files\n\
107             level: warning\n",
108        );
109        assert!(build(&spec).is_err());
110    }
111
112    #[test]
113    fn build_accepts_file_remove_fix() {
114        let spec = spec_yaml(
115            "id: t\n\
116             kind: no_empty_files\n\
117             paths: \"**/*\"\n\
118             level: warning\n\
119             fix:\n  \
120               file_remove: {}\n",
121        );
122        let rule = build(&spec).unwrap();
123        assert!(rule.fixer().is_some());
124    }
125
126    #[test]
127    fn build_rejects_incompatible_fix() {
128        let spec = spec_yaml(
129            "id: t\n\
130             kind: no_empty_files\n\
131             paths: \"**/*\"\n\
132             level: warning\n\
133             fix:\n  \
134               file_create:\n    \
135                 content: \"x\"\n",
136        );
137        assert!(build(&spec).is_err());
138    }
139
140    #[test]
141    fn evaluate_fires_on_zero_byte_files() {
142        let spec = spec_yaml(
143            "id: t\n\
144             kind: no_empty_files\n\
145             paths: \"**/*\"\n\
146             level: warning\n",
147        );
148        let rule = build(&spec).unwrap();
149        let i = idx(&[("a.txt", 0), ("b.txt", 100), ("c.txt", 0)]);
150        let v = rule.evaluate(&ctx(Path::new("/fake"), &i)).unwrap();
151        assert_eq!(v.len(), 2, "two empty files should fire");
152    }
153
154    #[test]
155    fn evaluate_passes_on_non_empty_files() {
156        let spec = spec_yaml(
157            "id: t\n\
158             kind: no_empty_files\n\
159             paths: \"**/*\"\n\
160             level: warning\n",
161        );
162        let rule = build(&spec).unwrap();
163        let i = idx(&[("a.txt", 1), ("b.txt", 1024)]);
164        let v = rule.evaluate(&ctx(Path::new("/fake"), &i)).unwrap();
165        assert!(v.is_empty());
166    }
167}