spec_driven_docs/domain/
projection.rs1use serde::{Deserialize, Serialize};
9use thiserror::Error;
10
11use crate::domain::profile::{DocsRoot, ProfileId};
12
13pub const DECLARATION_PATH: &str = "instance/projection.toml";
15
16#[derive(Debug, Error, PartialEq, Eq)]
18pub enum DeclarationError {
19 #[error("{DECLARATION_PATH} does not parse: {0}")]
21 Malformed(String),
22
23 #[error("{DECLARATION_PATH} is inconsistent: {0}")]
25 Inconsistent(String),
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
33#[serde(deny_unknown_fields)]
34pub struct Projection {
35 pub source: String,
37 pub destination: String,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub yields_to: Option<String>,
43}
44
45impl Projection {
46 #[must_use]
49 pub fn yield_set(&self) -> Option<YieldSet> {
50 self.yields_to.as_deref().and_then(YieldSet::parse)
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum YieldSet {
60 MarkdownlintConfiguration,
62}
63
64impl YieldSet {
65 #[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 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
84#[serde(deny_unknown_fields)]
85pub struct ProfileDeclaration {
86 pub id: ProfileId,
88 pub docs_root: DocsRoot,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
94#[serde(deny_unknown_fields)]
95pub struct SentinelDeclaration {
96 pub rule: String,
98 pub source: String,
100 pub destination: String,
102 pub declares: String,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
108#[serde(deny_unknown_fields)]
109pub struct Declaration {
110 #[serde(default)]
112 pub canon_templates: Vec<String>,
113 pub profiles: Vec<ProfileDeclaration>,
115 #[serde(default)]
117 pub managed: Vec<Projection>,
118 #[serde(default)]
120 pub adopted: Vec<Projection>,
121 #[serde(default)]
123 pub sentinels: Vec<SentinelDeclaration>,
124}
125
126impl Declaration {
127 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 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 #[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 #[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 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}