1use super::formats_d::{
8 check_clashes, folder_files, refuse_findings, settled_types, unsettled, without_alike,
9};
10use crate::{
11 Error, RepoPath, RepoRoot, Result, Spanned,
12 grammar::{FormatRegistry, FormatSource, Grammar, RegexCache},
13 source::{Fnv, read_optional},
14 yaml,
15};
16
17pub const FORMATS_DIR: &str = ".sokf/formats.d";
20
21pub fn formats_path() -> RepoPath {
23 RepoPath::parse("/.sokf/formats.yaml").expect("literal")
24}
25
26#[derive(Debug, Clone, Default)]
29pub struct RepoFormats {
30 pub repo: Option<FormatRegistry>,
32 pub folder: Option<FormatRegistry>,
37 merged: Option<FormatRegistry>,
41 pub hash: u64,
44}
45
46impl RepoFormats {
47 pub fn effective(&self, embedded: &FormatRegistry) -> FormatRegistry {
50 self.merged.clone().unwrap_or_else(|| embedded.clone())
51 }
52
53 pub fn folder_layer(&self) -> Option<FormatRegistry> {
56 let layer = self.folder.as_ref()?;
57 Some(only(layer, |s| matches!(s, FormatSource::File(_))))
58 }
59}
60
61fn only(layer: &FormatRegistry, keep: impl Fn(&FormatSource) -> bool) -> FormatRegistry {
64 let mut out = layer.clone();
65 out.entries.retain(|_, (_, s)| keep(s));
66 out.types.entries.retain(|_, (_, s)| keep(s));
67 out
68}
69
70pub fn load_repo_formats(
90 root: &RepoRoot,
91 grammar: &Grammar,
92 regexes: &RegexCache,
93) -> Result<RepoFormats> {
94 let embedded = crate::grammar::embedded_formats(grammar, regexes)?;
95 load_repo_formats_on(root, embedded, grammar, regexes)
96}
97
98fn load_repo_formats_on(
106 root: &RepoRoot,
107 embedded: FormatRegistry,
108 grammar: &Grammar,
109 regexes: &RegexCache,
110) -> Result<RepoFormats> {
111 let mut hash = Fnv::new();
112 let mut docs = Vec::new();
113 for path in super::d_folder::d_files(root, FORMATS_DIR, "yaml", false)? {
114 let Some(text) = read_optional(&path.to_fs(root))? else {
115 continue;
116 };
117 hash.update(path.as_str().as_bytes());
118 hash.update(text.as_bytes());
119 let doc = parse_doc(&path, &text)?;
120 docs.push((path, doc));
121 }
122 let repo_path = formats_path();
123 let repo_text = read_optional(&repo_path.to_fs(root))?;
124 if let Some(text) = &repo_text {
125 hash.update(text.as_bytes());
126 }
127 let repo_doc = match &repo_text {
128 Some(text) => Some(parse_doc(&repo_path, text)?),
129 None => None,
130 };
131 without_alike(&mut docs, &embedded);
134 check_clashes(&docs, repo_doc.as_ref())?;
137 let (base, broken) = match settled_types(
138 &mut docs,
139 repo_doc.as_ref().map(|d| (&repo_path, d)),
140 &embedded,
141 grammar,
142 regexes,
143 )? {
144 Some((base, broken)) => (base, broken),
145 None => (embedded, Vec::new()),
146 };
147 let files = folder_files(&docs, &base, grammar, regexes)?;
148 let layer = base.with_packs(&files);
152 let repo = match &repo_doc {
153 Some(doc) => {
154 let registry = doc.get("registry").ok_or_else(|| {
155 Error::formats(repo_path.clone(), "The file has no `registry` map.")
156 })?;
157 Some(layer_of(
158 &repo_path,
159 doc,
160 registry,
161 FormatSource::Repo,
162 grammar,
163 regexes,
164 layer.registry(),
165 )?)
166 }
167 None => None,
168 };
169 let none = FormatRegistry::default();
170 let host = repo.as_ref().unwrap_or(&none);
171 let merged = refuse_findings(&layer, host)?;
172 unsettled(&broken, host)?;
173 let formats = RepoFormats {
174 folder: (!files.is_empty()).then(|| layer.registry().clone()),
175 merged: (repo.is_some() || !files.is_empty()).then_some(merged),
176 repo,
177 hash: hash.finish(),
178 };
179 Ok(formats)
180}
181
182pub(super) fn line_message(f: &crate::Finding) -> String {
185 match f.line {
186 Some(l) => format!("line {l}: {}", crate::report::message(f)),
187 None => crate::report::message(f),
188 }
189}
190
191fn parse_doc(path: &RepoPath, text: &str) -> Result<Spanned> {
193 yaml::parse(text, 1).map_err(|e| Error::formats(path.clone(), e.to_string()))
194}
195
196pub(super) fn layer_of(
199 path: &RepoPath,
200 doc: &Spanned,
201 registry: &Spanned,
202 source: FormatSource,
203 grammar: &Grammar,
204 regexes: &RegexCache,
205 base: &FormatRegistry,
206) -> Result<FormatRegistry> {
207 FormatRegistry::from_yaml_at(
208 registry,
209 doc.get("types"),
210 source,
211 grammar,
212 regexes,
213 path,
214 Some(base),
215 )
216 .map_err(|findings| {
217 let messages: Vec<String> = findings.iter().map(line_message).collect();
218 Error::formats(path.clone(), messages.join("; "))
219 })
220}
221
222#[cfg(test)]
223mod tests {
224 use std::{
225 fs,
226 path::{Path, PathBuf},
227 };
228
229 use super::*;
230 use crate::grammar::{FormatMatch, load_grammar};
231
232 fn temp(name: &str) -> PathBuf {
233 let dir = crate::test_support::fresh_dir(&format!("formats-{name}"));
234 fs::create_dir_all(dir.join(".sokf")).unwrap();
235 dir
236 }
237
238 fn with(dir: &Path, text: Option<&str>) -> Result<Option<FormatRegistry>> {
239 with_all(dir, text).map(|f| f.repo)
240 }
241
242 fn with_all(dir: &Path, text: Option<&str>) -> Result<RepoFormats> {
243 if let Some(text) = text {
244 fs::write(dir.join(".sokf/formats.yaml"), text).unwrap();
245 }
246 let grammar = load_grammar().unwrap();
247 load_repo_formats(
248 &RepoRoot::new(dir.to_path_buf()),
249 &grammar,
250 &RegexCache::new(),
251 )
252 }
253
254 #[test]
255 fn absent_file_is_none_and_a_good_file_is_the_repo_layer() {
256 let dir = temp("ok");
257 assert!(with(&dir, None).unwrap().is_none());
258 let r = with(
259 &dir,
260 Some("registry:\n requirement-ears:\n pattern: '.*'\n example: x\n"),
261 )
262 .unwrap()
263 .unwrap();
264 assert_eq!(r.entries["requirement-ears"].1, FormatSource::Repo);
265 fs::remove_dir_all(&dir).unwrap();
266 }
267
268 #[test]
273 fn an_embedded_format_takes_the_type_that_settles_a_clash() {
274 let l = Layers::new("settled");
275 for (file, kinds) in [("a", "[Versioning]"), ("b", "[Deprecation]")] {
276 l.write(
277 &format!(".sokf/formats.d/{file}/formats.yaml"),
278 Some(&format!(
279 "types:\n evolution-kind: {kinds}\nregistry: {{}}\n"
280 )),
281 );
282 }
283 l.write(
284 ".sokf/formats.yaml",
285 Some("types:\n evolution-kind: [Retirement]\nregistry: {}\n"),
286 );
287 let (format, _) = l.entry("requirement-evolution");
288 assert!(
289 matches!(
290 format.check("Retirement: The file goes."),
291 FormatMatch::Ok(_)
292 ),
293 "{:?}",
294 format.check("Retirement: The file goes.")
295 );
296 assert!(matches!(
297 format.check("Versioning: The file goes."),
298 FormatMatch::Fail(_)
299 ));
300 }
301
302 const ONE: &str = ".sokf/formats.d/pakf/@acme/one/formats.yaml";
305 const TWO: &str = ".sokf/formats.d/pakf/@acme/two/formats.yaml";
306
307 const BIG: &str = "'\\w{1,200}'";
309
310 struct Layers {
314 dir: PathBuf,
315 grammar: Grammar,
316 embedded: FormatRegistry,
317 }
318
319 impl Layers {
320 fn new(name: &str) -> Self {
321 let grammar = load_grammar().unwrap();
322 let embedded = crate::test_support::requirement_formats(&grammar);
323 Layers {
324 dir: temp(name),
325 grammar,
326 embedded,
327 }
328 }
329
330 fn write(&self, path: &str, text: Option<&str>) {
333 match text {
334 Some(text) => crate::test_support::write(&self.dir, path, text),
335 None => fs::remove_file(self.dir.join(path)).unwrap(),
336 }
337 }
338
339 fn load(&self) -> Result<RepoFormats> {
340 load_repo_formats_on(
341 &RepoRoot::new(self.dir.clone()),
342 self.embedded.clone(),
343 &self.grammar,
344 &RegexCache::new(),
345 )
346 }
347
348 fn error(&self) -> String {
350 self.load().unwrap_err().to_string()
351 }
352
353 fn entry(&self, name: &str) -> (crate::grammar::Format, FormatSource) {
355 let effective = self.load().unwrap().effective(&self.embedded);
356 effective.entries[name].clone()
357 }
358 }
359
360 impl Drop for Layers {
361 fn drop(&mut self) {
362 let _ = fs::remove_dir_all(&self.dir);
363 }
364 }
365
366 fn one() -> FormatSource {
367 FormatSource::File("/.sokf/formats.d/pakf/@acme/one/formats.yaml".into())
368 }
369
370 #[test]
373 fn the_layer_formats_d_lies_above_the_embedded_formats() {
374 let l = Layers::new("above");
375 assert_eq!(l.entry("requirement-evolution").1, FormatSource::Embedded);
376 l.write(
378 ONE,
379 Some("registry:\n requirement-evolution:\n patch: true\n example: 'Versioning: The file changes with each release.'\n"),
380 );
381 let (format, source) = l.entry("requirement-evolution");
382 assert_eq!(source, one());
383 assert!(
384 format
385 .examples()
386 .contains(&"Versioning: The file changes with each release.")
387 );
388 assert!(matches!(
389 format.check("Sunset: A sentence."),
390 FormatMatch::Fail(_)
391 ));
392 l.write(
394 ONE,
395 Some("registry:\n requirement-evolution:\n pattern: '.*'\n example: A line.\n"),
396 );
397 let (format, source) = l.entry("requirement-evolution");
398 assert_eq!(source, one());
399 assert!(matches!(
400 format.check("Sunset: anything"),
401 FormatMatch::Ok(_)
402 ));
403 }
404
405 #[test]
407 fn a_patch_of_formats_d_merges_onto_the_layers_below() {
408 let l = Layers::new("patch");
409 l.write(
410 ONE,
411 Some("registry:\n user-story:\n patch: true\n example: 'ST-1: AS A writer, I WANT a patch, SO THAT the folder changes a format.'\n"),
412 );
413 let (format, _) = l.entry("user-story");
414 assert!(
415 format.examples().contains(
416 &"ST-1: AS A writer, I WANT a patch, SO THAT the folder changes a format."
417 )
418 );
419 assert!(matches!(
422 format.check("ST-1: I want a patch."),
423 FormatMatch::Fail(_)
424 ));
425 let story = "ST-2: AS A writer, I WANT a story, SO THAT it reads.";
426 assert!(
427 matches!(format.check(story), FormatMatch::Ok(Some(ref c)) if c.key == "ST-2"),
428 "{:?}",
429 format.check(story)
430 );
431 }
432
433 #[test]
435 fn alike_patches_of_formats_d_count_once() {
436 let l = Layers::new("alike");
437 let story = "ST-1: AS A writer, I WANT a patch, SO THAT the folder changes a format.";
438 l.write(
439 ONE,
440 Some(&format!(
441 "registry:\n user-story:\n patch: true\n example: '{story}'\n"
442 )),
443 );
444 l.write(
445 TWO,
446 Some(&format!("# The same patch as one.\nregistry:\n user-story: {{ example: \"{story}\", patch: true }}\n")),
447 );
448 let layer = l.load().unwrap().folder_layer().unwrap();
450 assert_eq!(layer.entries["user-story"].1, one());
451 let ubiquitous = " ubiquitous:\n example: 'PLUMB-4_AC-1 [ubiquitous]: the plumber SHALL queue a message.'\n";
454 let event = " event:\n example: 'PLUMB-1_AC-1 [event]: WHEN a program writes, the plumber SHALL deliver the message.'\n";
455 let patch = |first: &str, second: &str| {
456 format!(
457 "registry:\n requirement-ears:\n patch: true\n variants:\n{first}{second}"
458 )
459 };
460 l.write(ONE, Some(&patch(ubiquitous, event)));
461 l.write(TWO, Some(&patch(event, ubiquitous)));
462 assert!(l.load().is_ok());
463 }
464
465 #[test]
468 fn an_embedded_format_that_a_type_of_formats_d_breaks_stops_the_run() {
469 let l = Layers::new("embedded-d");
472 let types = format!("types:\n evolution-kind: {BIG}\n sentence: {BIG}\n");
473 l.write(ONE, Some(&format!("{types}registry: {{}}\n")));
474 let err = l.error();
475 assert!(
476 err.starts_with("/.sokf/formats.d/pakf/@acme/one/formats.yaml: ")
477 && err.contains("`requirement-evolution`")
478 && err.contains("the layer `embedded`")
479 && err.contains("`evolution-kind`"),
480 "{err}"
481 );
482 l.write(
485 ONE,
486 Some(&format!(
487 "{types}registry:\n requirement-evolution:\n patch: true\n template: '${{:evolution-kind}}: A sentence.'\n example: 'Versioning: A sentence.'\n"
488 )),
489 );
490 assert!(l.load().is_ok());
491 l.write(ONE, Some(&format!("{types}registry: {{}}\n")));
492 l.write(
495 ".sokf/formats.yaml",
496 Some("registry:\n requirement-evolution:\n pattern: '.*'\n example: 'Versioning: A sentence.'\n"),
497 );
498 assert!(l.load().is_ok());
499 l.write(
501 ".sokf/formats.yaml",
502 Some("registry:\n requirement-evolution:\n patch: true\n template: '${:evolution-kind}: A sentence.'\n example: 'Versioning: A sentence.'\n"),
503 );
504 assert!(l.load().is_ok());
505 l.write(
507 ".sokf/formats.yaml",
508 Some("types:\n sentence: '[A-Z].*\\.'\nregistry: {}\n"),
509 );
510 assert!(l.load().is_ok());
511 l.write(".sokf/formats.yaml", None);
513 l.write(
514 ONE,
515 Some(&format!("types:\n evolution-kind: [Versioning, Deprecation]\n sentence: {BIG}\nregistry: {{}}\n")),
516 );
517 assert!(l.load().is_ok());
518 }
519
520 #[test]
522 fn a_format_below_compiles_against_the_types_that_a_schema_sees() {
523 let l = Layers::new("below");
524 l.write(
527 ONE,
528 Some(&format!(
529 "types:\n evolution-kind: {BIG}\nregistry: {{}}\n"
530 )),
531 );
532 l.write(
533 TWO,
534 Some("types:\n sentence: '\\w{1,199}'\nregistry: {}\n"),
535 );
536 let err = l.error();
537 assert!(
538 err.starts_with("/.sokf/formats.d/pakf/@acme/one/formats.yaml: ")
539 && err.contains("format `requirement-evolution`: ")
540 && err.contains("the types `evolution-kind`, `sentence` of this layer"),
541 "{err}"
542 );
543 l.write(TWO, None);
545 l.write(
546 ".sokf/formats.yaml",
547 Some("types:\n sentence: [x]\nregistry: {}\n"),
548 );
549 assert!(l.load().is_ok());
550 l.write(".sokf/formats.yaml", None);
554 l.write(
555 ONE,
556 Some(&format!(
557 "types:\n property-id: {BIG}\n property-shape: {BIG}\nregistry: {{}}\n"
558 )),
559 );
560 let err = l.error();
561 assert!(
562 err.contains("`requirement-property`") && !err.contains("`requirement-evolution`"),
563 "{err}"
564 );
565 l.write(
568 ONE,
569 Some("types:\n evolution-kind: '\\w{1,199}'\nregistry: {}\n"),
570 );
571 l.write(
572 ".sokf/formats.yaml",
573 Some("types:\n sentence: '\\w{1,201}'\nregistry: {}\n"),
574 );
575 let err = l.error();
576 assert!(
577 err.starts_with("/.sokf/formats.yaml: ")
578 && err.contains("format `requirement-evolution`: ")
579 && err.contains("the type `sentence` of this layer"),
580 "{err}"
581 );
582 l.write(
583 ".sokf/formats.yaml",
584 Some("types:\n sentence: [x]\nregistry: {}\n"),
585 );
586 assert!(l.load().is_ok());
587 }
588
589 #[test]
591 fn an_embedded_format_that_a_type_of_formats_yaml_breaks_stops_the_run() {
592 let l = Layers::new("embedded-repo");
593 let types = format!("types:\n evolution-kind: {BIG}\n sentence: {BIG}\n");
594 l.write(
595 ".sokf/formats.yaml",
596 Some(&format!("{types}registry: {{}}\n")),
597 );
598 let err = l.error();
599 assert!(
600 err.starts_with("/.sokf/formats.yaml: ")
601 && err.contains(
602 "format `requirement-evolution`: the entry of the layer `embedded` no longer compiles against the types `evolution-kind`, `sentence` of this layer"
603 ),
604 "{err}"
605 );
606 l.write(
609 ONE,
610 Some("types:\n sentence: '[A-Z].*\\.'\nregistry: {}\n"),
611 );
612 l.write(
613 TWO,
614 Some("types:\n sentence: '[A-Z].*[.!]'\nregistry: {}\n"),
615 );
616 let err = l.error();
617 assert!(
618 err.starts_with("/.sokf/formats.yaml: ") && err.contains("`requirement-evolution`"),
619 "{err}"
620 );
621 l.write(
623 ".sokf/formats.yaml",
624 Some(&format!("types:\n sentence: {BIG}\nregistry: {{}}\n")),
625 );
626 assert!(l.load().is_ok());
627 }
628
629 #[test]
630 fn refuses_bad_files() {
631 let dir = temp("bad");
632 for text in [
633 "registry: [",
634 "other: 1\n",
635 "registry:\n requirement-ears:\n doc: d\n",
636 "registry:\n requirement-ears:\n doc: d\n example: e\n pattern: '('\n",
637 ] {
638 let e = with(&dir, Some(text)).unwrap_err();
639 assert!(matches!(e, Error::FormatsFile { .. }), "{text:?} -> {e}");
640 assert!(e.to_string().starts_with("/.sokf/formats.yaml: "), "{e}");
641 }
642 fs::remove_dir_all(&dir).unwrap();
643 }
644}