spec_driven_docs/services/
reader.rs1use include_dir::Dir;
9
10use crate::domain::docs_catalog::ShelfId;
11
12#[derive(Debug, Clone, Copy)]
14pub struct Shelf {
15 pub id: ShelfId,
17 pub dir: &'static Dir<'static>,
19 pub merged_specs: bool,
21 pub strip: Option<&'static str>,
23}
24
25pub const METHOD: Shelf = Shelf {
27 id: ShelfId::Method,
28 dir: &crate::embedded::METHOD,
29 strip: None,
30 merged_specs: false,
31};
32pub const SPECS: Shelf = Shelf {
34 id: ShelfId::Spec,
35 dir: &crate::embedded::SPECS,
36 strip: Some("SPEC-"),
37 merged_specs: true,
38};
39pub const TEMPLATES: Shelf = Shelf {
41 id: ShelfId::Template,
42 dir: &crate::embedded::TEMPLATES,
43 strip: Some("TEMPLATE-"),
44 merged_specs: false,
45};
46
47impl Shelf {
48 fn files(&self) -> Vec<(&'static str, &'static include_dir::File<'static>)> {
50 if self.merged_specs {
51 return crate::embedded::spec_files();
52 }
53 self.dir
54 .files()
55 .filter_map(|file| Some((file.path().as_os_str().to_str()?, file)))
56 .collect()
57 }
58}
59
60fn short_name<'a>(shelf: &Shelf, file_name: &'a str) -> Option<&'a str> {
61 let stem = file_name.strip_suffix(".md")?;
62 shelf
63 .strip
64 .map_or(Some(stem), |prefix| stem.strip_prefix(prefix))
65}
66
67#[must_use]
69pub fn list(shelf: &Shelf) -> Vec<String> {
70 let mut names: Vec<String> = shelf
71 .files()
72 .into_iter()
73 .filter_map(|(name, _)| short_name(shelf, name).map(String::from))
74 .collect();
75 names.sort();
76 names
77}
78
79#[must_use]
81pub fn get(shelf: &Shelf, name: &str) -> Option<&'static str> {
82 let wanted = name.strip_suffix(".md").unwrap_or(name);
83 shelf.files().into_iter().find_map(|(file_name, file)| {
84 let stem = file_name.strip_suffix(".md")?;
85 let matches = stem == wanted || short_name(shelf, file_name) == Some(wanted);
86 if matches { file.contents_utf8() } else { None }
87 })
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn shelves_list_their_short_names() {
96 assert!(list(&METHOD).contains(&"glossary".to_string()));
97 assert!(list(&SPECS).contains(&"distribution".to_string()));
98 assert!(list(&TEMPLATES).contains(&"adr".to_string()));
99 }
100
101 #[test]
102 fn documents_resolve_by_short_and_full_names() {
103 let by_short = get(&SPECS, "distribution").unwrap();
104 assert_eq!(get(&SPECS, "SPEC-distribution").unwrap(), by_short);
105 assert_eq!(get(&SPECS, "SPEC-distribution.md").unwrap(), by_short);
106 assert!(by_short.contains("distribution:instances-operate-offline"));
107 assert!(get(&SPECS, "nonexistent").is_none());
108 }
109}