alint_rules/
file_absent.rs1use alint_core::{
4 Context, Error, FixSpec, Fixer, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation,
5};
6
7use crate::fixers::FileRemoveFixer;
8
9#[derive(Debug)]
10pub struct FileAbsentRule {
11 id: String,
12 level: Level,
13 policy_url: Option<String>,
14 message: Option<String>,
15 scope: Scope,
16 patterns: Vec<String>,
17 git_tracked_only: bool,
24 fixer: Option<FileRemoveFixer>,
25}
26
27impl Rule for FileAbsentRule {
28 fn id(&self) -> &str {
29 &self.id
30 }
31 fn level(&self) -> Level {
32 self.level
33 }
34 fn policy_url(&self) -> Option<&str> {
35 self.policy_url.as_deref()
36 }
37 fn wants_git_tracked(&self) -> bool {
38 self.git_tracked_only
39 }
40
41 fn requires_full_index(&self) -> bool {
42 true
48 }
49
50 fn path_scope(&self) -> Option<&Scope> {
51 Some(&self.scope)
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 if self.git_tracked_only && !ctx.is_git_tracked(&entry.path) {
61 continue;
62 }
63 let msg = self.message.clone().unwrap_or_else(|| {
64 let tracked = if self.git_tracked_only {
65 " and tracked in git"
66 } else {
67 ""
68 };
69 format!(
70 "file is forbidden (matches [{}]{tracked}): {}",
71 self.patterns.join(", "),
72 entry.path.display()
73 )
74 });
75 violations.push(Violation::new(msg).with_path(&entry.path));
76 }
77 Ok(violations)
78 }
79
80 fn fixer(&self) -> Option<&dyn Fixer> {
81 self.fixer.as_ref().map(|f| f as &dyn Fixer)
82 }
83}
84
85pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
86 let Some(paths) = &spec.paths else {
87 return Err(Error::rule_config(
88 &spec.id,
89 "file_absent requires a `paths` field",
90 ));
91 };
92 let fixer = match &spec.fix {
93 Some(FixSpec::FileRemove { .. }) => Some(FileRemoveFixer),
94 Some(other) => {
95 return Err(Error::rule_config(
96 &spec.id,
97 format!("fix.{} is not compatible with file_absent", other.op_name()),
98 ));
99 }
100 None => None,
101 };
102 Ok(Box::new(FileAbsentRule {
103 id: spec.id.clone(),
104 level: spec.level,
105 policy_url: spec.policy_url.clone(),
106 message: spec.message.clone(),
107 scope: Scope::from_paths_spec(paths)?,
108 patterns: patterns_of(paths),
109 git_tracked_only: spec.git_tracked_only,
110 fixer,
111 }))
112}
113
114fn patterns_of(spec: &PathsSpec) -> Vec<String> {
115 match spec {
116 PathsSpec::Single(s) => vec![s.clone()],
117 PathsSpec::Many(v) => v.clone(),
118 PathsSpec::IncludeExclude { include, .. } => include.clone(),
119 }
120}