Skip to main content

alint_rules/
pair.rs

1//! `pair` — for every file matching `primary`, require a file matching the
2//! `partner` template to exist somewhere in the tree.
3//!
4//! The partner template is a path string with `{dir}`, `{stem}`, `{ext}`,
5//! `{basename}`, `{path}`, `{parent_name}` substitutions derived from the
6//! primary match. The resolved partner path is looked up in the engine's
7//! `FileIndex`; a missing match emits a violation anchored on the primary.
8//!
9//! Example (every `.c` needs a same-directory `.h`):
10//!
11//! ```yaml
12//! - id: c-requires-h
13//!   kind: pair
14//!   primary: "**/*.c"
15//!   partner: "{dir}/{stem}.h"
16//!   level: error
17//!   message: "{{ctx.primary}} has no header at {{ctx.partner}}"
18//! ```
19
20use std::path::{Path, PathBuf};
21
22use alint_core::template::{PathTokens, render_message, render_path};
23use alint_core::{Context, Error, Level, Result, Rule, RuleSpec, Scope, Violation};
24use serde::Deserialize;
25
26#[derive(Debug, Deserialize)]
27#[serde(deny_unknown_fields)]
28struct Options {
29    primary: String,
30    partner: String,
31}
32
33#[derive(Debug)]
34pub struct PairRule {
35    id: String,
36    level: Level,
37    policy_url: Option<String>,
38    message: Option<String>,
39    primary_scope: Scope,
40    partner_template: String,
41}
42
43impl Rule for PairRule {
44    fn id(&self) -> &str {
45        &self.id
46    }
47    fn level(&self) -> Level {
48        self.level
49    }
50    fn policy_url(&self) -> Option<&str> {
51        self.policy_url.as_deref()
52    }
53
54    fn requires_full_index(&self) -> bool {
55        // Cross-file: a verdict on a primary file depends on
56        // whether its partner exists *anywhere* in the tree, not
57        // just in the diff. Roadmap §"Monorepo & scale" defines
58        // this rule as opting out of `--changed` filtering. We
59        // also leave `path_scope` as `None` so the engine doesn't
60        // skip-by-intersection — pair always evaluates.
61        true
62    }
63
64    fn evaluate(&self, ctx: &Context<'_>) -> Result<Vec<Violation>> {
65        let mut violations = Vec::new();
66        for entry in ctx.index.files() {
67            if !self.primary_scope.matches(&entry.path) {
68                continue;
69            }
70            let tokens = PathTokens::from_path(&entry.path);
71            let partner_rel = render_path(&self.partner_template, &tokens);
72            if partner_rel.is_empty() {
73                violations.push(
74                    Violation::new(format!(
75                        "partner template {:?} resolved to an empty path for {}",
76                        self.partner_template,
77                        entry.path.display(),
78                    ))
79                    .with_path(entry.path.clone()),
80                );
81                continue;
82            }
83            let partner_path = PathBuf::from(&partner_rel);
84            if resolves_to_self(&partner_path, &entry.path) {
85                violations.push(
86                    Violation::new(format!(
87                        "partner template {:?} resolves to the primary file itself ({}) — \
88                         check that the template differs from the primary",
89                        self.partner_template,
90                        entry.path.display(),
91                    ))
92                    .with_path(entry.path.clone()),
93                );
94                continue;
95            }
96            if ctx.index.find_file(&partner_path).is_some() {
97                continue;
98            }
99            let message = self.format_message(&entry.path, &partner_path);
100            violations.push(Violation::new(message).with_path(entry.path.clone()));
101        }
102        Ok(violations)
103    }
104}
105
106fn resolves_to_self(partner: &Path, primary: &Path) -> bool {
107    partner == primary
108}
109
110impl PairRule {
111    fn format_message(&self, primary: &Path, partner: &Path) -> String {
112        let primary_str = primary.display().to_string();
113        let partner_str = partner.display().to_string();
114        if let Some(user_msg) = self.message.as_deref() {
115            return render_message(user_msg, |ns, key| match (ns, key) {
116                ("ctx", "primary") => Some(primary_str.clone()),
117                ("ctx", "partner") => Some(partner_str.clone()),
118                _ => None,
119            });
120        }
121        format!(
122            "{} has no matching partner at {} (template: {})",
123            primary_str, partner_str, self.partner_template,
124        )
125    }
126}
127
128pub fn build(spec: &RuleSpec) -> Result<Box<dyn Rule>> {
129    let opts: Options = spec
130        .deserialize_options()
131        .map_err(|e| Error::rule_config(&spec.id, format!("invalid options: {e}")))?;
132    if opts.partner.trim().is_empty() {
133        return Err(Error::rule_config(
134            &spec.id,
135            "pair `partner` template must not be empty",
136        ));
137    }
138    let primary_patterns = vec![opts.primary.clone()];
139    let primary_scope = Scope::from_patterns(&primary_patterns)?;
140    Ok(Box::new(PairRule {
141        id: spec.id.clone(),
142        level: spec.level,
143        policy_url: spec.policy_url.clone(),
144        message: spec.message.clone(),
145        primary_scope,
146        partner_template: opts.partner,
147    }))
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use alint_core::{FileEntry, FileIndex};
154    use std::path::Path;
155
156    fn idx(paths: &[&str]) -> FileIndex {
157        FileIndex {
158            entries: paths
159                .iter()
160                .map(|p| FileEntry {
161                    path: std::path::Path::new(p).into(),
162                    is_dir: false,
163                    size: 1,
164                })
165                .collect(),
166        }
167    }
168
169    fn rule(primary: &str, partner: &str, message: Option<&str>) -> PairRule {
170        PairRule {
171            id: "t".into(),
172            level: Level::Error,
173            policy_url: None,
174            message: message.map(ToString::to_string),
175            primary_scope: Scope::from_patterns(&[primary.to_string()]).unwrap(),
176            partner_template: partner.into(),
177        }
178    }
179
180    fn eval(rule: &PairRule, files: &[&str]) -> Vec<Violation> {
181        let index = idx(files);
182        let ctx = Context {
183            root: Path::new("/"),
184            index: &index,
185            registry: None,
186            facts: None,
187            vars: None,
188            git_tracked: None,
189            git_blame: None,
190        };
191        rule.evaluate(&ctx).unwrap()
192    }
193
194    #[test]
195    fn passes_when_partner_exists() {
196        let r = rule("**/*.c", "{dir}/{stem}.h", None);
197        let v = eval(&r, &["src/mod/foo.c", "src/mod/foo.h"]);
198        assert!(v.is_empty(), "unexpected: {v:?}");
199    }
200
201    #[test]
202    fn violates_when_partner_missing() {
203        let r = rule("**/*.c", "{dir}/{stem}.h", None);
204        let v = eval(&r, &["src/mod/foo.c"]);
205        assert_eq!(v.len(), 1);
206        assert_eq!(v[0].path.as_deref(), Some(Path::new("src/mod/foo.c")));
207        assert!(v[0].message.contains("src/mod/foo.h"));
208    }
209
210    #[test]
211    fn violates_per_missing_primary() {
212        let r = rule("**/*.c", "{dir}/{stem}.h", None);
213        let v = eval(
214            &r,
215            &[
216                "src/mod/foo.c",
217                "src/mod/foo.h", // has partner — OK
218                "src/mod/bar.c", // no bar.h
219                "src/mod/baz.c", // no baz.h
220            ],
221        );
222        assert_eq!(v.len(), 2);
223    }
224
225    #[test]
226    fn no_primary_matches_means_no_violation() {
227        let r = rule("**/*.c", "{dir}/{stem}.h", None);
228        let v = eval(&r, &["README.md", "src/mod/other.rs"]);
229        assert!(v.is_empty());
230    }
231
232    #[test]
233    fn user_message_with_ctx_substitution() {
234        let r = rule(
235            "**/*.c",
236            "{dir}/{stem}.h",
237            Some("missing header {{ctx.partner}} for {{ctx.primary}}"),
238        );
239        let v = eval(&r, &["src/foo.c"]);
240        assert_eq!(v.len(), 1);
241        assert_eq!(v[0].message, "missing header src/foo.h for src/foo.c");
242    }
243
244    #[test]
245    fn rejects_partner_resolving_to_self() {
246        // Partner template evaluates to the same file as the primary — caught
247        // as a config/authorship mistake rather than silently passing.
248        let r = rule("**/*.c", "{path}", None);
249        let v = eval(&r, &["src/foo.c"]);
250        assert_eq!(v.len(), 1);
251        assert!(v[0].message.contains("primary file itself"));
252    }
253
254    #[test]
255    fn empty_partner_after_substitution_is_a_violation() {
256        // Template yields "" (only unknown-stripped content would). This
257        // exercises the empty-partner guard.
258        let r = rule("**/*.c", "", None);
259        // Guard is in build(); direct construction bypasses it, so the runtime
260        // guard in evaluate() catches this.
261        let v = eval(&r, &["src/foo.c"]);
262        assert_eq!(v.len(), 1);
263        assert!(v[0].message.contains("empty path"));
264    }
265}