alint_rules/
dir_absent.rs1use alint_core::{Context, Error, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation};
4
5#[derive(Debug)]
6pub struct DirAbsentRule {
7 id: String,
8 level: Level,
9 policy_url: Option<String>,
10 message: Option<String>,
11 scope: Scope,
12 patterns: Vec<String>,
13 git_tracked_only: bool,
20}
21
22impl Rule for DirAbsentRule {
23 fn id(&self) -> &str {
24 &self.id
25 }
26 fn level(&self) -> Level {
27 self.level
28 }
29 fn policy_url(&self) -> Option<&str> {
30 self.policy_url.as_deref()
31 }
32 fn wants_git_tracked(&self) -> bool {
33 self.git_tracked_only
34 }
35
36 fn requires_full_index(&self) -> bool {
37 true
42 }
43
44 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
45 let mut violations = Vec::new();
46 for entry in ctx.index.dirs() {
47 if !self.scope.matches(&entry.path) {
48 continue;
49 }
50 if self.git_tracked_only && !ctx.dir_has_tracked_files(&entry.path) {
51 continue;
52 }
53 let msg = self.message.clone().unwrap_or_else(|| {
54 let tracked = if self.git_tracked_only {
55 " and has tracked content"
56 } else {
57 ""
58 };
59 format!(
60 "directory is forbidden (matches [{}]{tracked}): {}",
61 self.patterns.join(", "),
62 entry.path.display()
63 )
64 });
65 violations.push(Violation::new(msg).with_path(entry.path.clone()));
66 }
67 Ok(violations)
68 }
69}
70
71pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
72 alint_core::reject_scope_filter_on_cross_file(spec, "dir_absent")?;
73 let Some(paths) = &spec.paths else {
74 return Err(Error::rule_config(
75 &spec.id,
76 "dir_absent requires a `paths` field",
77 ));
78 };
79 Ok(Box::new(DirAbsentRule {
80 id: spec.id.clone(),
81 level: spec.level,
82 policy_url: spec.policy_url.clone(),
83 message: spec.message.clone(),
84 scope: Scope::from_paths_spec(paths)?,
85 patterns: patterns_of(paths),
86 git_tracked_only: spec.git_tracked_only,
87 }))
88}
89
90fn patterns_of(spec: &PathsSpec) -> Vec<String> {
91 match spec {
92 PathsSpec::Single(s) => vec![s.clone()],
93 PathsSpec::Many(v) => v.clone(),
94 PathsSpec::IncludeExclude { include, .. } => include.clone(),
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101 use crate::test_support::{ctx, index_with_dirs, spec_yaml};
102 use std::path::Path;
103
104 #[test]
105 fn build_rejects_missing_paths_field() {
106 let spec = spec_yaml(
107 "id: t\n\
108 kind: dir_absent\n\
109 level: error\n",
110 );
111 let err = build(&spec).unwrap_err().to_string();
112 assert!(err.contains("paths"), "unexpected: {err}");
113 }
114
115 #[test]
116 fn evaluate_passes_when_no_matching_dir_present() {
117 let spec = spec_yaml(
118 "id: t\n\
119 kind: dir_absent\n\
120 paths: \"target\"\n\
121 level: error\n",
122 );
123 let rule = build(&spec).unwrap();
124 let idx = index_with_dirs(&[("src", true), ("docs", true)]);
125 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
126 assert!(v.is_empty(), "unexpected: {v:?}");
127 }
128
129 #[test]
130 fn evaluate_fires_one_violation_per_forbidden_dir() {
131 let spec = spec_yaml(
132 "id: t\n\
133 kind: dir_absent\n\
134 paths: \"**/target\"\n\
135 level: error\n",
136 );
137 let rule = build(&spec).unwrap();
138 let idx = index_with_dirs(&[("target", true), ("crates/foo/target", true), ("src", true)]);
139 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
140 assert_eq!(v.len(), 2, "expected one violation per target dir: {v:?}");
141 }
142
143 #[test]
144 fn evaluate_ignores_files_with_matching_name() {
145 let spec = spec_yaml(
146 "id: t\n\
147 kind: dir_absent\n\
148 paths: \"target\"\n\
149 level: error\n",
150 );
151 let rule = build(&spec).unwrap();
152 let idx = index_with_dirs(&[("target", false)]);
154 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
155 assert!(v.is_empty(), "file named 'target' shouldn't fire");
156 }
157
158 #[test]
159 fn git_tracked_only_silent_outside_repo() {
160 let spec = spec_yaml(
161 "id: t\n\
162 kind: dir_absent\n\
163 paths: \"target\"\n\
164 level: error\n\
165 git_tracked_only: true\n",
166 );
167 let rule = build(&spec).unwrap();
168 let idx = index_with_dirs(&[("target", true)]);
169 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
172 assert!(
173 v.is_empty(),
174 "git_tracked_only without tracked-set must no-op: {v:?}",
175 );
176 }
177
178 #[test]
179 fn rule_advertises_full_index_requirement() {
180 let spec = spec_yaml(
181 "id: t\n\
182 kind: dir_absent\n\
183 paths: \"target\"\n\
184 level: error\n",
185 );
186 let rule = build(&spec).unwrap();
187 assert!(rule.requires_full_index());
188 }
189
190 #[test]
191 fn build_rejects_scope_filter_on_cross_file_rule() {
192 let yaml = r#"
197id: t
198kind: dir_absent
199paths: "target"
200level: error
201scope_filter:
202 has_ancestor: Cargo.toml
203"#;
204 let spec = spec_yaml(yaml);
205 let err = build(&spec).unwrap_err().to_string();
206 assert!(
207 err.contains("scope_filter is supported on per-file rules only"),
208 "expected per-file-only message, got: {err}",
209 );
210 assert!(
211 err.contains("dir_absent"),
212 "expected message to name the cross-file kind, got: {err}",
213 );
214 }
215}