spec_driven_docs/services/
hooks_render.rs1use 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
22const LANGUAGE: &str = "system";
27
28#[derive(Debug, Clone)]
30pub struct RenderOptions {
31 pub docs_root: String,
34 pub entry: String,
36 pub indent: String,
38 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
56fn quoted(value: &str) -> String {
58 format!("'{}'", value.replace('\'', "''"))
59}
60
61fn escape(out: &mut String, ch: char) {
63 if ".^$+()|[]{}\\*?".contains(ch) {
64 out.push('\\');
65 }
66 out.push(ch);
67}
68
69fn 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 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
161fn 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
180fn 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 let declared = options.declaration.for_gate(gate.id);
196 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 if gate.warns {
236 let _ = writeln!(out, "{field}verbose: true");
237 }
238 }
239 out
240}
241
242#[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#[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
297fn 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 #[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 #[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 #[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]
405 fn the_unwrapped_prose_hook_carries_no_changelog_exclude() {
406 let out = render_block(&RenderOptions::default());
407 assert!(!out.contains("CHANGELOG"), "{out}");
408 let hooks = selectors(&out);
409 let (files, exclude) = &hooks["prose-stays-unwrapped"];
410 assert!(files.is_some());
411 assert_eq!(exclude, &None);
412 }
413
414 #[test]
415 fn block_style_carries_the_markers_and_the_verifier() {
416 let out = render_block(&RenderOptions::default());
417 assert!(out.starts_with("# BEGIN spec-driven-docs managed\n"));
418 assert!(out.ends_with("# END spec-driven-docs managed\n"));
419 assert!(out.contains(" - id: spec-driven-docs-verify\n"));
420 assert!(out.contains(" entry: sdd verify\n"));
421 assert!(out.contains(" - id: adr-filename-shape\n"));
422 assert!(out.contains(" files: '^_docs/decisions/[^/]*\\.md$'\n"));
423 }
424
425 #[test]
426 fn a_glob_projects_onto_an_anchored_regex() {
427 assert_eq!(glob_to_regex("README.md"), r"^README\.md$");
428 assert_eq!(glob_to_regex("_docs/*.md"), r"^_docs/[^/]*\.md$");
429 assert_eq!(glob_to_regex("_docs/**/*.md"), r"^_docs/(?:.*/)?[^/]*\.md$");
430 assert_eq!(glob_to_regex("**/AGENTS.md"), r"^(?:.*/)?AGENTS\.md$");
431 assert_eq!(glob_to_regex("vendor/**"), r"^vendor/.*$");
432 assert_eq!(glob_to_regex("a?.md"), r"^a[^/]\.md$");
433 assert_eq!(glob_to_regex("[abc].md"), r"^[abc]\.md$");
434 assert_eq!(glob_to_regex("{SPEC,ADR}-a.md"), r"^(?:SPEC|ADR)-a\.md$");
435 }
436
437 #[test]
438 fn several_includes_render_as_one_alternation() {
439 let rendered = render_patterns(&["a.md", "b/*.md"], "_docs").expect("two patterns render");
440 assert_eq!(rendered, r"^(?:a\.md|b/[^/]*\.md)$");
441 assert_eq!(render_patterns(&[], "_docs"), None);
442 }
443
444 #[test]
449 fn the_rendered_pattern_is_a_superset_of_the_matcher() {
450 use crate::domain::path_filter::{Layer, PathFilter, Pattern};
451
452 let corpus = [
453 "README.md",
454 "AGENTS.md",
455 "method/AGENTS.md",
456 "method/gates.md",
457 "CHANGELOG.md",
458 "_docs/specs/SPEC-release.md",
459 "_docs/decisions/ADR-a-choice.md",
460 "_docs/reference/known-issues/KI-a-case.md",
461 "_docs/reference/tracking.yaml",
462 "_docs/guides/release.md",
463 "comparison-docs/COMPARISON-tools.md",
464 ".spec-driven-docs/manifest.json",
465 "src/gates.rs",
466 "vendor/third/lib.rs",
467 ];
468
469 for gate in GATES {
470 let filter = PathFilter::build(
471 gate.include
472 .iter()
473 .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
474 .collect(),
475 gate.exclude
476 .iter()
477 .map(|g| Pattern::new(render_root(g, "_docs"), Layer::Registry))
478 .collect(),
479 )
480 .expect("every registry pattern compiles");
481
482 let files = render_patterns(gate.include, "_docs");
483 let excludes = render_patterns(gate.exclude, "_docs");
484
485 for path in corpus {
486 if !filter.judges(camino::Utf8Path::new(path)) {
487 continue;
488 }
489 if let Some(files) = &files {
490 let selector = regex::Regex::new(files).expect("the projection compiles");
491 assert!(
492 selector.is_match(path),
493 "{}: the matcher judges {path} and the rendered files: {files} does not select it",
494 gate.id
495 );
496 }
497 if let Some(excludes) = &excludes {
498 let selector = regex::Regex::new(excludes).expect("the projection compiles");
499 assert!(
500 !selector.is_match(path),
501 "{}: the matcher judges {path} and the rendered exclude: {excludes} drops it",
502 gate.id
503 );
504 }
505 }
506 }
507 }
508
509 #[test]
510 fn always_run_gates_do_not_take_filenames() {
511 let out = render_gates(&RenderOptions::default());
512 assert_eq!(
513 out.matches("always_run: true").count(),
514 out.matches("pass_filenames: false").count()
515 );
516 }
517
518 #[test]
519 fn an_apostrophe_in_a_name_would_be_doubled() {
520 assert_eq!(quoted("it's"), "'it''s'");
521 }
522
523 #[test]
524 fn the_block_splices_into_a_plain_config() {
525 let block = render_block(&RenderOptions::default());
526 let spliced = crate::domain::marker::splice("repos:\n", &block).unwrap();
527 let (base, found) = crate::domain::marker::split_block(&spliced).unwrap();
528 assert_eq!(base, "repos:\n");
529 assert_eq!(found.as_deref(), Some(block.as_str()));
530 }
531}