Skip to main content

spec_driven_docs/domain/
projection.rs

1//! What this release lands, read as data rather than compiled in.
2//!
3//! The release declares its own projection in `instance/projection.toml`,
4//! which the binary carries. Selection stays in data because the
5//! declaration is simpler to read, to diff, and to review than the Rust
6//! constants it replaced.
7
8use serde::{Deserialize, Serialize};
9use thiserror::Error;
10
11use crate::domain::profile::{DocsRoot, ProfileId};
12
13/// Where the declaration sits inside the payload.
14pub const DECLARATION_PATH: &str = "instance/projection.toml";
15
16/// A declaration this engine cannot read.
17#[derive(Debug, Error, PartialEq, Eq)]
18pub enum DeclarationError {
19    /// The bytes are not the declaration's shape.
20    #[error("{DECLARATION_PATH} does not parse: {0}")]
21    Malformed(String),
22
23    /// The declaration is internally inconsistent.
24    #[error("{DECLARATION_PATH} is inconsistent: {0}")]
25    Inconsistent(String),
26}
27
28/// One payload projection: an embedded source and its instance destination.
29///
30/// A destination may carry a `{docs_root}` placeholder, resolved per
31/// profile by [`crate::domain::profile::resolve_destination`].
32#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
33#[serde(deny_unknown_fields)]
34pub struct Projection {
35    /// The payload path, as the bundle names it.
36    pub source: String,
37    /// The destination, relative to the instance root.
38    pub destination: String,
39    /// The named set of files whose presence at the target root makes an
40    /// adopted seed yield: the landing does not introduce it there.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub yields_to: Option<String>,
43}
44
45impl Projection {
46    /// The set this projection yields to, where it names one this engine
47    /// knows.
48    #[must_use]
49    pub fn yield_set(&self) -> Option<YieldSet> {
50        self.yields_to.as_deref().and_then(YieldSet::parse)
51    }
52}
53
54/// A named set of files that makes an adopted seed yield.
55///
56/// A set is named in the declaration and resolved here, so the declaration
57/// stays readable and the file names stay in the module that owns them.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum YieldSet {
60    /// Every markdownlint configuration name of both discovery families.
61    MarkdownlintConfiguration,
62}
63
64impl YieldSet {
65    /// The set a declaration names, where this engine knows it.
66    #[must_use]
67    pub fn parse(name: &str) -> Option<Self> {
68        match name {
69            "markdownlint-configuration" => Some(Self::MarkdownlintConfiguration),
70            _ => None,
71        }
72    }
73
74    /// The file names, relative to the target root, the set holds.
75    pub fn names(self) -> impl Iterator<Item = &'static str> {
76        match self {
77            Self::MarkdownlintConfiguration => crate::domain::markdownlint::discovery_names(),
78        }
79    }
80}
81
82/// One profile the release offers.
83#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
84#[serde(deny_unknown_fields)]
85pub struct ProfileDeclaration {
86    /// The profile's kebab-case name.
87    pub id: ProfileId,
88    /// Where that profile keeps the documents the gates read.
89    pub docs_root: DocsRoot,
90}
91
92/// One sentinel: the rule, and the adopted specification that owns it.
93#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
94#[serde(deny_unknown_fields)]
95pub struct SentinelDeclaration {
96    /// The rule an instance's specifications must define.
97    pub rule: String,
98    /// The payload specification that carries it.
99    pub source: String,
100    /// Where an instance holds that specification, templated.
101    pub destination: String,
102    /// The declaration it authorizes, for the note that names it.
103    pub declares: String,
104}
105
106/// Everything one release declares about what it lands.
107#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
108#[serde(deny_unknown_fields)]
109pub struct Declaration {
110    /// The template copies the canon keeps in its own documentation tree.
111    #[serde(default)]
112    pub canon_templates: Vec<String>,
113    /// Every profile the release offers.
114    pub profiles: Vec<ProfileDeclaration>,
115    /// Byte projections the canon keeps owning.
116    #[serde(default)]
117    pub managed: Vec<Projection>,
118    /// Seeds the instance owns from the moment they land.
119    #[serde(default)]
120    pub adopted: Vec<Projection>,
121    /// One sentinel per feature a project can declare.
122    #[serde(default)]
123    pub sentinels: Vec<SentinelDeclaration>,
124}
125
126impl Declaration {
127    /// Read a declaration, refusing a schema this engine does not decode.
128    ///
129    /// # Errors
130    ///
131    /// [`DeclarationError`] when the bytes do not parse or when the
132    /// declaration contradicts itself.
133    pub fn parse(bytes: &[u8]) -> Result<Self, DeclarationError> {
134        let text = std::str::from_utf8(bytes)
135            .map_err(|source| DeclarationError::Malformed(source.to_string()))?;
136        let held: Self = toml::from_str(text)
137            .map_err(|source| DeclarationError::Malformed(source.to_string()))?;
138        held.consistent()?;
139        Ok(held)
140    }
141
142    /// Whether the declaration says one thing.
143    fn consistent(&self) -> Result<(), DeclarationError> {
144        if self.profiles.is_empty() {
145            return Err(DeclarationError::Inconsistent(
146                "no profile is declared".to_string(),
147            ));
148        }
149        for entry in self.managed.iter().chain(&self.adopted) {
150            if let Some(name) = &entry.yields_to
151                && YieldSet::parse(name).is_none()
152            {
153                return Err(DeclarationError::Inconsistent(format!(
154                    "{} yields to {name}, a set this engine does not know",
155                    entry.destination
156                )));
157            }
158        }
159        if let Some(entry) = self.managed.iter().find(|entry| entry.yields_to.is_some()) {
160            return Err(DeclarationError::Inconsistent(format!(
161                "the managed destination {} yields, and only an adopted seed may",
162                entry.destination
163            )));
164        }
165        let mut seen: Vec<&str> = Vec::new();
166        for entry in self.managed.iter().chain(&self.adopted) {
167            if seen.contains(&entry.destination.as_str()) {
168                return Err(DeclarationError::Inconsistent(format!(
169                    "{} is projected twice",
170                    entry.destination
171                )));
172            }
173            seen.push(&entry.destination);
174        }
175        Ok(())
176    }
177
178    /// What one profile lands, as this release declares it.
179    #[must_use]
180    pub fn profile(&self, id: ProfileId) -> Option<crate::domain::profile::Profile<'_>> {
181        Some(crate::domain::profile::Profile {
182            id,
183            docs_root: self.docs_root(id)?,
184            managed: &self.managed,
185            adopted: &self.adopted,
186        })
187    }
188
189    /// The documentation root one profile takes, where it is declared.
190    #[must_use]
191    pub fn docs_root(&self, id: ProfileId) -> Option<DocsRoot> {
192        self.profiles
193            .iter()
194            .find(|profile| profile.id == id)
195            .map(|profile| profile.docs_root)
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    #![allow(
202        clippy::unwrap_used,
203        reason = "a test panics as its failure signal, not as control flow"
204    )]
205
206    use super::*;
207
208    const MINIMAL: &str = r#"
209[[profiles]]
210id = "codebase"
211docs_root = "docs"
212"#;
213
214    #[test]
215    fn a_minimal_declaration_parses() {
216        let held = Declaration::parse(MINIMAL.as_bytes()).unwrap();
217        assert_eq!(held.docs_root(ProfileId::Codebase), Some(DocsRoot::Docs));
218        assert_eq!(held.docs_root(ProfileId::KnowledgeBase), None);
219    }
220
221    #[test]
222    fn a_declaration_with_no_profile_refuses() {
223        // Absent is a parse failure and empty is an inconsistency. Both
224        // refuse, because a release that offers no profile lands nothing.
225        assert!(matches!(
226            Declaration::parse(b"").unwrap_err(),
227            DeclarationError::Malformed(_)
228        ));
229        assert!(matches!(
230            Declaration::parse(b"profiles = []\n").unwrap_err(),
231            DeclarationError::Inconsistent(_)
232        ));
233    }
234
235    #[test]
236    fn a_templated_managed_destination_parses() {
237        let text =
238            format!("{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"{{docs_root}}/a\"\n");
239        let held = Declaration::parse(text.as_bytes()).unwrap();
240        assert_eq!(held.managed[0].destination, "{docs_root}/a");
241    }
242
243    #[test]
244    fn a_known_yield_set_resolves_to_its_names() {
245        let text = format!(
246            "{MINIMAL}\n[[adopted]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"markdownlint-configuration\"\n"
247        );
248        let held = Declaration::parse(text.as_bytes()).unwrap();
249        let set = held.adopted[0].yield_set().unwrap();
250        assert!(set.names().any(|name| name == ".markdownlint-cli2.jsonc"));
251        assert!(set.names().any(|name| name == ".markdownlint.yaml"));
252    }
253
254    #[test]
255    fn an_unknown_yield_set_is_inconsistent() {
256        let text = format!(
257            "{MINIMAL}\n[[adopted]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"everything\"\n"
258        );
259        let error = Declaration::parse(text.as_bytes()).unwrap_err();
260        assert!(
261            matches!(error, DeclarationError::Inconsistent(_)),
262            "{error}"
263        );
264        assert!(error.to_string().contains("everything"), "{error}");
265    }
266
267    #[test]
268    fn a_yielding_managed_file_is_inconsistent() {
269        let text = format!(
270            "{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"markdownlint-configuration\"\n"
271        );
272        let error = Declaration::parse(text.as_bytes()).unwrap_err();
273        assert!(
274            error.to_string().contains("only an adopted seed"),
275            "{error}"
276        );
277    }
278
279    #[test]
280    fn one_destination_projected_twice_is_inconsistent() {
281        let text = format!(
282            "{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"x\"\n[[adopted]]\nsource = \"b\"\ndestination = \"x\"\n"
283        );
284        let error = Declaration::parse(text.as_bytes()).unwrap_err();
285        assert!(error.to_string().contains("projected twice"), "{error}");
286    }
287
288    #[test]
289    fn an_unknown_field_refuses_rather_than_being_ignored() {
290        let text = format!("{MINIMAL}\nsomething_new = 1\n");
291        assert!(matches!(
292            Declaration::parse(text.as_bytes()).unwrap_err(),
293            DeclarationError::Malformed(_)
294        ));
295    }
296}