alint_rules/
file_exists.rs1use std::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 root_only: bool,
29 fixer: Option<FileCreateFixer>,
30}
31
32impl FileExistsRule {
33 fn describe_patterns(&self) -> String {
34 self.patterns.join(", ")
35 }
36}
37
38impl Rule for FileExistsRule {
39 fn id(&self) -> &str {
40 &self.id
41 }
42 fn level(&self) -> Level {
43 self.level
44 }
45 fn policy_url(&self) -> Option<&str> {
46 self.policy_url.as_deref()
47 }
48
49 fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
50 let found = ctx.index.files().any(|entry| {
51 if self.root_only && entry.path.components().count() != 1 {
52 return false;
53 }
54 self.scope.matches(&entry.path)
55 });
56 if found {
57 Ok(Vec::new())
58 } else {
59 let message = self.message.clone().unwrap_or_else(|| {
60 let scope = if self.root_only {
61 " at the repo root"
62 } else {
63 ""
64 };
65 format!(
66 "expected a file matching [{}]{scope}",
67 self.describe_patterns()
68 )
69 });
70 Ok(vec![Violation::new(message)])
71 }
72 }
73
74 fn fixer(&self) -> Option<&dyn Fixer> {
75 self.fixer.as_ref().map(|f| f as &dyn Fixer)
76 }
77}
78
79pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
80 let Some(paths) = &spec.paths else {
81 return Err(Error::rule_config(
82 &spec.id,
83 "file_exists requires a `paths` field",
84 ));
85 };
86 let patterns = patterns_of(paths);
87 let scope = Scope::from_paths_spec(paths)?;
88 let opts: Options = spec
89 .deserialize_options()
90 .unwrap_or(Options { root_only: false });
91 let fixer = match &spec.fix {
92 Some(FixSpec::FileCreate { file_create: cfg }) => {
93 let target = cfg
94 .path
95 .clone()
96 .or_else(|| first_literal_path(&patterns))
97 .ok_or_else(|| {
98 Error::rule_config(
99 &spec.id,
100 "fix.file_create needs a `path` — none of the rule's `paths:` \
101 entries is a literal filename",
102 )
103 })?;
104 Some(FileCreateFixer::new(
105 target,
106 cfg.content.clone(),
107 cfg.create_parents,
108 ))
109 }
110 Some(other) => {
111 return Err(Error::rule_config(
112 &spec.id,
113 format!("fix.{} is not compatible with file_exists", other.op_name()),
114 ));
115 }
116 None => None,
117 };
118 Ok(Box::new(FileExistsRule {
119 id: spec.id.clone(),
120 level: spec.level,
121 policy_url: spec.policy_url.clone(),
122 message: spec.message.clone(),
123 scope,
124 patterns,
125 root_only: opts.root_only,
126 fixer,
127 }))
128}
129
130fn first_literal_path(patterns: &[String]) -> Option<PathBuf> {
135 patterns
136 .iter()
137 .find(|p| !p.chars().any(|c| matches!(c, '*' | '?' | '[' | '{')))
138 .map(PathBuf::from)
139}
140
141fn patterns_of(spec: &PathsSpec) -> Vec<String> {
142 match spec {
143 PathsSpec::Single(s) => vec![s.clone()],
144 PathsSpec::Many(v) => v.clone(),
145 PathsSpec::IncludeExclude { include, .. } => include.clone(),
146 }
147}