use std::path::PathBuf;
struct Section {
title: String,
slug: String,
pages: Vec<String>,
}
fn main() {
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let docs = root.join("docs");
let index = docs.join("index.toml");
println!("cargo:rerun-if-changed={}", index.display());
let src = std::fs::read_to_string(&index).unwrap_or_else(|e| panic!("read {}: {e}", index.display()));
let mut out = String::from(
"// @generated by build.rs from docs/index.toml.\n\
/// (section title, section slug, [(page slug, markdown)]).\n\
pub(crate) static HELP_SECTIONS: &[(&str, &str, &[(&str, &str)])] = &[\n",
);
for section in parse(&src) {
out.push_str(&format!(" ({:?}, {:?}, &[\n", section.title, section.slug));
for page in §ion.pages {
let path = docs.join(page);
assert!(path.is_file(), "docs/index.toml lists {page}, which does not exist");
println!("cargo:rerun-if-changed={}", path.display());
let stem = page.strip_suffix(".md").unwrap_or(page);
out.push_str(&format!(
" ({stem:?}, include_str!({:?})),\n",
path.display().to_string()
));
}
out.push_str(" ]),\n");
}
out.push_str("];\n");
let dest = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR")).join("help_docs.rs");
std::fs::write(dest, out).expect("write help_docs.rs");
}
fn parse(src: &str) -> Vec<Section> {
let mut sections: Vec<Section> = Vec::new();
let mut in_pages = false;
for raw in src.lines() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line == "[[section]]" {
sections.push(Section { title: String::new(), slug: String::new(), pages: Vec::new() });
in_pages = false;
continue;
}
let Some(current) = sections.last_mut() else { continue };
if in_pages || line.starts_with("pages") {
current.pages.extend(quoted(line));
in_pages = !line.contains(']');
continue;
}
if let Some(v) = line.strip_prefix("title").and_then(value) {
current.title = v;
} else if let Some(v) = line.strip_prefix("slug").and_then(value) {
current.slug = v;
}
}
sections
}
fn value(rest: &str) -> Option<String> {
quoted(rest.trim_start().strip_prefix('=')?).into_iter().next()
}
fn quoted(line: &str) -> Vec<String> {
line.split('"').skip(1).step_by(2).map(str::to_owned).collect()
}