alint_rules/
file_exists.rs1use alint_core::{Context, Error, Level, PathsSpec, Result, Rule, RuleSpec, Scope, Violation};
5use serde::Deserialize;
6
7#[derive(Debug, Deserialize)]
8#[serde(deny_unknown_fields)]
9struct Options {
10 #[serde(default)]
11 root_only: bool,
12}
13
14#[derive(Debug)]
15pub struct FileExistsRule {
16 id: String,
17 level: Level,
18 policy_url: Option<String>,
19 message: Option<String>,
20 scope: Scope,
21 patterns: Vec<String>,
22 root_only: bool,
23}
24
25impl FileExistsRule {
26 fn describe_patterns(&self) -> String {
27 self.patterns.join(", ")
28 }
29}
30
31impl Rule for FileExistsRule {
32 fn id(&self) -> &str {
33 &self.id
34 }
35 fn level(&self) -> Level {
36 self.level
37 }
38 fn policy_url(&self) -> Option<&str> {
39 self.policy_url.as_deref()
40 }
41
42 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
43 let found = ctx.index.files().any(|entry| {
44 if self.root_only && entry.path.components().count() != 1 {
45 return false;
46 }
47 self.scope.matches(&entry.path)
48 });
49 if found {
50 Ok(Vec::new())
51 } else {
52 let message = self.message.clone().unwrap_or_else(|| {
53 let scope = if self.root_only {
54 " at the repo root"
55 } else {
56 ""
57 };
58 format!(
59 "expected a file matching [{}]{scope}",
60 self.describe_patterns()
61 )
62 });
63 Ok(vec![Violation::new(message)])
64 }
65 }
66}
67
68pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
69 let Some(paths) = &spec.paths else {
70 return Err(Error::rule_config(
71 &spec.id,
72 "file_exists requires a `paths` field",
73 ));
74 };
75 let patterns = patterns_of(paths);
76 let scope = Scope::from_paths_spec(paths)?;
77 let opts: Options = spec
78 .deserialize_options()
79 .unwrap_or(Options { root_only: false });
80 Ok(Box::new(FileExistsRule {
81 id: spec.id.clone(),
82 level: spec.level,
83 policy_url: spec.policy_url.clone(),
84 message: spec.message.clone(),
85 scope,
86 patterns,
87 root_only: opts.root_only,
88 }))
89}
90
91fn patterns_of(spec: &PathsSpec) -> Vec<String> {
92 match spec {
93 PathsSpec::Single(s) => vec![s.clone()],
94 PathsSpec::Many(v) => v.clone(),
95 PathsSpec::IncludeExclude { include, .. } => include.clone(),
96 }
97}