1use std::path::{Path, PathBuf};
5
6use alint_core::{
7 Context, Error, FixSpec, Fixer, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation,
8};
9use serde::Deserialize;
10
11use crate::fixers::FileCreateFixer;
12
13#[derive(Debug, Deserialize)]
14#[serde(deny_unknown_fields)]
15struct Options {
16 #[serde(default)]
17 root_only: bool,
18}
19
20#[derive(Debug)]
21pub struct FileExistsRule {
22 id: String,
23 level: Level,
24 policy_url: Option<String>,
25 message: Option<String>,
26 scope: Scope,
27 patterns: Vec<String>,
28 literal_paths: Option<Vec<PathBuf>>,
39 root_only: bool,
40 git_tracked_only: bool,
45 fixer: Option<FileCreateFixer>,
46}
47
48fn is_literal_path(pattern: &str) -> bool {
54 !pattern.starts_with('!')
55 && !pattern
56 .chars()
57 .any(|c| matches!(c, '*' | '?' | '[' | ']' | '{' | '}'))
58}
59
60fn paths_spec_has_no_excludes(spec: &PathsSpec) -> bool {
64 match spec {
65 PathsSpec::Single(_) | PathsSpec::Many(_) => true,
66 PathsSpec::IncludeExclude { exclude, .. } => exclude.is_empty(),
67 }
68}
69
70impl FileExistsRule {
71 fn describe_patterns(&self) -> String {
72 self.patterns.join(", ")
73 }
74}
75
76impl Rule for FileExistsRule {
77 fn id(&self) -> &str {
78 &self.id
79 }
80 fn level(&self) -> Level {
81 self.level
82 }
83 fn policy_url(&self) -> Option<&str> {
84 self.policy_url.as_deref()
85 }
86
87 fn wants_git_tracked(&self) -> bool {
88 self.git_tracked_only
89 }
90
91 fn requires_full_index(&self) -> bool {
92 true
98 }
99
100 fn path_scope(&self) -> Option<&Scope> {
101 Some(&self.scope)
102 }
103
104 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
105 let found = if let Some(literals) = self.literal_paths.as_ref() {
106 literals.iter().any(|p| {
112 if self.root_only && literal_is_nested(p) {
113 return false;
114 }
115 ctx.index.contains_file(p)
116 })
117 } else {
118 ctx.index.files().any(|entry| {
123 if self.root_only && entry.path.components().count() != 1 {
124 return false;
125 }
126 if !self.scope.matches(&entry.path) {
127 return false;
128 }
129 if self.git_tracked_only && !ctx.is_git_tracked(&entry.path) {
130 return false;
131 }
132 true
133 })
134 };
135 if found {
136 Ok(Vec::new())
137 } else {
138 let message = self.message.clone().unwrap_or_else(|| {
139 let scope = if self.root_only {
140 " at the repo root"
141 } else {
142 ""
143 };
144 let tracked = if self.git_tracked_only {
145 " (tracked in git)"
146 } else {
147 ""
148 };
149 format!(
150 "expected a file matching [{}]{scope}{tracked}",
151 self.describe_patterns()
152 )
153 });
154 Ok(vec![Violation::new(message)])
155 }
156 }
157
158 fn fixer(&self) -> Option<&dyn Fixer> {
159 self.fixer.as_ref().map(|f| f as &dyn Fixer)
160 }
161}
162
163pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
164 let Some(paths) = &spec.paths else {
165 return Err(Error::rule_config(
166 &spec.id,
167 "file_exists requires a `paths` field",
168 ));
169 };
170 let patterns = patterns_of(paths);
171 let scope = Scope::from_paths_spec(paths)?;
172 let opts: Options = spec
173 .deserialize_options()
174 .unwrap_or(Options { root_only: false });
175 let literal_paths = if !spec.git_tracked_only
182 && paths_spec_has_no_excludes(paths)
183 && patterns.iter().all(|p| is_literal_path(p))
184 {
185 Some(patterns.iter().map(PathBuf::from).collect())
186 } else {
187 None
188 };
189 let fixer = match &spec.fix {
190 Some(FixSpec::FileCreate { file_create: cfg }) => {
191 let target = cfg
192 .path
193 .clone()
194 .or_else(|| first_literal_path(&patterns))
195 .ok_or_else(|| {
196 Error::rule_config(
197 &spec.id,
198 "fix.file_create needs a `path` — none of the rule's `paths:` \
199 entries is a literal filename",
200 )
201 })?;
202 let source = alint_core::resolve_content_source(
203 &spec.id,
204 "file_create",
205 &cfg.content,
206 &cfg.content_from,
207 )?;
208 Some(FileCreateFixer::new(target, source, cfg.create_parents))
209 }
210 Some(other) => {
211 return Err(Error::rule_config(
212 &spec.id,
213 format!("fix.{} is not compatible with file_exists", other.op_name()),
214 ));
215 }
216 None => None,
217 };
218 Ok(Box::new(FileExistsRule {
219 id: spec.id.clone(),
220 level: spec.level,
221 policy_url: spec.policy_url.clone(),
222 message: spec.message.clone(),
223 scope,
224 patterns,
225 literal_paths,
226 root_only: opts.root_only,
227 git_tracked_only: spec.git_tracked_only,
228 fixer,
229 }))
230}
231
232fn literal_is_nested(p: &Path) -> bool {
237 p.components().count() != 1
238}
239
240fn first_literal_path(patterns: &[String]) -> Option<PathBuf> {
245 patterns
246 .iter()
247 .find(|p| !p.chars().any(|c| matches!(c, '*' | '?' | '[' | '{')))
248 .map(PathBuf::from)
249}
250
251fn patterns_of(spec: &PathsSpec) -> Vec<String> {
252 match spec {
253 PathsSpec::Single(s) => vec![s.clone()],
254 PathsSpec::Many(v) => v.clone(),
255 PathsSpec::IncludeExclude { include, .. } => include.clone(),
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262 use crate::test_support::{ctx, index, spec_yaml};
263 use std::path::Path;
264
265 #[test]
266 fn build_rejects_missing_paths_field() {
267 let spec = spec_yaml(
268 "id: t\n\
269 kind: file_exists\n\
270 level: error\n",
271 );
272 let err = build(&spec).unwrap_err().to_string();
273 assert!(err.contains("paths"), "unexpected: {err}");
274 }
275
276 #[test]
277 fn build_accepts_root_only_option() {
278 let spec = spec_yaml(
286 "id: t\n\
287 kind: file_exists\n\
288 paths: \"LICENSE\"\n\
289 level: error\n\
290 root_only: true\n",
291 );
292 assert!(build(&spec).is_ok());
293 }
294
295 #[test]
296 fn build_rejects_incompatible_fix_op() {
297 let spec = spec_yaml(
301 "id: t\n\
302 kind: file_exists\n\
303 paths: \"LICENSE\"\n\
304 level: error\n\
305 fix:\n \
306 file_remove: {}\n",
307 );
308 let err = build(&spec).unwrap_err().to_string();
309 assert!(err.contains("file_remove"), "unexpected: {err}");
310 }
311
312 #[test]
313 fn build_file_create_needs_explicit_path_for_glob_only_paths() {
314 let spec = spec_yaml(
318 "id: t\n\
319 kind: file_exists\n\
320 paths: \"docs/**/*.md\"\n\
321 level: error\n\
322 fix:\n \
323 file_create:\n \
324 content: \"# title\\n\"\n",
325 );
326 let err = build(&spec).unwrap_err().to_string();
327 assert!(err.contains("path"), "unexpected: {err}");
328 }
329
330 #[test]
331 fn evaluate_passes_when_matching_file_present() {
332 let spec = spec_yaml(
333 "id: t\n\
334 kind: file_exists\n\
335 paths: \"README.md\"\n\
336 level: error\n",
337 );
338 let rule = build(&spec).unwrap();
339 let idx = index(&["README.md", "Cargo.toml"]);
340 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
341 assert!(v.is_empty(), "unexpected violations: {v:?}");
342 }
343
344 #[test]
345 fn evaluate_fires_when_no_matching_file_present() {
346 let spec = spec_yaml(
347 "id: t\n\
348 kind: file_exists\n\
349 paths: \"LICENSE\"\n\
350 level: error\n",
351 );
352 let rule = build(&spec).unwrap();
353 let idx = index(&["README.md"]);
354 let v = rule.evaluate(&ctx(Path::new("/fake"), &idx)).unwrap();
355 assert_eq!(v.len(), 1, "expected one violation; got: {v:?}");
356 }
357
358 #[test]
359 fn evaluate_root_only_excludes_nested_matches() {
360 let spec = spec_yaml(
364 "id: t\n\
365 kind: file_exists\n\
366 paths: \"LICENSE\"\n\
367 level: error\n\
368 root_only: true\n",
369 );
370 let rule = build(&spec).unwrap();
371 let idx_only_nested = index(&["pkg/LICENSE"]);
372 let v = rule
373 .evaluate(&ctx(Path::new("/fake"), &idx_only_nested))
374 .unwrap();
375 assert_eq!(v.len(), 1, "nested match shouldn't satisfy root_only");
376 }
377
378 #[test]
379 fn first_literal_path_picks_first_non_glob() {
380 let patterns = vec!["docs/**/*.md".into(), "LICENSE".into(), "README.md".into()];
381 assert_eq!(
382 first_literal_path(&patterns).as_deref(),
383 Some(Path::new("LICENSE")),
384 );
385 }
386
387 #[test]
388 fn first_literal_path_returns_none_when_all_glob() {
389 let patterns = vec!["docs/**/*.md".into(), "src/[a-z]*.rs".into()];
390 assert!(first_literal_path(&patterns).is_none());
391 }
392
393 #[test]
394 fn patterns_of_handles_every_paths_spec_shape() {
395 assert_eq!(patterns_of(&PathsSpec::Single("a".into())), vec!["a"]);
396 assert_eq!(
397 patterns_of(&PathsSpec::Many(vec!["a".into(), "b".into()])),
398 vec!["a", "b"],
399 );
400 assert_eq!(
401 patterns_of(&PathsSpec::IncludeExclude {
402 include: vec!["a".into()],
403 exclude: vec!["b".into()],
404 }),
405 vec!["a"],
406 );
407 }
408}