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    /// Every profile the release offers.
111    pub profiles: Vec<ProfileDeclaration>,
112    /// Byte projections the canon keeps owning.
113    #[serde(default)]
114    pub managed: Vec<Projection>,
115    /// Seeds the instance owns from the moment they land.
116    #[serde(default)]
117    pub adopted: Vec<Projection>,
118    /// One sentinel per feature a project can declare.
119    #[serde(default)]
120    pub sentinels: Vec<SentinelDeclaration>,
121}
122
123impl Declaration {
124    /// Read a declaration, refusing a schema this engine does not decode.
125    ///
126    /// # Errors
127    ///
128    /// [`DeclarationError`] when the bytes do not parse or when the
129    /// declaration contradicts itself.
130    pub fn parse(bytes: &[u8]) -> Result<Self, DeclarationError> {
131        let text = std::str::from_utf8(bytes)
132            .map_err(|source| DeclarationError::Malformed(source.to_string()))?;
133        let held: Self = toml::from_str(text)
134            .map_err(|source| DeclarationError::Malformed(source.to_string()))?;
135        held.consistent()?;
136        Ok(held)
137    }
138
139    /// Whether the declaration says one thing.
140    fn consistent(&self) -> Result<(), DeclarationError> {
141        if self.profiles.is_empty() {
142            return Err(DeclarationError::Inconsistent(
143                "no profile is declared".to_string(),
144            ));
145        }
146        for entry in self.managed.iter().chain(&self.adopted) {
147            if let Some(name) = &entry.yields_to
148                && YieldSet::parse(name).is_none()
149            {
150                return Err(DeclarationError::Inconsistent(format!(
151                    "{} yields to {name}, a set this engine does not know",
152                    entry.destination
153                )));
154            }
155        }
156        if let Some(entry) = self.managed.iter().find(|entry| entry.yields_to.is_some()) {
157            return Err(DeclarationError::Inconsistent(format!(
158                "the managed destination {} yields, and only an adopted seed may",
159                entry.destination
160            )));
161        }
162        let mut seen: Vec<&str> = Vec::new();
163        for entry in self.managed.iter().chain(&self.adopted) {
164            if seen.contains(&entry.destination.as_str()) {
165                return Err(DeclarationError::Inconsistent(format!(
166                    "{} is projected twice",
167                    entry.destination
168                )));
169            }
170            seen.push(&entry.destination);
171        }
172        Ok(())
173    }
174
175    /// What one profile lands, as this release declares it.
176    #[must_use]
177    pub fn profile(&self, id: ProfileId) -> Option<crate::domain::profile::Profile<'_>> {
178        Some(crate::domain::profile::Profile {
179            id,
180            docs_root: self.docs_root(id)?,
181            managed: &self.managed,
182            adopted: &self.adopted,
183        })
184    }
185
186    /// The documentation root one profile takes, where it is declared.
187    #[must_use]
188    pub fn docs_root(&self, id: ProfileId) -> Option<DocsRoot> {
189        self.profiles
190            .iter()
191            .find(|profile| profile.id == id)
192            .map(|profile| profile.docs_root)
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    #![allow(
199        clippy::unwrap_used,
200        reason = "a test panics as its failure signal, not as control flow"
201    )]
202
203    use super::*;
204
205    const MINIMAL: &str = r#"
206[[profiles]]
207id = "codebase"
208docs_root = "docs"
209"#;
210
211    #[test]
212    fn a_minimal_declaration_parses() {
213        let held = Declaration::parse(MINIMAL.as_bytes()).unwrap();
214        assert_eq!(held.docs_root(ProfileId::Codebase), Some(DocsRoot::Docs));
215        assert_eq!(held.docs_root(ProfileId::KnowledgeBase), None);
216    }
217
218    #[test]
219    fn a_declaration_with_no_profile_refuses() {
220        // Absent is a parse failure and empty is an inconsistency. Both
221        // refuse, because a release that offers no profile lands nothing.
222        assert!(matches!(
223            Declaration::parse(b"").unwrap_err(),
224            DeclarationError::Malformed(_)
225        ));
226        assert!(matches!(
227            Declaration::parse(b"profiles = []\n").unwrap_err(),
228            DeclarationError::Inconsistent(_)
229        ));
230    }
231
232    #[test]
233    fn a_templated_managed_destination_parses() {
234        let text =
235            format!("{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"{{docs_root}}/a\"\n");
236        let held = Declaration::parse(text.as_bytes()).unwrap();
237        assert_eq!(held.managed[0].destination, "{docs_root}/a");
238    }
239
240    #[test]
241    fn a_known_yield_set_resolves_to_its_names() {
242        let text = format!(
243            "{MINIMAL}\n[[adopted]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"markdownlint-configuration\"\n"
244        );
245        let held = Declaration::parse(text.as_bytes()).unwrap();
246        let set = held.adopted[0].yield_set().unwrap();
247        assert!(set.names().any(|name| name == ".markdownlint-cli2.jsonc"));
248        assert!(set.names().any(|name| name == ".markdownlint.yaml"));
249    }
250
251    #[test]
252    fn an_unknown_yield_set_is_inconsistent() {
253        let text = format!(
254            "{MINIMAL}\n[[adopted]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"everything\"\n"
255        );
256        let error = Declaration::parse(text.as_bytes()).unwrap_err();
257        assert!(
258            matches!(error, DeclarationError::Inconsistent(_)),
259            "{error}"
260        );
261        assert!(error.to_string().contains("everything"), "{error}");
262    }
263
264    #[test]
265    fn a_yielding_managed_file_is_inconsistent() {
266        let text = format!(
267            "{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"a\"\nyields_to = \"markdownlint-configuration\"\n"
268        );
269        let error = Declaration::parse(text.as_bytes()).unwrap_err();
270        assert!(
271            error.to_string().contains("only an adopted seed"),
272            "{error}"
273        );
274    }
275
276    #[test]
277    fn one_destination_projected_twice_is_inconsistent() {
278        let text = format!(
279            "{MINIMAL}\n[[managed]]\nsource = \"a\"\ndestination = \"x\"\n[[adopted]]\nsource = \"b\"\ndestination = \"x\"\n"
280        );
281        let error = Declaration::parse(text.as_bytes()).unwrap_err();
282        assert!(error.to_string().contains("projected twice"), "{error}");
283    }
284
285    #[test]
286    fn an_unknown_field_refuses_rather_than_being_ignored() {
287        let text = format!("{MINIMAL}\nsomething_new = 1\n");
288        assert!(matches!(
289            Declaration::parse(text.as_bytes()).unwrap_err(),
290            DeclarationError::Malformed(_)
291        ));
292    }
293}