Skip to main content

spec_driven_docs/domain/
instance_config.rs

1//! What a project declares about the files its gates judge.
2//!
3//! One hand-edited file, `.spec-driven-docs/config.yaml`, states which paths
4//! no delivered gate judges and which filters each named gate takes. The
5//! managed pre-commit block is rendered from it, so the block stays wholly
6//! owned by `sdd` and an upgrade never meets a project's edit.
7//!
8//! # The two keys are named apart
9//!
10//! `ESLint`'s flat config overloads one `ignores` key whose meaning changes
11//! with what else sits beside it, and it is a documented, repeated source of
12//! user confusion. `reserved` and `gates` mean one thing each.
13//!
14//! # The composition algorithm
15//!
16//! Four layers, in this order, and one function implements it:
17//!
18//! ```text
19//! layer 1  registry   the row's include and exclude in GATES
20//! layer 2  project    the gates: entry for that gate
21//! layer 3  flag       --include and --exclude on the command line
22//! layer 4  reserved   the reserved: list, as excludes only
23//! ```
24//!
25//! Per field, a later layer extends rather than replaces, with one stated
26//! exception: a project `include` list replaces the registry `include` list.
27//! A registry include is a whitelist, so extending it can only widen what a
28//! gate judges, which is the opposite of what a project asking for `include`
29//! wants. Every `exclude` layer extends, and `reserved` is last, so nothing
30//! reopens it. No layer can reopen an exclusion at all, because the grammar
31//! carries no negation: `crate::domain::path_filter` refuses a leading `!`.
32//!
33//! # The writing style is the project's to select
34//!
35//! `writing_style` states where the writing convention comes from: this
36//! convention's chapter, a document of the project's own, or none. The
37//! managed documentation block routes authors to the selection, and `none`
38//! installs no route and imposes no conversion obligation. The combination
39//! is validated, not just the field: `project` without a `path` names
40//! nothing, and a `path` beside another source is a value nothing reads,
41//! which is a value that drifts.
42
43use 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/// The filters one named gate takes.
54#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
55#[serde(deny_unknown_fields)]
56pub struct GateFilters {
57    /// Replaces the registry's include list for this gate.
58    #[serde(default)]
59    pub include: Vec<String>,
60    /// Extends the registry's exclude list for this gate.
61    #[serde(default)]
62    pub exclude: Vec<String>,
63}
64
65/// Where a project's writing style comes from.
66#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq)]
67#[serde(rename_all = "lowercase")]
68pub enum WritingSource {
69    /// This convention's chapter, served by `sdd method writing-style`.
70    #[default]
71    Builtin,
72    /// A document of the project's own, named by `path`.
73    Project,
74    /// No route and no conversion obligation.
75    None,
76}
77
78/// The writing-style selection as written.
79#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
80#[serde(deny_unknown_fields)]
81pub struct WritingStyle {
82    /// Which source.
83    #[serde(default)]
84    pub source: WritingSource,
85    /// The project's own document, relative to the repository root, where
86    /// the source is `project`.
87    #[serde(default)]
88    pub path: Option<String>,
89}
90
91impl WritingStyle {
92    /// Read the `--writing-style` argument: `builtin`, `none`, or
93    /// `project:<path>`.
94    ///
95    /// # Errors
96    ///
97    /// [`ConfigError::WritingStyle`] for any other form, or a path the
98    /// selection refuses.
99    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    /// Hold the combination, not just each field.
123    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    /// The document authors are routed to, relative to the repository, or
152    /// `None` where the selection installs no route.
153    #[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    /// The selection as the declaration file spells it.
163    #[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/// The declaration as written.
180#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq)]
181#[serde(deny_unknown_fields)]
182pub struct InstanceConfig {
183    /// Paths no delivered gate judges. Another tool owns these.
184    ///
185    /// The list covers the gates `sdd` delivers. The Markdown linter reads
186    /// its scope from the `ignores` of its own configuration, so a Markdown
187    /// path it must skip goes in the root `.markdownlint-cli2.jsonc`.
188    #[serde(default)]
189    pub reserved: Vec<String>,
190    /// Per-gate filters, keyed by gate id. A gate not named here takes its
191    /// registry default.
192    #[serde(default)]
193    pub gates: BTreeMap<String, GateFilters>,
194    /// Where the writing style comes from. Absent, the convention's own
195    /// chapter.
196    #[serde(default)]
197    pub writing_style: WritingStyle,
198}
199
200/// A declaration that does not parse, or that names something no gate has.
201#[derive(Debug, thiserror::Error)]
202pub enum ConfigError {
203    /// The file is not YAML of this shape.
204    #[error("{CONFIG_PATH} does not parse: {0}")]
205    Shape(String),
206    /// A `gates:` key is not a delivered gate id.
207    #[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    /// A pattern the filter grammar refuses.
212    #[error("{CONFIG_PATH}: {0}")]
213    Pattern(#[from] PathFilterError),
214    /// A writing-style selection whose fields do not agree.
215    #[error("{CONFIG_PATH}: writing_style: {0}")]
216    WritingStyle(String),
217}
218
219impl InstanceConfig {
220    /// Parse a declaration.
221    ///
222    /// # Errors
223    ///
224    /// [`ConfigError::Shape`] when the text is not a declaration, and
225    /// [`ConfigError::UnknownGate`] when a `gates:` key names no delivered
226    /// gate. Neither falls back to the default: a filter that quietly stops
227    /// applying is worse than one that fails loudly.
228    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        // Compile every pattern here, at the one boundary, rather than
237        // where a gate runs. A malformed pattern that reached `render_block`
238        // would be written into the managed block and blessed by `verify`,
239        // then fail separately from every gate that ran.
240        parsed.check_patterns()?;
241        parsed.writing_style.check()?;
242        Ok(parsed)
243    }
244
245    /// Read the declaration an instance carries.
246    ///
247    /// A missing file is the empty declaration and never an error: an
248    /// instance that declares nothing is a valid instance.
249    ///
250    /// # Errors
251    ///
252    /// See [`Self::parse`]. An unreadable file that exists is a shape error
253    /// rather than a silent default.
254    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    /// Compile every declared pattern, so a bad one fails once and here.
264    ///
265    /// # Errors
266    ///
267    /// [`ConfigError::Pattern`] naming the pattern the grammar refuses.
268    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    /// This gate's declared filters, if the project named it.
281    #[must_use]
282    pub fn for_gate(&self, id: GateId) -> Option<&GateFilters> {
283        self.gates.get(&id.to_string())
284    }
285}
286
287/// Map a `gates:` key onto a delivered gate.
288fn resolve_id(key: &str) -> Option<GateId> {
289    GateId::ALL.iter().copied().find(|id| id.to_string() == key)
290}
291
292/// Build one gate's filter from every layer.
293///
294/// `registry_include` and `registry_exclude` arrive already templated
295/// against the instance's documentation root, because the root is the
296/// caller's to resolve.
297///
298/// # Errors
299///
300/// [`ConfigError::Pattern`] naming the pattern the grammar refuses.
301pub 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    // A project include replaces the registry include; extending a
310    // whitelist could only widen what the gate judges.
311    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    // Every exclude layer extends, and `reserved` is last so nothing that
336    // follows can reopen it.
337    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
361/// One glob as a YAML scalar that reads back as itself.
362///
363/// A glob and YAML disagree about several leading characters: `*` opens an
364/// alias, `[` and `{` open a flow collection, and `#` opens a comment. The
365/// filter grammar accepts `**/generated.md`, so writing it bare would
366/// produce a file the next read refuses. Single quotes make every glob a
367/// scalar, with an apostrophe doubled.
368fn quoted(glob: &str) -> String {
369    format!("'{}'", glob.replace('\'', "''"))
370}
371
372/// Record a writing-style selection in a declaration, keeping every comment.
373///
374/// The `writing_style:` key and its indented children are replaced as a
375/// block; a declaration written before the key existed gets it appended.
376#[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/// Record reserved paths in a declaration, keeping every comment.
412///
413/// The file is hand-edited and its comments carry the whole explanation of
414/// the four layers, so this rewrites one key textually rather than
415/// round-tripping the YAML. A path already recorded is left alone, which is
416/// what makes a repeated `--reserve` idempotent.
417#[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            // Drop the previous list items, which the rewritten key carries.
444            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        // `*`, `[`, `{`, and `#` all open something in YAML, and the filter
624        // grammar accepts globs starting with the first three.
625        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        // Not where a gate runs, and not after the managed block carries it.
640        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        // A declaration written before the key existed gets it appended.
720        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        // The grammar carries no negation, so there is nothing to write that
729        // would undo an earlier exclude. This asserts the refusal rather
730        // than the absence.
731        let error = resolve(&[], &[], None, &[], &["!a.md".to_string()], &[])
732            .expect_err("a negation is refused");
733        assert!(matches!(error, ConfigError::Pattern(_)));
734    }
735}