Skip to main content

spec_driven_docs/services/
hooks_render.rs

1//! Render the gate registry as the managed pre-commit block.
2//!
3//! The registry is the one declaration and this is its one delivery: the
4//! block an instance's configuration carries, rendered at install time and
5//! never committed anywhere in between. A gate reaches an instance because
6//! it is in the registry, so it cannot reach the payload and miss the
7//! wiring. What the registry contains is `gates`' business; where the
8//! output lands is the caller's.
9//!
10//! There is deliberately no second shape. A `.pre-commit-hooks.yaml` would
11//! serve repositories that never adopt this framework, and most gates read
12//! an instance layout those repositories do not have.
13
14use std::fmt::Write as _;
15
16use crate::domain::instance_config::InstanceConfig;
17use crate::domain::markdownlint;
18use crate::domain::marker;
19use crate::domain::profile::render_root;
20use crate::gates::GATES;
21
22/// The pre-commit language every delivered gate declares.
23///
24/// An instance runs `sdd` from its own PATH, which is what `system` means;
25/// no other language has a caller.
26const LANGUAGE: &str = "system";
27
28/// Everything a render depends on.
29#[derive(Debug, Clone)]
30pub struct RenderOptions {
31    /// What replaces `{docs_root}` in wiring patterns — the literal root
32    /// the instance's profile selected.
33    pub docs_root: String,
34    /// The command prefix an entry invokes, e.g. `sdd` or `cargo run -q --`.
35    pub entry: String,
36    /// The sequence-item indentation of the consumer's `repos:` entries.
37    pub indent: String,
38    /// What the project declared about what its gates judge.
39    ///
40    /// The block is rendered from this, so the project never edits the
41    /// block and an upgrade never meets its choice.
42    pub declaration: InstanceConfig,
43}
44
45impl Default for RenderOptions {
46    fn default() -> Self {
47        Self {
48            docs_root: "_docs".to_string(),
49            entry: "sdd".to_string(),
50            indent: "  ".to_string(),
51            declaration: InstanceConfig::default(),
52        }
53    }
54}
55
56/// A single-quoted YAML scalar; an apostrophe is escaped by doubling it.
57fn quoted(value: &str) -> String {
58    format!("'{}'", value.replace('\'', "''"))
59}
60
61/// Escape one literal character for a regex.
62fn escape(out: &mut String, ch: char) {
63    if ".^$+()|[]{}\\*?".contains(ch) {
64        out.push('\\');
65    }
66    out.push(ch);
67}
68
69/// Project one glob onto a Python regex for pre-commit's `files:` field.
70///
71/// # The contract is one-directional
72///
73/// The rendered selection MUST match every path the matcher judges, and MAY
74/// match more. `globset` compiles to a Rust byte regex and pre-commit
75/// applies Python `re.search`, and the two languages are not the same, so
76/// promising equivalence would mean writing and maintaining a converter
77/// between them. `PathFilter` stays authoritative at runtime and drops the
78/// excess, which makes a lossy projection cost a wasted invocation and never
79/// a missed violation.
80///
81/// The restricted grammar `crate::domain::path_filter` enforces is what
82/// makes the projection small: a leading `!` or `#`, an absolute path, and a
83/// `..` component are already refused, so this handles `*`, `**`, `?`, a
84/// character class, a brace alternation, and literals.
85fn glob_to_regex(glob: &str) -> String {
86    let mut out = String::from("^");
87    let bytes: Vec<char> = glob.chars().collect();
88    let mut i = 0;
89    while i < bytes.len() {
90        match bytes[i] {
91            '*' if bytes.get(i + 1) == Some(&'*') => {
92                if bytes.get(i + 2) == Some(&'/') {
93                    // `**/` matches zero or more leading directories.
94                    out.push_str("(?:.*/)?");
95                    i += 3;
96                } else {
97                    out.push_str(".*");
98                    i += 2;
99                }
100            }
101            '*' => {
102                out.push_str("[^/]*");
103                i += 1;
104            }
105            '?' => {
106                out.push_str("[^/]");
107                i += 1;
108            }
109            '[' => {
110                let close = bytes[i..].iter().position(|c| *c == ']').map(|p| i + p);
111                if let Some(close) = close {
112                    out.push('[');
113                    let mut j = i + 1;
114                    if bytes.get(j) == Some(&'!') {
115                        out.push('^');
116                        j += 1;
117                    }
118                    for ch in &bytes[j..close] {
119                        out.push(*ch);
120                    }
121                    out.push(']');
122                    i = close + 1;
123                } else {
124                    escape(&mut out, '[');
125                    i += 1;
126                }
127            }
128            '{' => {
129                let close = bytes[i..].iter().position(|c| *c == '}').map(|p| i + p);
130                if let Some(close) = close {
131                    out.push_str("(?:");
132                    let branches: String = bytes[i + 1..close].iter().collect();
133                    let rendered: Vec<String> = branches
134                        .split(',')
135                        .map(|branch| {
136                            let whole = glob_to_regex(branch);
137                            whole
138                                .trim_start_matches('^')
139                                .trim_end_matches('$')
140                                .to_string()
141                        })
142                        .collect();
143                    out.push_str(&rendered.join("|"));
144                    out.push(')');
145                    i = close + 1;
146                } else {
147                    escape(&mut out, '{');
148                    i += 1;
149                }
150            }
151            ch => {
152                escape(&mut out, ch);
153                i += 1;
154            }
155        }
156    }
157    out.push('$');
158    out
159}
160
161/// Project many globs onto one alternation, as pre-commit takes one regex.
162fn render_patterns(globs: &[&str], docs_root: &str) -> Option<String> {
163    let rendered: Vec<String> = globs
164        .iter()
165        .map(|glob| glob_to_regex(&render_root(glob, docs_root)))
166        .collect();
167    match rendered.len() {
168        0 => None,
169        1 => Some(rendered[0].clone()),
170        _ => {
171            let inner: Vec<String> = rendered
172                .iter()
173                .map(|r| r.trim_start_matches('^').trim_end_matches('$').to_string())
174                .collect();
175            Some(format!("^(?:{})$", inner.join("|")))
176        }
177    }
178}
179
180/// Render the gate entries alone, without the markers or the verifier.
181fn render_gates(options: &RenderOptions) -> String {
182    let item = format!("{0}    - ", options.indent);
183    let field = format!("{0}      ", options.indent);
184    let mut out = String::new();
185    for gate in GATES {
186        let _ = writeln!(out, "{item}id: {}", gate.id);
187        let _ = writeln!(out, "{field}name: {}", quoted(gate.name));
188        let _ = writeln!(out, "{field}entry: {} gate {}", options.entry, gate.id);
189        let _ = writeln!(out, "{field}language: {LANGUAGE}");
190        // An `always_run` row takes no filenames, so pre-commit ignores
191        // `files:` and `exclude:` there. The registry still declares what
192        // the row judges, and `PathFilter` still applies it; emitting a
193        // selector pre-commit never reads would tell a reader of the block
194        // something untrue.
195        let declared = options.declaration.for_gate(gate.id);
196        // A project `include` replaces the registry's, and every `exclude`
197        // layer extends. `instance_config` states the algorithm; this only
198        // projects the result.
199        let include: Vec<&str> = declared.filter(|d| !d.include.is_empty()).map_or_else(
200            || gate.include.to_vec(),
201            |declared| declared.include.iter().map(String::as_str).collect(),
202        );
203        let exclude: Vec<&str> = gate
204            .exclude
205            .iter()
206            .copied()
207            .chain(
208                declared
209                    .into_iter()
210                    .flat_map(|d| &d.exclude)
211                    .map(String::as_str),
212            )
213            .chain(options.declaration.reserved.iter().map(String::as_str))
214            .collect();
215
216        if !gate.always_run
217            && let Some(files) = render_patterns(&include, &options.docs_root)
218        {
219            let _ = writeln!(out, "{field}files: {}", quoted(&files));
220        }
221        if let Some(types) = gate.types {
222            let _ = writeln!(out, "{field}types: [{types}]");
223        }
224        if !gate.always_run
225            && let Some(exclude) = render_patterns(&exclude, &options.docs_root)
226        {
227            let _ = writeln!(out, "{field}exclude: {}", quoted(&exclude));
228        }
229        if gate.always_run {
230            let _ = writeln!(out, "{field}always_run: true");
231            let _ = writeln!(out, "{field}pass_filenames: false");
232        }
233        // pre-commit hides the output of a passing hook unless it is
234        // verbose, and a warning gate passes.
235        if gate.warns {
236            let _ = writeln!(out, "{field}verbose: true");
237        }
238    }
239    out
240}
241
242/// The `files:` and `exclude:` a hook entry declares, by hook id.
243///
244/// Read from rendered or installed YAML alike, so the two can be compared.
245/// A block an older release rendered may carry hooks this renderer never
246/// emits, so the comparison is per gate rather than over the whole region.
247#[must_use]
248pub fn selectors(
249    block: &str,
250) -> std::collections::BTreeMap<String, (Option<String>, Option<String>)> {
251    let mut found = std::collections::BTreeMap::new();
252    let mut current: Option<String> = None;
253    for line in block.lines() {
254        let trimmed = line.trim_start();
255        if let Some(id) = trimmed.strip_prefix("- id: ") {
256            current = Some(id.trim().to_string());
257            found.insert(id.trim().to_string(), (None, None));
258            continue;
259        }
260        let Some(id) = current.as_ref() else { continue };
261        if let Some(value) = trimmed.strip_prefix("files: ") {
262            if let Some(entry) = found.get_mut(id) {
263                entry.0 = Some(value.trim().to_string());
264            }
265        } else if let Some(value) = trimmed.strip_prefix("exclude: ")
266            && let Some(entry) = found.get_mut(id)
267        {
268            entry.1 = Some(value.trim().to_string());
269        }
270    }
271    found
272}
273
274/// Render the complete managed block an instance's configuration carries:
275/// markers, the verifier hook, and every gate.
276#[must_use]
277pub fn render_block(options: &RenderOptions) -> String {
278    let indent = &options.indent;
279    let mut out = String::new();
280    out.push_str(marker::BEGIN);
281    out.push('\n');
282    let _ = writeln!(out, "{indent}- repo: local");
283    let _ = writeln!(out, "{indent}  hooks:");
284    let _ = writeln!(out, "{indent}    - id: spec-driven-docs-verify");
285    let _ = writeln!(out, "{indent}      name: verify spec-driven docs instance");
286    let _ = writeln!(out, "{indent}      entry: {} verify", options.entry);
287    let _ = writeln!(out, "{indent}      language: {LANGUAGE}");
288    let _ = writeln!(out, "{indent}      always_run: true");
289    let _ = writeln!(out, "{indent}      pass_filenames: false");
290    out.push_str(&render_gates(options));
291    out.push_str(&render_markdownlint(options));
292    out.push_str(marker::END);
293    out.push('\n');
294    out
295}
296
297/// Wire the markdown linter, which reads its configuration through its own
298/// discovery.
299///
300/// One plain hook, with no `--config`, no `files:`, and no `exclude:`. The
301/// landing's configurations sit where the linter discovers them, so a hook
302/// run, a direct run, and an editor read the same settings. The linter's
303/// scope lives in its own `ignores`, so `reserved:` does not reach this hook:
304/// a commit that skipped a file a direct run still judged would put the
305/// scope in two places. The one dependency is the custom rule the root seed
306/// loads, pinned, because pre-commit installs it into the hook's own
307/// environment.
308fn render_markdownlint(options: &RenderOptions) -> String {
309    let indent = &options.indent;
310    let mut out = String::new();
311    let _ = writeln!(out, "{indent}- repo: {}", markdownlint::REPO);
312    let _ = writeln!(out, "{indent}  rev: {}", markdownlint::REV);
313    let _ = writeln!(out, "{indent}  hooks:");
314    let _ = writeln!(out, "{indent}    - id: markdownlint-cli2");
315    let _ = writeln!(
316        out,
317        "{indent}      additional_dependencies: [{}]",
318        quoted(&markdownlint::relative_links_dependency())
319    );
320    out
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn the_linter_is_one_plain_hook_that_carries_the_pin() {
329        let out = render_markdownlint(&RenderOptions::default());
330        assert_eq!(
331            out,
332            "  - repo: https://github.com/DavidAnson/markdownlint-cli2\n    rev: v0.24.0\n    hooks:\n      - id: markdownlint-cli2\n        additional_dependencies: ['markdownlint-rule-relative-links@5.1.3']\n"
333        );
334        for absent in ["--config", "files:", "exclude:", "alias:", "args:"] {
335            assert!(!out.contains(absent), "{absent} in {out}");
336        }
337    }
338
339    /// The linter's scope lives in its own configuration, so a reserved
340    /// path reaches sdd's gates and leaves the linter hook alone.
341    #[test]
342    fn a_reserved_path_leaves_the_linter_hook_unchanged() {
343        let declared = RenderOptions {
344            declaration: InstanceConfig::parse("reserved: ['vendor/**']\n").unwrap(),
345            ..RenderOptions::default()
346        };
347        assert_eq!(
348            render_markdownlint(&declared),
349            render_markdownlint(&RenderOptions::default())
350        );
351        assert!(render_gates(&declared).contains("vendor/"));
352    }
353
354    /// A rule the root seed loads is a module the hook's environment must
355    /// hold, or the hook exits on an import error before it judges a file.
356    #[test]
357    fn every_rule_the_root_seed_loads_is_a_hook_dependency() {
358        let seed = std::str::from_utf8(
359            crate::embedded::asset("instance/seeds/markdownlint-cli2.jsonc").unwrap(),
360        )
361        .unwrap();
362        let json: String = seed
363            .lines()
364            .filter(|line| !line.trim_start().starts_with("//"))
365            .collect::<Vec<_>>()
366            .join("\n");
367        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
368        let rules = parsed["customRules"].as_array().unwrap();
369        assert!(!rules.is_empty());
370        let out = render_markdownlint(&RenderOptions::default());
371        for rule in rules {
372            let rule = rule.as_str().unwrap();
373            assert!(
374                out.contains(&format!("'{rule}@")),
375                "{rule} is not a dependency: {out}"
376            );
377        }
378    }
379
380    #[test]
381    fn every_gate_renders_its_wiring_fields() {
382        let out = render_gates(&RenderOptions::default());
383        assert!(out.starts_with("      - id: adr-cites-a-live-rule\n"));
384        assert!(out.contains("        entry: sdd gate adr-filename-shape\n"));
385        assert!(out.contains("        language: system\n"));
386        assert!(out.contains("        types: [markdown]\n"));
387        assert_eq!(out.matches("- id: ").count(), crate::gates::GATES.len());
388    }
389
390    /// The profile picks the root, so a `docs` instance wires `docs` paths.
391    #[test]
392    fn the_docs_root_reaches_every_templated_pattern() {
393        let out = render_gates(&RenderOptions {
394            docs_root: "docs".to_string(),
395            ..RenderOptions::default()
396        });
397        assert!(out.contains("        files: '^docs/decisions/[^/]*\\.md$'\n"));
398        assert!(out.contains("        exclude: '^docs/decisions/.*$'\n"));
399        assert!(!out.contains("{docs_root}"));
400    }
401
402    #[test]
403    fn block_style_carries_the_markers_and_the_verifier() {
404        let out = render_block(&RenderOptions::default());
405        assert!(out.starts_with("# BEGIN spec-driven-docs managed\n"));
406        assert!(out.ends_with("# END spec-driven-docs managed\n"));
407        assert!(out.contains("      - id: spec-driven-docs-verify\n"));
408        assert!(out.contains("        entry: sdd verify\n"));
409        assert!(out.contains("      - id: adr-filename-shape\n"));
410        assert!(out.contains("        files: '^_docs/decisions/[^/]*\\.md$'\n"));
411    }
412
413    #[test]
414    fn a_glob_projects_onto_an_anchored_regex() {
415        assert_eq!(glob_to_regex("README.md"), r"^README\.md$");
416        assert_eq!(glob_to_regex("_docs/*.md"), r"^_docs/[^/]*\.md$");
417        assert_eq!(glob_to_regex("_docs/**/*.md"), r"^_docs/(?:.*/)?[^/]*\.md$");
418        assert_eq!(glob_to_regex("**/AGENTS.md"), r"^(?:.*/)?AGENTS\.md$");
419        assert_eq!(glob_to_regex("vendor/**"), r"^vendor/.*$");
420        assert_eq!(glob_to_regex("a?.md"), r"^a[^/]\.md$");
421        assert_eq!(glob_to_regex("[abc].md"), r"^[abc]\.md$");
422        assert_eq!(glob_to_regex("{SPEC,ADR}-a.md"), r"^(?:SPEC|ADR)-a\.md$");
423    }
424
425    #[test]
426    fn several_includes_render_as_one_alternation() {
427        let rendered = render_patterns(&["a.md", "b/*.md"], "_docs").expect("two patterns render");
428        assert_eq!(rendered, r"^(?:a\.md|b/[^/]*\.md)$");
429        assert_eq!(render_patterns(&[], "_docs"), None);
430    }
431
432    /// The one-directional contract, asserted over every row: pre-commit's
433    /// rendered selection matches everything the matcher judges.
434    ///
435    /// SATISFIES release:a-delivered-gate-reads-what-the-convention-owns
436    #[test]
437    fn the_rendered_pattern_is_a_superset_of_the_matcher() {
438        use crate::domain::path_filter::{Layer, PathFilter, Pattern};
439
440        let corpus = [
441            "README.md",
442            "AGENTS.md",
443            "method/AGENTS.md",
444            "method/gates.md",
445            "CHANGELOG.md",
446            "_docs/specs/SPEC-release.md",
447            "_docs/decisions/ADR-a-choice.md",
448            "_docs/reference/known-issues/KI-a-case.md",
449            "_docs/reference/tracking.yaml",
450            "_docs/guides/release.md",
451            "comparison-docs/COMPARISON-tools.md",
452            ".spec-driven-docs/manifest.json",
453            "src/gates.rs",
454            "vendor/third/lib.rs",
455        ];
456
457        for gate in GATES {
458            let filter = PathFilter::build(
459                gate.include
460                    .iter()
461                    .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
462                    .collect(),
463                gate.exclude
464                    .iter()
465                    .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
466                    .collect(),
467            )
468            .expect("every registry pattern compiles");
469
470            let files = render_patterns(gate.include, "_docs");
471            let excludes = render_patterns(gate.exclude, "_docs");
472
473            for path in corpus {
474                if !filter.judges(camino::Utf8Path::new(path)) {
475                    continue;
476                }
477                if let Some(files) = &files {
478                    let selector = regex::Regex::new(files).expect("the projection compiles");
479                    assert!(
480                        selector.is_match(path),
481                        "{}: the matcher judges {path} and the rendered files: {files} does not select it",
482                        gate.id
483                    );
484                }
485                if let Some(excludes) = &excludes {
486                    let selector = regex::Regex::new(excludes).expect("the projection compiles");
487                    assert!(
488                        !selector.is_match(path),
489                        "{}: the matcher judges {path} and the rendered exclude: {excludes} drops it",
490                        gate.id
491                    );
492                }
493            }
494        }
495    }
496
497    #[test]
498    fn always_run_gates_do_not_take_filenames() {
499        let out = render_gates(&RenderOptions::default());
500        assert_eq!(
501            out.matches("always_run: true").count(),
502            out.matches("pass_filenames: false").count()
503        );
504    }
505
506    #[test]
507    fn an_apostrophe_in_a_name_would_be_doubled() {
508        assert_eq!(quoted("it's"), "'it''s'");
509    }
510
511    #[test]
512    fn the_block_splices_into_a_plain_config() {
513        let block = render_block(&RenderOptions::default());
514        let spliced = crate::domain::marker::splice("repos:\n", &block).unwrap();
515        let (base, found) = crate::domain::marker::split_block(&spliced).unwrap();
516        assert_eq!(base, "repos:\n");
517        assert_eq!(found.as_deref(), Some(block.as_str()));
518    }
519}