use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use comrak::nodes::NodeValue;
use comrak::{Arena, Options, parse_document};
use serde::Deserialize;
use crate::document::{Document, Kind};
use crate::markup::split_front_matter;
use crate::nav;
use crate::problem::Problem;
#[derive(Deserialize)]
#[serde(untagged)]
enum Names {
One(String),
Many(Vec<String>),
}
#[derive(Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct Rules {
parent: Option<Names>,
sections: Option<Vec<String>>,
}
struct Type {
parent: Option<Vec<String>>,
sections: Vec<String>,
}
pub struct Structure {
folder: PathBuf,
folder_name: String,
types: BTreeMap<String, Type>,
files: Vec<PathBuf>,
problems: Vec<Problem>,
parents: HashMap<PathBuf, PathBuf>,
}
impl Structure {
pub fn of(document: &Document) -> Option<Self> {
let folder = document.structure.clone()?;
let Kind::Site { .. } = &document.kind else {
return None;
};
let folder_name = document
.name(&folder)
.unwrap_or_else(|| folder.display().to_string());
let mut files: Vec<PathBuf> = std::fs::read_dir(&folder)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.filter(|file| file.extension().is_some_and(|ext| ext == "md"))
.collect();
files.sort();
let mut types = BTreeMap::new();
let mut problems = Vec::new();
let mut named = Vec::new();
for file in &files {
let name = file
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let shown = document
.name(file)
.unwrap_or_else(|| file.display().to_string());
let source = std::fs::read_to_string(file).unwrap_or_default();
let yaml = split_front_matter(&source).map_or("", |(yaml, _)| yaml);
let rules = if yaml.trim().is_empty() {
Rules::default()
} else {
serde_yaml::from_str(yaml).unwrap_or_else(|error: serde_yaml::Error| {
problems.push(Problem {
file: shown.clone(),
line: error.location().map(|at| at.line() + 1),
column: None,
message: format!("front matter — {error}"),
target: None,
});
Rules::default()
})
};
let parent = rules.parent.map(|names| match names {
Names::One(name) => vec![name],
Names::Many(names) => names,
});
for parent in parent.iter().flatten() {
named.push((shown.clone(), line_of(&source, parent, 0), parent.clone()));
}
types.insert(
name,
Type {
parent,
sections: rules.sections.unwrap_or_default(),
},
);
}
for (file, line, parent) in named {
if !types.contains_key(&parent) {
problems.push(Problem {
file,
line,
column: None,
message: format!("parent {parent} — no {folder_name}/{parent}.md"),
target: None,
});
}
}
Some(Structure {
folder,
folder_name,
types,
files,
problems,
parents: nav::parents(document),
})
}
pub fn files(&self) -> &[PathBuf] {
&self.files
}
pub fn type_problems(&self) -> Vec<Problem> {
self.problems.clone()
}
pub fn problems(&self, document: &Document, page: &Path, source: &str) -> Vec<Problem> {
let Some(file) = document.name(page) else {
return Vec::new();
};
if !page.starts_with(&document.base)
|| page.starts_with(&self.folder)
|| page == document.base.join("404.md")
{
return Vec::new();
}
let problem = |line: Option<usize>, message: String, target: Option<String>| Problem {
file: file.clone(),
line,
column: None,
message,
target,
};
let mut problems = Vec::new();
let own = page_type(source);
match &own {
None => problems.push(problem(None, "no page-type".to_string(), None)),
Some((name, line)) if !self.types.contains_key(name) => problems.push(problem(
Some(*line),
format!("page-type {name} — no {}/{name}.md", self.folder_name),
None,
)),
Some(_) => {}
}
let Some((name, own)) = own.and_then(|(name, _)| {
let own = self.types.get(&name)?;
Some((name, own))
}) else {
return problems;
};
for (line, message) in sections(source, &name, &own.sections) {
problems.push(problem(line, message, None));
}
let mut placed = HashSet::new();
for topic in nav::topics(source) {
let nav::Target::Page(child) = nav::resolve(document, page, &topic.href) else {
continue;
};
if self.parents.get(&child).map(PathBuf::as_path) != Some(page)
|| child.starts_with(&self.folder)
|| !placed.insert(child.clone())
{
continue;
}
let Some((child_type, _)) = std::fs::read_to_string(&child)
.ok()
.and_then(|source| page_type(&source))
else {
continue;
};
let Some(allowed) = self
.types
.get(&child_type)
.and_then(|kind| kind.parent.as_ref())
else {
continue;
};
if !allowed.contains(&name) {
let from = source.find("\n## Topics").unwrap_or(0);
problems.push(problem(
line_of(source, &topic.href, from),
format!(
"{} — a page of type {child_type} sits under {}, and this page's type is {name}",
topic.href,
any_of(allowed)
),
Some(topic.href.clone()),
));
}
}
problems
}
}
fn line_of(source: &str, needle: &str, from: usize) -> Option<usize> {
let at = from + source[from..].find(needle)?;
Some(source[..at].lines().count().max(1))
}
fn any_of(names: &[String]) -> String {
match names {
[] => String::new(),
[one] => one.clone(),
[most @ .., last] => format!("{} or {last}", most.join(", ")),
}
}
pub fn page_type(source: &str) -> Option<(String, usize)> {
let (yaml, _) = split_front_matter(source)?;
let map: serde_yaml::Mapping = serde_yaml::from_str(yaml).ok()?;
let name = map.get("page-type")?.as_str()?.trim().to_string();
if name.is_empty() {
return None;
}
let line = yaml
.lines()
.position(|line| line.starts_with("page-type"))
.map_or(1, |at| at + 2);
Some((name, line))
}
pub fn front_matter(source: &str, key: &str) -> Option<String> {
let (yaml, _) = split_front_matter(source)?;
let map: serde_yaml::Mapping = serde_yaml::from_str(yaml).ok()?;
let value = map.get(key)?.as_str()?.trim().to_string();
(!value.is_empty()).then_some(value)
}
fn sections(source: &str, name: &str, required: &[String]) -> Vec<(Option<usize>, String)> {
if required.is_empty() {
return Vec::new();
}
let body = split_front_matter(source).map_or(source, |(_, body)| body);
let before = source[..source.len() - body.len()].lines().count();
let arena = Arena::new();
let root = parse_document(&arena, body, &Options::default());
let headings: Vec<(String, usize)> = root
.children()
.filter_map(|node| {
let data = node.data.borrow();
match &data.value {
NodeValue::Heading(heading) if heading.level == 2 => Some((
nav::text(node).trim().to_string(),
before + data.sourcepos.start.line,
)),
_ => None,
}
})
.collect();
let has = required
.iter()
.map(|heading| format!("## {heading}"))
.collect::<Vec<_>>()
.join(", ");
let mut problems = Vec::new();
let mut last: Option<(&str, usize)> = None;
for heading in required {
let Some((_, line)) = headings.iter().find(|(found, _)| found == heading) else {
problems.push((
None,
format!("no ## {heading} section — a page of type {name} has {has}"),
));
continue;
};
match last {
Some((earlier, at)) if *line < at => problems.push((
Some(*line),
format!("## {heading} comes before ## {earlier} — a page of type {name} has {has}"),
)),
_ => last = Some((heading, *line)),
}
}
problems
}