1use std::collections::{BTreeMap, HashMap, HashSet};
7use std::path::{Path, PathBuf};
8
9use comrak::nodes::NodeValue;
10use comrak::{Arena, Options, parse_document};
11use serde::Deserialize;
12
13use crate::document::{Document, Kind};
14use crate::markup::split_front_matter;
15use crate::nav;
16use crate::problem::Problem;
17
18#[derive(Deserialize)]
20#[serde(untagged)]
21enum Names {
22 One(String),
24 Many(Vec<String>),
26}
27
28#[derive(Deserialize, Default)]
30#[serde(deny_unknown_fields)]
31struct Rules {
32 parent: Option<Names>,
34 sections: Option<Vec<String>>,
36}
37
38struct Type {
40 parent: Option<Vec<String>>,
42 sections: Vec<String>,
44}
45
46pub struct Structure {
48 folder: PathBuf,
50 folder_name: String,
52 types: BTreeMap<String, Type>,
54 files: Vec<PathBuf>,
56 problems: Vec<Problem>,
58 parents: HashMap<PathBuf, PathBuf>,
60}
61
62impl Structure {
63 pub fn of(document: &Document) -> Option<Self> {
66 let folder = document.structure.clone()?;
67 let Kind::Site { .. } = &document.kind else {
68 return None;
69 };
70 let folder_name = document
71 .name(&folder)
72 .unwrap_or_else(|| folder.display().to_string());
73 let mut files: Vec<PathBuf> = std::fs::read_dir(&folder)
74 .into_iter()
75 .flatten()
76 .flatten()
77 .map(|entry| entry.path())
78 .filter(|file| file.extension().is_some_and(|ext| ext == "md"))
79 .collect();
80 files.sort();
81 let mut types = BTreeMap::new();
82 let mut problems = Vec::new();
83 let mut named = Vec::new();
84 for file in &files {
85 let name = file
86 .file_stem()
87 .unwrap_or_default()
88 .to_string_lossy()
89 .into_owned();
90 let shown = document
91 .name(file)
92 .unwrap_or_else(|| file.display().to_string());
93 let source = std::fs::read_to_string(file).unwrap_or_default();
94 let yaml = split_front_matter(&source).map_or("", |(yaml, _)| yaml);
95 let rules = if yaml.trim().is_empty() {
96 Rules::default()
97 } else {
98 serde_yaml::from_str(yaml).unwrap_or_else(|error: serde_yaml::Error| {
99 problems.push(Problem {
100 file: shown.clone(),
101 line: error.location().map(|at| at.line() + 1),
103 column: None,
104 message: format!("front matter — {error}"),
105 target: None,
106 });
107 Rules::default()
108 })
109 };
110 let parent = rules.parent.map(|names| match names {
111 Names::One(name) => vec![name],
112 Names::Many(names) => names,
113 });
114 for parent in parent.iter().flatten() {
115 named.push((shown.clone(), line_of(&source, parent, 0), parent.clone()));
116 }
117 types.insert(
118 name,
119 Type {
120 parent,
121 sections: rules.sections.unwrap_or_default(),
122 },
123 );
124 }
125 for (file, line, parent) in named {
126 if !types.contains_key(&parent) {
127 problems.push(Problem {
128 file,
129 line,
130 column: None,
131 message: format!("parent {parent} — no {folder_name}/{parent}.md"),
132 target: None,
133 });
134 }
135 }
136 Some(Structure {
137 folder,
138 folder_name,
139 types,
140 files,
141 problems,
142 parents: nav::parents(document),
143 })
144 }
145
146 pub fn files(&self) -> &[PathBuf] {
148 &self.files
149 }
150
151 pub fn type_problems(&self) -> Vec<Problem> {
153 self.problems.clone()
154 }
155
156 pub fn problems(&self, document: &Document, page: &Path, source: &str) -> Vec<Problem> {
162 let Some(file) = document.name(page) else {
163 return Vec::new();
164 };
165 if !page.starts_with(&document.base)
166 || page.starts_with(&self.folder)
167 || page == document.base.join("404.md")
168 {
169 return Vec::new();
170 }
171 let problem = |line: Option<usize>, message: String, target: Option<String>| Problem {
172 file: file.clone(),
173 line,
174 column: None,
175 message,
176 target,
177 };
178 let mut problems = Vec::new();
179 let own = page_type(source);
180 match &own {
181 None => problems.push(problem(None, "no page-type".to_string(), None)),
182 Some((name, line)) if !self.types.contains_key(name) => problems.push(problem(
183 Some(*line),
184 format!("page-type {name} — no {}/{name}.md", self.folder_name),
185 None,
186 )),
187 Some(_) => {}
188 }
189 let Some((name, own)) = own.and_then(|(name, _)| {
190 let own = self.types.get(&name)?;
191 Some((name, own))
192 }) else {
193 return problems;
194 };
195 for (line, message) in sections(source, &name, &own.sections) {
196 problems.push(problem(line, message, None));
197 }
198 let mut placed = HashSet::new();
199 for topic in nav::topics(source) {
200 let nav::Target::Page(child) = nav::resolve(document, page, &topic.href) else {
201 continue;
202 };
203 if self.parents.get(&child).map(PathBuf::as_path) != Some(page)
204 || child.starts_with(&self.folder)
205 || !placed.insert(child.clone())
206 {
207 continue;
208 }
209 let Some((child_type, _)) = std::fs::read_to_string(&child)
210 .ok()
211 .and_then(|source| page_type(&source))
212 else {
213 continue;
214 };
215 let Some(allowed) = self
216 .types
217 .get(&child_type)
218 .and_then(|kind| kind.parent.as_ref())
219 else {
220 continue;
221 };
222 if !allowed.contains(&name) {
223 let from = source.find("\n## Topics").unwrap_or(0);
224 problems.push(problem(
225 line_of(source, &topic.href, from),
226 format!(
227 "{} — a page of type {child_type} sits under {}, and this page's type is {name}",
228 topic.href,
229 any_of(allowed)
230 ),
231 Some(topic.href.clone()),
232 ));
233 }
234 }
235 problems
236 }
237}
238
239fn line_of(source: &str, needle: &str, from: usize) -> Option<usize> {
242 let at = from + source[from..].find(needle)?;
243 Some(source[..at].lines().count().max(1))
244}
245
246fn any_of(names: &[String]) -> String {
248 match names {
249 [] => String::new(),
250 [one] => one.clone(),
251 [most @ .., last] => format!("{} or {last}", most.join(", ")),
252 }
253}
254
255pub fn page_type(source: &str) -> Option<(String, usize)> {
258 let (yaml, _) = split_front_matter(source)?;
259 let map: serde_yaml::Mapping = serde_yaml::from_str(yaml).ok()?;
260 let name = map.get("page-type")?.as_str()?.trim().to_string();
261 if name.is_empty() {
262 return None;
263 }
264 let line = yaml
265 .lines()
266 .position(|line| line.starts_with("page-type"))
267 .map_or(1, |at| at + 2);
268 Some((name, line))
269}
270
271pub fn front_matter(source: &str, key: &str) -> Option<String> {
274 let (yaml, _) = split_front_matter(source)?;
275 let map: serde_yaml::Mapping = serde_yaml::from_str(yaml).ok()?;
276 let value = map.get(key)?.as_str()?.trim().to_string();
277 (!value.is_empty()).then_some(value)
278}
279
280fn sections(source: &str, name: &str, required: &[String]) -> Vec<(Option<usize>, String)> {
283 if required.is_empty() {
284 return Vec::new();
285 }
286 let body = split_front_matter(source).map_or(source, |(_, body)| body);
287 let before = source[..source.len() - body.len()].lines().count();
289 let arena = Arena::new();
290 let root = parse_document(&arena, body, &Options::default());
291 let headings: Vec<(String, usize)> = root
292 .children()
293 .filter_map(|node| {
294 let data = node.data.borrow();
295 match &data.value {
296 NodeValue::Heading(heading) if heading.level == 2 => Some((
297 nav::text(node).trim().to_string(),
298 before + data.sourcepos.start.line,
299 )),
300 _ => None,
301 }
302 })
303 .collect();
304 let has = required
305 .iter()
306 .map(|heading| format!("## {heading}"))
307 .collect::<Vec<_>>()
308 .join(", ");
309 let mut problems = Vec::new();
310 let mut last: Option<(&str, usize)> = None;
311 for heading in required {
312 let Some((_, line)) = headings.iter().find(|(found, _)| found == heading) else {
313 problems.push((
314 None,
315 format!("no ## {heading} section — a page of type {name} has {has}"),
316 ));
317 continue;
318 };
319 match last {
320 Some((earlier, at)) if *line < at => problems.push((
321 Some(*line),
322 format!("## {heading} comes before ## {earlier} — a page of type {name} has {has}"),
323 )),
324 _ => last = Some((heading, *line)),
325 }
326 }
327 problems
328}