Skip to main content

spec_driven_docs/gates/
spec_verify_hooks_exist.rs

1//! Gate: every rule whose verification runs a hook names a hook that is
2//! still defined.
3//!
4//! A rule can be stated in a spec, given a `Verify:` line, and enforced by
5//! nothing. This reads the hook name out of every verification that runs
6//! pre-commit and asserts the hook is defined, so renaming or deleting one
7//! fails here instead of quietly turning a rule back into a suggestion.
8//! Aliases count, because that is how a spec names a scoped variant.
9
10use std::collections::BTreeSet;
11
12use crate::domain::finding::Finding;
13use crate::domain::rule_id::RuleId;
14
15use crate::gates::{GateCtx, GateResult, Violation, read_text};
16
17/// The rules this gate can cite.
18pub const CITES: &[RuleId] = &[RuleId::VerificationNamesALiveHook];
19
20fn hook_names_in(text: &str) -> impl Iterator<Item = String> + '_ {
21    text.match_indices("pre-commit run ")
22        .filter_map(|(index, needle)| {
23            let after = &text[index + needle.len()..];
24            let name: String = after
25                .chars()
26                .take_while(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '-')
27                .collect();
28            (!name.is_empty()).then_some(name)
29        })
30}
31
32fn defines_hook(config: &str, hook: &str) -> bool {
33    config.lines().any(|line| {
34        let trimmed = line.trim_start();
35        trimmed
36            .strip_prefix("- id: ")
37            .or_else(|| trimmed.strip_prefix("alias: "))
38            .is_some_and(|value| value == hook)
39    })
40}
41
42/// Judge every hook the local specs cite.
43///
44/// # Errors
45///
46/// [`crate::gates::GateError::Io`] when a spec or the pre-commit
47/// configuration cannot be read.
48pub fn run(ctx: &GateCtx, _files: &[String]) -> GateResult {
49    // Both layout predicates read the unfiltered set. A project that
50    // reserves every spec still has a layout and still names hooks; it has
51    // asked this gate to judge none of them, which is an answer rather than
52    // a moved layout.
53    let Some(all_specs) = crate::gates::spec_rule_id_unique::spec_files(ctx) else {
54        return Ok(vec![Violation::Layout(
55            "no specs matched; the layout moved".to_string(),
56        )]);
57    };
58    let mut declared: BTreeSet<String> = BTreeSet::new();
59    for file in &all_specs {
60        declared.extend(hook_names_in(&read_text(ctx, file)?));
61    }
62    if declared.is_empty() {
63        return Ok(vec![Violation::Layout(
64            "no spec names a hook; the Verify shape moved".to_string(),
65        )]);
66    }
67
68    let mut hooks: BTreeSet<String> = BTreeSet::new();
69    for file in ctx.retained(all_specs) {
70        hooks.extend(hook_names_in(&read_text(ctx, &file)?));
71    }
72    let config = read_text(ctx, ".pre-commit-config.yaml")?;
73    Ok(hooks
74        .into_iter()
75        .filter(|hook| !defines_hook(&config, hook))
76        .map(|hook| Violation::Finding(Finding::global(RuleId::VerificationNamesALiveHook, hook)))
77        .collect())
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    fn fixture(hook_id: &str) -> tempfile::TempDir {
85        let dir = tempfile::tempdir().unwrap();
86        let specs = dir.path().join("_docs/specs");
87        std::fs::create_dir_all(&specs).unwrap();
88        std::fs::write(
89            specs.join("SPEC-sample.md"),
90            "### `sample:works` — Works\n\nVerify: `pre-commit run sample-hook --all-files`\n",
91        )
92        .unwrap();
93        std::fs::write(
94            dir.path().join(".pre-commit-config.yaml"),
95            format!(
96                "repos:\n  - repo: local\n    hooks:\n      - id: {hook_id}\n        entry: true\n"
97            ),
98        )
99        .unwrap();
100        dir
101    }
102
103    fn run_in(dir: &tempfile::TempDir) -> Vec<String> {
104        let ctx = GateCtx::new(dir.path().to_str().unwrap());
105        run(&ctx, &[])
106            .unwrap()
107            .iter()
108            .map(ToString::to_string)
109            .collect()
110    }
111
112    #[test]
113    fn accepts_a_cited_hook_that_exists() {
114        assert!(run_in(&fixture("sample-hook")).is_empty());
115    }
116
117    #[test]
118    fn rejects_a_cited_hook_that_was_renamed() {
119        let out = run_in(&fixture("renamed-hook"));
120        assert_eq!(
121            out,
122            vec!["FAIL docs-specs:verification-names-a-live-hook: sample-hook".to_string()]
123        );
124    }
125
126    #[test]
127    fn a_suffixed_rename_does_not_satisfy_the_citation() {
128        assert_eq!(run_in(&fixture("sample-hook-v2")).len(), 1);
129    }
130
131    #[test]
132    fn an_alias_satisfies_the_citation() {
133        let dir = fixture("other");
134        let config = dir.path().join(".pre-commit-config.yaml");
135        let text = std::fs::read_to_string(&config).unwrap() + "        alias: sample-hook\n";
136        std::fs::write(&config, text).unwrap();
137        assert!(run_in(&dir).is_empty());
138    }
139}