1use std::{
2 error::Error,
3 fmt, fs,
4 path::{Path, PathBuf},
5};
6
7use norm_spec_core::SchemaBundle;
8use serde_json::Value;
9
10const EMBEDDED_ROOT: &str = include_str!(concat!(
11 env!("CARGO_MANIFEST_DIR"),
12 "/schema/norm-schema.json"
13));
14const EMBEDDED_PROFILES: [(&str, &str); 7] = [
15 (
16 "architecture",
17 include_str!(concat!(
18 env!("CARGO_MANIFEST_DIR"),
19 "/schema/profiles/architecture.json"
20 )),
21 ),
22 (
23 "convention",
24 include_str!(concat!(
25 env!("CARGO_MANIFEST_DIR"),
26 "/schema/profiles/convention.json"
27 )),
28 ),
29 (
30 "epic",
31 include_str!(concat!(
32 env!("CARGO_MANIFEST_DIR"),
33 "/schema/profiles/epic.json"
34 )),
35 ),
36 (
37 "module",
38 include_str!(concat!(
39 env!("CARGO_MANIFEST_DIR"),
40 "/schema/profiles/module.json"
41 )),
42 ),
43 (
44 "root",
45 include_str!(concat!(
46 env!("CARGO_MANIFEST_DIR"),
47 "/schema/profiles/root.json"
48 )),
49 ),
50 (
51 "task",
52 include_str!(concat!(
53 env!("CARGO_MANIFEST_DIR"),
54 "/schema/profiles/task.json"
55 )),
56 ),
57 (
58 "test",
59 include_str!(concat!(
60 env!("CARGO_MANIFEST_DIR"),
61 "/schema/profiles/test.json"
62 )),
63 ),
64];
65const EMBEDDED_TEMPLATES: [(&str, &str); 7] = [
66 (
67 "architecture",
68 include_str!(concat!(
69 env!("CARGO_MANIFEST_DIR"),
70 "/templates/profiles/architecture.norm"
71 )),
72 ),
73 (
74 "convention",
75 include_str!(concat!(
76 env!("CARGO_MANIFEST_DIR"),
77 "/templates/profiles/convention.norm"
78 )),
79 ),
80 (
81 "epic",
82 include_str!(concat!(
83 env!("CARGO_MANIFEST_DIR"),
84 "/templates/profiles/epic.norm"
85 )),
86 ),
87 (
88 "module",
89 include_str!(concat!(
90 env!("CARGO_MANIFEST_DIR"),
91 "/templates/profiles/module.norm"
92 )),
93 ),
94 (
95 "root",
96 include_str!(concat!(
97 env!("CARGO_MANIFEST_DIR"),
98 "/templates/profiles/root.norm"
99 )),
100 ),
101 (
102 "task",
103 include_str!(concat!(
104 env!("CARGO_MANIFEST_DIR"),
105 "/templates/profiles/task.norm"
106 )),
107 ),
108 (
109 "test",
110 include_str!(concat!(
111 env!("CARGO_MANIFEST_DIR"),
112 "/templates/profiles/test.norm"
113 )),
114 ),
115];
116
117pub const PROFILE_NAMES: [&str; 7] = [
119 "architecture",
120 "convention",
121 "epic",
122 "module",
123 "root",
124 "task",
125 "test",
126];
127
128#[must_use]
130pub fn profile_template(profile: &str) -> Option<&'static str> {
131 EMBEDDED_TEMPLATES
132 .iter()
133 .find_map(|(name, contents)| (*name == profile).then_some(*contents))
134}
135
136#[derive(Debug)]
138pub struct SchemaLoadError {
139 path: Option<PathBuf>,
140 detail: String,
141}
142
143impl SchemaLoadError {
144 fn new(path: Option<PathBuf>, detail: impl Into<String>) -> Self {
145 Self {
146 path,
147 detail: detail.into(),
148 }
149 }
150
151 #[must_use]
153 pub fn path(&self) -> Option<&Path> {
154 self.path.as_deref()
155 }
156}
157
158impl fmt::Display for SchemaLoadError {
159 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
160 formatter.write_str(&self.detail)
161 }
162}
163
164impl Error for SchemaLoadError {}
165
166pub fn embedded_schema_bundle() -> Result<SchemaBundle, SchemaLoadError> {
172 let root = parse_schema(None, EMBEDDED_ROOT)?;
173 let profiles = EMBEDDED_PROFILES
174 .into_iter()
175 .map(|(name, contents)| {
176 parse_schema(None, contents).map(|schema| (name.to_owned(), schema))
177 })
178 .collect::<Result<Vec<_>, _>>()?;
179 Ok(SchemaBundle::new(root, profiles))
180}
181
182pub fn schema_bundle_from_dir(directory: &Path) -> Result<SchemaBundle, SchemaLoadError> {
189 if !directory.is_dir() {
190 return Err(SchemaLoadError::new(
191 Some(directory.to_path_buf()),
192 "The explicit schema path is not an available directory.",
193 ));
194 }
195 let root_path = directory.join("norm-schema.json");
196 let root = read_schema(&root_path)?;
197 let profiles_path = directory.join("profiles");
198 let mut profile_paths = fs::read_dir(&profiles_path)
199 .map_err(|error| {
200 SchemaLoadError::new(
201 Some(profiles_path.clone()),
202 format!("The profile schema directory is unavailable: {error}"),
203 )
204 })?
205 .map(|entry| {
206 entry.map(|entry| entry.path()).map_err(|error| {
207 SchemaLoadError::new(
208 Some(profiles_path.clone()),
209 format!("A profile schema entry is unavailable: {error}"),
210 )
211 })
212 })
213 .collect::<Result<Vec<_>, _>>()?;
214 profile_paths.retain(|path| {
215 path.extension()
216 .is_some_and(|extension| extension == "json")
217 });
218 profile_paths.sort();
219 let profiles = profile_paths
220 .into_iter()
221 .map(|path| {
222 let name = path
223 .file_stem()
224 .and_then(|stem| stem.to_str())
225 .ok_or_else(|| {
226 SchemaLoadError::new(
227 Some(path.clone()),
228 "A profile schema filename is not valid UTF-8.",
229 )
230 })?
231 .to_owned();
232 read_schema(&path).map(|schema| (name, schema))
233 })
234 .collect::<Result<Vec<_>, _>>()?;
235 Ok(SchemaBundle::new(root, profiles))
236}
237
238fn read_schema(path: &Path) -> Result<Value, SchemaLoadError> {
239 let contents = fs::read_to_string(path).map_err(|error| {
240 SchemaLoadError::new(
241 Some(path.to_path_buf()),
242 format!("The schema file is unavailable: {error}"),
243 )
244 })?;
245 parse_schema(Some(path), &contents)
246}
247
248fn parse_schema(path: Option<&Path>, contents: &str) -> Result<Value, SchemaLoadError> {
249 serde_json::from_str(contents).map_err(|error| {
250 SchemaLoadError::new(
251 path.map(Path::to_path_buf),
252 format!("The schema file is not valid JSON: {error}"),
253 )
254 })
255}
256
257#[cfg(test)]
258mod tests {
259 use norm_spec_core::{
260 ParseOptions, ReferenceResolver, ReferenceStatus, ValidationOptions, parse_norm,
261 validate_frontmatter,
262 };
263
264 use super::{EMBEDDED_TEMPLATES, embedded_schema_bundle};
265
266 struct ExistingReferences;
267
268 impl ReferenceResolver for ExistingReferences {
269 fn resolve(&self, _target: &str) -> ReferenceStatus {
270 ReferenceStatus::Exists
271 }
272 }
273
274 #[test]
275 fn every_packaged_profile_template_is_valid() {
276 let schemas = embedded_schema_bundle()
277 .unwrap_or_else(|error| panic!("packaged schemas should load: {error}"));
278 for (name, contents) in EMBEDDED_TEMPLATES {
279 let parsed = parse_norm(contents, ParseOptions::default())
280 .unwrap_or_else(|error| panic!("packaged {name} template should parse: {error}"));
281 assert_eq!(parsed.frontmatter["metadata"]["layer"].as_str(), Some(name));
282 let diagnostics = validate_frontmatter(
283 &parsed.frontmatter,
284 &schemas,
285 ValidationOptions {
286 compat_keys: false,
287 profile: Some(name),
288 },
289 &ExistingReferences,
290 )
291 .unwrap_or_else(|error| {
292 panic!("packaged {name} template schema should compile: {error}")
293 });
294 assert!(
295 diagnostics.errors.is_empty(),
296 "packaged {name} template has errors: {:?}",
297 diagnostics.errors
298 );
299 assert!(
300 diagnostics.warnings.is_empty(),
301 "packaged {name} template has warnings: {:?}",
302 diagnostics.warnings
303 );
304 }
305 }
306}