1use std::collections::BTreeMap;
44
45use camino::Utf8Path;
46use serde::Deserialize;
47
48use crate::domain::gate_id::GateId;
49use crate::domain::path_filter::{Layer, PathFilter, PathFilterError, Pattern};
50
51pub use crate::domain::paths::CONFIG_PATH;
52
53#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
55#[serde(deny_unknown_fields)]
56pub struct GateFilters {
57 #[serde(default)]
59 pub include: Vec<String>,
60 #[serde(default)]
62 pub exclude: Vec<String>,
63}
64
65#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq)]
67#[serde(rename_all = "lowercase")]
68pub enum WritingSource {
69 #[default]
71 Builtin,
72 Project,
74 None,
76}
77
78#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
80#[serde(deny_unknown_fields)]
81pub struct WritingStyle {
82 #[serde(default)]
84 pub source: WritingSource,
85 #[serde(default)]
88 pub path: Option<String>,
89}
90
91impl WritingStyle {
92 pub fn parse_flag(value: &str) -> Result<Self, ConfigError> {
100 let selection = match value.trim() {
101 "builtin" => Self::default(),
102 "none" => Self {
103 source: WritingSource::None,
104 path: None,
105 },
106 other => match other.strip_prefix("project:") {
107 Some(path) => Self {
108 source: WritingSource::Project,
109 path: Some(path.trim().to_string()),
110 },
111 None => {
112 return Err(ConfigError::WritingStyle(format!(
113 "`{other}` is not a selection; write `builtin`, `none`, or `project:<path>`"
114 )));
115 }
116 },
117 };
118 selection.check()?;
119 Ok(selection)
120 }
121
122 fn check(&self) -> Result<(), ConfigError> {
124 match (self.source, self.path.as_deref()) {
125 (WritingSource::Project, None | Some("")) => Err(ConfigError::WritingStyle(
126 "`source: project` names no `path`".to_string(),
127 )),
128 (WritingSource::Builtin | WritingSource::None, Some(path)) if !path.is_empty() => {
129 Err(ConfigError::WritingStyle(format!(
130 "`path: {path}` is set and the source is not `project`, so nothing reads it"
131 )))
132 }
133 (WritingSource::Project, Some(path)) => {
134 let candidate = Utf8Path::new(path);
135 if candidate.is_absolute() {
136 return Err(ConfigError::WritingStyle(format!(
137 "`path: {path}` is absolute; name the document relative to the repository"
138 )));
139 }
140 if candidate.components().any(|part| part.as_str() == "..") {
141 return Err(ConfigError::WritingStyle(format!(
142 "`path: {path}` leaves the repository"
143 )));
144 }
145 Ok(())
146 }
147 _ => Ok(()),
148 }
149 }
150
151 #[must_use]
154 pub fn route(&self) -> Option<String> {
155 match self.source {
156 WritingSource::Builtin => Some("`sdd method writing-style`".to_string()),
157 WritingSource::Project => self.path.as_ref().map(|path| format!("`{path}`")),
158 WritingSource::None => None,
159 }
160 }
161
162 #[must_use]
164 pub fn render(&self) -> String {
165 let source = match self.source {
166 WritingSource::Builtin => "builtin",
167 WritingSource::Project => "project",
168 WritingSource::None => "none",
169 };
170 let path = self
171 .path
172 .as_deref()
173 .filter(|path| !path.is_empty())
174 .map_or_else(|| "null".to_string(), quoted);
175 format!("writing_style:\n source: {source}\n path: {path}\n")
176 }
177}
178
179#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
181#[serde(deny_unknown_fields)]
182pub struct InstanceConfig {
183 #[serde(default)]
189 pub reserved: Vec<String>,
190 #[serde(default)]
193 pub gates: BTreeMap<String, GateFilters>,
194 #[serde(default)]
197 pub writing_style: WritingStyle,
198}
199
200#[derive(Debug, thiserror::Error)]
202pub enum ConfigError {
203 #[error("{CONFIG_PATH} does not parse: {0}")]
205 Shape(String),
206 #[error(
208 "{CONFIG_PATH} names the gate `{0}`, which this version does not deliver: `sdd gate --list` names every one"
209 )]
210 UnknownGate(String),
211 #[error("{CONFIG_PATH}: {0}")]
213 Pattern(#[from] PathFilterError),
214 #[error("{CONFIG_PATH}: writing_style: {0}")]
216 WritingStyle(String),
217}
218
219impl InstanceConfig {
220 pub fn parse(text: &str) -> Result<Self, ConfigError> {
229 let parsed: Self =
230 yaml_serde::from_str(text).map_err(|error| ConfigError::Shape(error.to_string()))?;
231 for key in parsed.gates.keys() {
232 if resolve_id(key).is_none() {
233 return Err(ConfigError::UnknownGate(key.clone()));
234 }
235 }
236 parsed.check_patterns()?;
241 parsed.writing_style.check()?;
242 Ok(parsed)
243 }
244
245 pub fn read(repo_root: &Utf8Path) -> Result<Self, ConfigError> {
255 let path = repo_root.join(CONFIG_PATH);
256 match std::fs::read_to_string(&path) {
257 Ok(text) => Self::parse(&text),
258 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
259 Err(error) => Err(ConfigError::Shape(error.to_string())),
260 }
261 }
262
263 fn check_patterns(&self) -> Result<(), ConfigError> {
269 let every = self.reserved.iter().chain(
270 self.gates
271 .values()
272 .flat_map(|filters| filters.include.iter().chain(&filters.exclude)),
273 );
274 for glob in every {
275 PathFilter::build(Vec::new(), vec![Pattern::new(glob.clone(), Layer::Project)])?;
276 }
277 Ok(())
278 }
279
280 #[must_use]
282 pub fn for_gate(&self, id: GateId) -> Option<&GateFilters> {
283 self.gates.get(&id.to_string())
284 }
285}
286
287fn resolve_id(key: &str) -> Option<GateId> {
289 GateId::ALL.iter().copied().find(|id| id.to_string() == key)
290}
291
292pub fn resolve(
302 registry_include: &[String],
303 registry_exclude: &[String],
304 declared: Option<&GateFilters>,
305 flag_include: &[String],
306 flag_exclude: &[String],
307 reserved: &[String],
308) -> Result<PathFilter, ConfigError> {
309 let includes: Vec<Pattern> = declared.filter(|d| !d.include.is_empty()).map_or_else(
312 || {
313 registry_include
314 .iter()
315 .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
316 .collect()
317 },
318 |declared| {
319 declared
320 .include
321 .iter()
322 .map(|glob| Pattern::new(glob.clone(), Layer::Project))
323 .collect()
324 },
325 );
326 let includes = includes
327 .into_iter()
328 .chain(
329 flag_include
330 .iter()
331 .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
332 )
333 .collect();
334
335 let excludes: Vec<Pattern> = registry_exclude
338 .iter()
339 .map(|glob| Pattern::new(glob.clone(), Layer::Registry))
340 .chain(
341 declared
342 .into_iter()
343 .flat_map(|d| &d.exclude)
344 .map(|glob| Pattern::new(glob.clone(), Layer::Project)),
345 )
346 .chain(
347 flag_exclude
348 .iter()
349 .map(|glob| Pattern::new(glob.clone(), Layer::Flag)),
350 )
351 .chain(
352 reserved
353 .iter()
354 .map(|glob| Pattern::new(glob.clone(), Layer::Reserved)),
355 )
356 .collect();
357
358 Ok(PathFilter::build(includes, excludes)?)
359}
360
361fn quoted(glob: &str) -> String {
369 format!("'{}'", glob.replace('\'', "''"))
370}
371
372#[must_use]
377pub fn with_writing_style(text: &str, selection: &WritingStyle) -> String {
378 let block = selection.render();
379 let mut out = String::new();
380 let mut wrote = false;
381 let mut skipping = false;
382 for line in text.lines() {
383 if skipping {
384 if line.starts_with(' ') || line.starts_with('\t') {
385 continue;
386 }
387 skipping = false;
388 }
389 if !wrote && line.starts_with("writing_style:") {
390 out.push_str(&block);
391 wrote = true;
392 skipping = true;
393 continue;
394 }
395 out.push_str(line);
396 out.push('\n');
397 }
398 if !wrote {
399 if !out.is_empty() && !out.ends_with("\n\n") {
400 out.push('\n');
401 }
402 out.push_str("# Where the writing style comes from: `builtin` routes authors to\n");
403 out.push_str("# `sdd method writing-style`, `project` routes them to the document\n");
404 out.push_str("# `path` names, and `none` installs no route and imposes no conversion\n");
405 out.push_str("# obligation.\n");
406 out.push_str(&block);
407 }
408 out
409}
410
411#[must_use]
418pub fn with_reserved(text: &str, paths: &[String]) -> String {
419 if paths.is_empty() {
420 return text.to_string();
421 }
422 let existing = InstanceConfig::parse(text).unwrap_or_default().reserved;
423 let mut added: Vec<&String> = paths
424 .iter()
425 .filter(|path| !existing.contains(path))
426 .collect();
427 added.dedup();
428 if added.is_empty() {
429 return text.to_string();
430 }
431
432 let entries: String = existing
433 .iter()
434 .map(|path| format!(" - {}\n", quoted(path)))
435 .chain(added.iter().map(|path| format!(" - {}\n", quoted(path))))
436 .collect();
437
438 let mut out = String::new();
439 let mut wrote = false;
440 let mut skipping = false;
441 for line in text.lines() {
442 if skipping {
443 if line.starts_with(" - ") || line.trim().is_empty() && !wrote {
445 continue;
446 }
447 skipping = false;
448 }
449 if !wrote && (line.starts_with("reserved:")) {
450 out.push_str("reserved:\n");
451 out.push_str(&entries);
452 wrote = true;
453 skipping = true;
454 continue;
455 }
456 out.push_str(line);
457 out.push('\n');
458 }
459 if !wrote {
460 out.push_str("reserved:\n");
461 out.push_str(&entries);
462 }
463 out
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469 use crate::domain::path_filter::Decision;
470
471 fn config(text: &str) -> InstanceConfig {
472 InstanceConfig::parse(text).expect("the fixture parses")
473 }
474
475 #[test]
476 fn an_absent_file_is_the_empty_declaration() {
477 let dir = tempfile::tempdir().expect("a scratch directory");
478 let root = camino::Utf8PathBuf::from_path_buf(dir.path().to_path_buf())
479 .expect("the scratch path is UTF-8");
480 let read = InstanceConfig::read(&root).expect("an absent file is not an error");
481 assert_eq!(read, InstanceConfig::default());
482 }
483
484 #[test]
485 fn an_empty_file_is_the_empty_declaration() {
486 assert_eq!(config("{}\n"), InstanceConfig::default());
487 }
488
489 #[test]
490 fn a_malformed_key_is_an_error_naming_the_key() {
491 let error = InstanceConfig::parse("reserved: AGENTS.md\n")
492 .expect_err("a scalar where a list belongs is refused");
493 assert!(
494 error.to_string().contains("reserved"),
495 "the error does not name the key: {error}"
496 );
497 }
498
499 #[test]
500 fn an_unknown_key_is_refused() {
501 assert!(InstanceConfig::parse("reservd:\n - a.md\n").is_err());
502 }
503
504 #[test]
505 fn an_unknown_gate_id_is_an_error_naming_the_key() {
506 let error = InstanceConfig::parse("gates:\n no-such-gate:\n exclude: [a]\n")
507 .expect_err("an unknown gate is refused");
508 assert!(matches!(error, ConfigError::UnknownGate(ref key) if key == "no-such-gate"));
509 }
510
511 #[test]
512 fn a_known_gate_id_parses() {
513 let parsed = config("gates:\n no-personal-path:\n exclude:\n - vendor/**\n");
514 assert_eq!(
515 parsed
516 .for_gate(GateId::NoPersonalPath)
517 .map(|f| f.exclude.clone()),
518 Some(vec!["vendor/**".to_string()])
519 );
520 }
521
522 #[test]
523 fn a_path_leaving_the_repository_is_refused() {
524 let error = resolve(&[], &[], None, &[], &[], &["../outside/**".to_string()])
525 .expect_err("a pattern that climbs out is refused");
526 assert!(matches!(error, ConfigError::Pattern(_)));
527 }
528
529 #[test]
530 fn a_project_include_replaces_the_registry_include() {
531 let filter = resolve(
532 &["_docs/**/*.md".to_string()],
533 &[],
534 Some(&GateFilters {
535 include: vec!["method/**/*.md".to_string()],
536 exclude: Vec::new(),
537 }),
538 &[],
539 &[],
540 &[],
541 )
542 .expect("resolves");
543 assert_eq!(
544 filter.decide(Utf8Path::new("method/gates.md")),
545 Decision::Read
546 );
547 assert_eq!(
548 filter.decide(Utf8Path::new("_docs/specs/SPEC-a.md")),
549 Decision::NotIncluded,
550 "the registry include survived a project include that replaces it"
551 );
552 }
553
554 #[test]
555 fn every_exclude_layer_extends() {
556 let filter = resolve(
557 &[],
558 &["a.md".to_string()],
559 Some(&GateFilters {
560 include: Vec::new(),
561 exclude: vec!["b.md".to_string()],
562 }),
563 &[],
564 &["c.md".to_string()],
565 &["d.md".to_string()],
566 )
567 .expect("resolves");
568 for path in ["a.md", "b.md", "c.md", "d.md"] {
569 assert!(
570 matches!(filter.decide(Utf8Path::new(path)), Decision::Skipped(_)),
571 "{path} survived its exclude layer"
572 );
573 }
574 }
575
576 #[test]
577 fn reserved_wins_over_a_gate_entry_that_includes_it() {
578 let filter = resolve(
579 &[],
580 &[],
581 Some(&GateFilters {
582 include: vec!["AGENTS.md".to_string()],
583 exclude: Vec::new(),
584 }),
585 &[],
586 &[],
587 &["AGENTS.md".to_string()],
588 )
589 .expect("resolves");
590 match filter.decide(Utf8Path::new("AGENTS.md")) {
591 Decision::Skipped(pattern) => assert_eq!(pattern.layer, Layer::Reserved),
592 other => panic!("reserved did not win: {other:?}"),
593 }
594 }
595
596 #[test]
597 fn reserving_a_path_keeps_every_comment() {
598 let seed = "# why this file exists\nreserved: []\n\n# per gate\ngates: {}\n";
599 let out = with_reserved(seed, &["AGENTS.md".to_string()]);
600 assert!(
601 out.contains("# why this file exists"),
602 "a comment was lost:\n{out}"
603 );
604 assert!(out.contains("# per gate"), "a comment was lost:\n{out}");
605 assert!(
606 out.contains(" - 'AGENTS.md'"),
607 "the path is missing:\n{out}"
608 );
609 assert_eq!(
610 InstanceConfig::parse(&out).expect("still parses").reserved,
611 vec!["AGENTS.md".to_string()]
612 );
613 }
614
615 #[test]
616 fn reserving_a_recorded_path_changes_nothing() {
617 let text = "reserved:\n - 'AGENTS.md'\ngates: {}\n";
618 assert_eq!(with_reserved(text, &["AGENTS.md".to_string()]), text);
619 }
620
621 #[test]
622 fn a_glob_is_written_as_a_yaml_scalar_that_reads_back() {
623 for glob in ["**/generated.md", "[ab]/x.md", "{a,b}/x.md", "it's/x.md"] {
626 let out = with_reserved("reserved: []\ngates: {}\n", &[glob.to_string()]);
627 assert_eq!(
628 InstanceConfig::parse(&out)
629 .unwrap_or_else(|e| panic!("{glob} did not read back: {e}"))
630 .reserved,
631 vec![glob.to_string()],
632 "for {glob}"
633 );
634 }
635 }
636
637 #[test]
638 fn a_refused_pattern_fails_at_the_declaration_boundary() {
639 let error = InstanceConfig::parse("reserved:\n - '!negated'\ngates: {}\n")
641 .expect_err("a negation is refused at parse");
642 assert!(matches!(error, ConfigError::Pattern(_)));
643 assert!(
644 InstanceConfig::parse("gates:\n no-personal-path:\n exclude: ['a[']\n").is_err()
645 );
646 }
647
648 #[test]
649 fn reserving_adds_beside_what_is_recorded() {
650 let text = "reserved:\n - AGENTS.md\ngates: {}\n";
651 let out = with_reserved(text, &["vendor/**".to_string()]);
652 assert_eq!(
653 InstanceConfig::parse(&out).expect("parses").reserved,
654 vec!["AGENTS.md".to_string(), "vendor/**".to_string()]
655 );
656 }
657
658 #[test]
659 fn an_absent_key_is_builtin() {
660 assert_eq!(
661 config("reserved: []\ngates: {}\n").writing_style,
662 WritingStyle::default()
663 );
664 assert_eq!(
665 config("writing_style:\n source: builtin\n path: null\n")
666 .writing_style
667 .route(),
668 Some("`sdd method writing-style`".to_string())
669 );
670 }
671
672 #[test]
673 fn project_without_a_path_is_an_error_naming_the_key() {
674 let error = InstanceConfig::parse("writing_style:\n source: project\n")
675 .expect_err("a project source needs a path");
676 assert!(matches!(error, ConfigError::WritingStyle(_)));
677 assert!(error.to_string().contains("writing_style"), "{error}");
678 assert!(error.to_string().contains("path"), "{error}");
679 }
680
681 #[test]
682 fn a_path_without_the_project_source_is_an_error() {
683 for source in ["builtin", "none"] {
684 let error = InstanceConfig::parse(&format!(
685 "writing_style:\n source: {source}\n path: docs/style.md\n"
686 ))
687 .expect_err("a path nothing reads is refused");
688 assert!(error.to_string().contains("nothing reads it"), "{error}");
689 }
690 }
691
692 #[test]
693 fn a_writing_style_path_leaving_the_repository_is_refused() {
694 for path in ["/etc/style.md", "../style.md", "docs/../../style.md"] {
695 assert!(
696 WritingStyle::parse_flag(&format!("project:{path}")).is_err(),
697 "{path} was accepted"
698 );
699 }
700 assert_eq!(
701 WritingStyle::parse_flag("project:docs/STYLE.md")
702 .unwrap()
703 .route(),
704 Some("`docs/STYLE.md`".to_string())
705 );
706 assert_eq!(WritingStyle::parse_flag("none").unwrap().route(), None);
707 assert!(WritingStyle::parse_flag("house").is_err());
708 }
709
710 #[test]
711 fn a_selection_is_written_into_the_declaration_and_reads_back() {
712 let seed = "reserved: []\n\n# how to write\nwriting_style:\n source: builtin\n path: null\n\ngates: {}\n";
713 let selection = WritingStyle::parse_flag("project:docs/STYLE.md").unwrap();
714 let out = with_writing_style(seed, &selection);
715 assert!(out.contains("# how to write"), "a comment was lost:\n{out}");
716 assert!(out.contains("gates: {}"), "a later key was lost:\n{out}");
717 assert_eq!(config(&out).writing_style, selection);
718
719 let older = "reserved: []\ngates: {}\n";
721 let out = with_writing_style(older, &WritingStyle::parse_flag("none").unwrap());
722 assert_eq!(config(&out).writing_style.source, WritingSource::None);
723 assert!(config(&out).reserved.is_empty());
724 }
725
726 #[test]
727 fn no_layer_can_reopen_an_exclusion() {
728 let error = resolve(&[], &[], None, &[], &["!a.md".to_string()], &[])
732 .expect_err("a negation is refused");
733 assert!(matches!(error, ConfigError::Pattern(_)));
734 }
735}