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    }
234    out
235}
236
237/// The `files:` and `exclude:` a hook entry declares, by hook id.
238///
239/// Read from rendered or installed YAML alike, so the two can be compared.
240/// A block an older release rendered may carry hooks this renderer never
241/// emits, so the comparison is per gate rather than over the whole region.
242#[must_use]
243pub fn selectors(
244    block: &str,
245) -> std::collections::BTreeMap<String, (Option<String>, Option<String>)> {
246    let mut found = std::collections::BTreeMap::new();
247    let mut current: Option<String> = None;
248    for line in block.lines() {
249        let trimmed = line.trim_start();
250        if let Some(id) = trimmed.strip_prefix("- id: ") {
251            current = Some(id.trim().to_string());
252            found.insert(id.trim().to_string(), (None, None));
253            continue;
254        }
255        let Some(id) = current.as_ref() else { continue };
256        if let Some(value) = trimmed.strip_prefix("files: ") {
257            if let Some(entry) = found.get_mut(id) {
258                entry.0 = Some(value.trim().to_string());
259            }
260        } else if let Some(value) = trimmed.strip_prefix("exclude: ")
261            && let Some(entry) = found.get_mut(id)
262        {
263            entry.1 = Some(value.trim().to_string());
264        }
265    }
266    found
267}
268
269/// Render the complete managed block an instance's configuration carries:
270/// markers, the verifier hook, and every gate.
271#[must_use]
272pub fn render_block(options: &RenderOptions) -> String {
273    let indent = &options.indent;
274    let mut out = String::new();
275    out.push_str(marker::BEGIN);
276    out.push('\n');
277    let _ = writeln!(out, "{indent}- repo: local");
278    let _ = writeln!(out, "{indent}  hooks:");
279    let _ = writeln!(out, "{indent}    - id: spec-driven-docs-verify");
280    let _ = writeln!(out, "{indent}      name: verify spec-driven docs instance");
281    let _ = writeln!(out, "{indent}      entry: {} verify", options.entry);
282    let _ = writeln!(out, "{indent}      language: {LANGUAGE}");
283    let _ = writeln!(out, "{indent}      always_run: true");
284    let _ = writeln!(out, "{indent}      pass_filenames: false");
285    out.push_str(&render_gates(options));
286    out.push_str(&render_markdownlint(options));
287    out.push_str(marker::END);
288    out.push('\n');
289    out
290}
291
292/// Wire the markdown linter, which reads its configuration through its own
293/// discovery.
294///
295/// One plain hook, with no `--config`, no `files:`, and no `exclude:`. The
296/// landing's configurations sit where the linter discovers them, so a hook
297/// run, a direct run, and an editor read the same settings. The linter's
298/// scope lives in its own `ignores`, so `reserved:` does not reach this hook:
299/// a commit that skipped a file a direct run still judged would put the
300/// scope in two places. The one dependency is the custom rule the root seed
301/// loads, pinned, because pre-commit installs it into the hook's own
302/// environment.
303fn render_markdownlint(options: &RenderOptions) -> String {
304    let indent = &options.indent;
305    let mut out = String::new();
306    let _ = writeln!(out, "{indent}- repo: {}", markdownlint::REPO);
307    let _ = writeln!(out, "{indent}  rev: {}", markdownlint::REV);
308    let _ = writeln!(out, "{indent}  hooks:");
309    let _ = writeln!(out, "{indent}    - id: markdownlint-cli2");
310    let _ = writeln!(
311        out,
312        "{indent}      additional_dependencies: [{}]",
313        quoted(&markdownlint::relative_links_dependency())
314    );
315    out
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn the_linter_is_one_plain_hook_that_carries_the_pin() {
324        let out = render_markdownlint(&RenderOptions::default());
325        assert_eq!(
326            out,
327            "  - repo: https://github.com/DavidAnson/markdownlint-cli2\n    rev: v0.23.3\n    hooks:\n      - id: markdownlint-cli2\n        additional_dependencies: ['markdownlint-rule-relative-links@5.1.3']\n"
328        );
329        for absent in ["--config", "files:", "exclude:", "alias:", "args:"] {
330            assert!(!out.contains(absent), "{absent} in {out}");
331        }
332    }
333
334    /// The linter's scope lives in its own configuration, so a reserved
335    /// path reaches sdd's gates and leaves the linter hook alone.
336    #[test]
337    fn a_reserved_path_leaves_the_linter_hook_unchanged() {
338        let declared = RenderOptions {
339            declaration: InstanceConfig::parse("reserved: ['vendor/**']\n").unwrap(),
340            ..RenderOptions::default()
341        };
342        assert_eq!(
343            render_markdownlint(&declared),
344            render_markdownlint(&RenderOptions::default())
345        );
346        assert!(render_gates(&declared).contains("vendor/"));
347    }
348
349    /// A rule the root seed loads is a module the hook's environment must
350    /// hold, or the hook exits on an import error before it judges a file.
351    #[test]
352    fn every_rule_the_root_seed_loads_is_a_hook_dependency() {
353        let seed = std::str::from_utf8(
354            crate::embedded::asset("instance/seeds/markdownlint-cli2.jsonc").unwrap(),
355        )
356        .unwrap();
357        let json: String = seed
358            .lines()
359            .filter(|line| !line.trim_start().starts_with("//"))
360            .collect::<Vec<_>>()
361            .join("\n");
362        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
363        let rules = parsed["customRules"].as_array().unwrap();
364        assert!(!rules.is_empty());
365        let out = render_markdownlint(&RenderOptions::default());
366        for rule in rules {
367            let rule = rule.as_str().unwrap();
368            assert!(
369                out.contains(&format!("'{rule}@")),
370                "{rule} is not a dependency: {out}"
371            );
372        }
373    }
374
375    #[test]
376    fn every_gate_renders_its_wiring_fields() {
377        let out = render_gates(&RenderOptions::default());
378        assert!(out.starts_with("      - id: adr-cites-a-live-rule\n"));
379        assert!(out.contains("        entry: sdd gate adr-filename-shape\n"));
380        assert!(out.contains("        language: system\n"));
381        assert!(out.contains("        types: [markdown]\n"));
382        assert_eq!(out.matches("- id: ").count(), crate::gates::GATES.len());
383    }
384
385    /// The profile picks the root, so a `docs` instance wires `docs` paths.
386    #[test]
387    fn the_docs_root_reaches_every_templated_pattern() {
388        let out = render_gates(&RenderOptions {
389            docs_root: "docs".to_string(),
390            ..RenderOptions::default()
391        });
392        assert!(out.contains("        files: '^docs/decisions/[^/]*\\.md$'\n"));
393        assert!(out.contains("        exclude: '^docs/decisions/.*$'\n"));
394        assert!(!out.contains("{docs_root}"));
395    }
396
397    #[test]
398    fn block_style_carries_the_markers_and_the_verifier() {
399        let out = render_block(&RenderOptions::default());
400        assert!(out.starts_with("# BEGIN spec-driven-docs managed\n"));
401        assert!(out.ends_with("# END spec-driven-docs managed\n"));
402        assert!(out.contains("      - id: spec-driven-docs-verify\n"));
403        assert!(out.contains("        entry: sdd verify\n"));
404        assert!(out.contains("      - id: adr-filename-shape\n"));
405        assert!(out.contains("        files: '^_docs/decisions/[^/]*\\.md$'\n"));
406    }
407
408    #[test]
409    fn a_glob_projects_onto_an_anchored_regex() {
410        assert_eq!(glob_to_regex("README.md"), r"^README\.md$");
411        assert_eq!(glob_to_regex("_docs/*.md"), r"^_docs/[^/]*\.md$");
412        assert_eq!(glob_to_regex("_docs/**/*.md"), r"^_docs/(?:.*/)?[^/]*\.md$");
413        assert_eq!(glob_to_regex("**/AGENTS.md"), r"^(?:.*/)?AGENTS\.md$");
414        assert_eq!(glob_to_regex("vendor/**"), r"^vendor/.*$");
415        assert_eq!(glob_to_regex("a?.md"), r"^a[^/]\.md$");
416        assert_eq!(glob_to_regex("[abc].md"), r"^[abc]\.md$");
417        assert_eq!(glob_to_regex("{SPEC,ADR}-a.md"), r"^(?:SPEC|ADR)-a\.md$");
418    }
419
420    #[test]
421    fn several_includes_render_as_one_alternation() {
422        let rendered = render_patterns(&["a.md", "b/*.md"], "_docs").expect("two patterns render");
423        assert_eq!(rendered, r"^(?:a\.md|b/[^/]*\.md)$");
424        assert_eq!(render_patterns(&[], "_docs"), None);
425    }
426
427    /// The one-directional contract, asserted over every row: pre-commit's
428    /// rendered selection matches everything the matcher judges.
429    ///
430    /// SATISFIES release:a-delivered-gate-reads-what-the-convention-owns
431    #[test]
432    fn the_rendered_pattern_is_a_superset_of_the_matcher() {
433        use crate::domain::path_filter::{Layer, PathFilter, Pattern};
434
435        let corpus = [
436            "README.md",
437            "AGENTS.md",
438            "method/AGENTS.md",
439            "method/gates.md",
440            "CHANGELOG.md",
441            "_docs/specs/SPEC-release.md",
442            "_docs/decisions/ADR-a-choice.md",
443            "_docs/reference/known-issues/KI-a-case.md",
444            "_docs/reference/tracking.yaml",
445            "_docs/guides/release.md",
446            "comparison-docs/COMPARISON-tools.md",
447            ".spec-driven-docs/manifest.json",
448            "src/gates.rs",
449            "vendor/third/lib.rs",
450        ];
451
452        for gate in GATES {
453            let filter = PathFilter::build(
454                gate.include
455                    .iter()
456                    .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
457                    .collect(),
458                gate.exclude
459                    .iter()
460                    .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
461                    .collect(),
462            )
463            .expect("every registry pattern compiles");
464
465            let files = render_patterns(gate.include, "_docs");
466            let excludes = render_patterns(gate.exclude, "_docs");
467
468            for path in corpus {
469                if !filter.judges(camino::Utf8Path::new(path)) {
470                    continue;
471                }
472                if let Some(files) = &files {
473                    let selector = regex::Regex::new(files).expect("the projection compiles");
474                    assert!(
475                        selector.is_match(path),
476                        "{}: the matcher judges {path} and the rendered files: {files} does not select it",
477                        gate.id
478                    );
479                }
480                if let Some(excludes) = &excludes {
481                    let selector = regex::Regex::new(excludes).expect("the projection compiles");
482                    assert!(
483                        !selector.is_match(path),
484                        "{}: the matcher judges {path} and the rendered exclude: {excludes} drops it",
485                        gate.id
486                    );
487                }
488            }
489        }
490    }
491
492    #[test]
493    fn always_run_gates_do_not_take_filenames() {
494        let out = render_gates(&RenderOptions::default());
495        assert_eq!(
496            out.matches("always_run: true").count(),
497            out.matches("pass_filenames: false").count()
498        );
499    }
500
501    #[test]
502    fn an_apostrophe_in_a_name_would_be_doubled() {
503        assert_eq!(quoted("it's"), "'it''s'");
504    }
505
506    #[test]
507    fn the_block_splices_into_a_plain_config() {
508        let block = render_block(&RenderOptions::default());
509        let spliced = crate::domain::marker::splice("repos:\n", &block).unwrap();
510        let (base, found) = crate::domain::marker::split_block(&spliced).unwrap();
511        assert_eq!(base, "repos:\n");
512        assert_eq!(found.as_deref(), Some(block.as_str()));
513    }
514}