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 pub profiles: Vec<ProfileDeclaration>,
112 #[serde(default)]
114 pub managed: Vec<Projection>,
115 #[serde(default)]
117 pub adopted: Vec<Projection>,
118 #[serde(default)]
120 pub sentinels: Vec<SentinelDeclaration>,
121}
122
123impl Declaration {
124 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 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 #[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 #[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 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}