use std::fs; use std::path::{Path, PathBuf}; use arborium::Highlighter; use comrak::{Options, markdown_to_html}; use serde::Deserialize; const DOCS_DIR: &str = "docs"; const OUT_DIR: &str = "target/bough-docs-site"; #[derive(Deserialize, Default)] struct Frontmatter { #[serde(default)] title: Option, #[serde(default)] idx: Option, } #[derive(Debug)] struct TocEntry { title: String, href: String, children: Vec, } struct Page { title: String, slug: String, body_html: String, } fn parse_md(content: &str) -> (Frontmatter, String) { match markdown_frontmatter::parse::(content) { Ok((fm, body)) => (fm, body.to_owned()), Err(_) => (Frontmatter::default(), content.to_owned()), } } fn build_toc(dir: &Path, docs_dir: &Path) -> Vec { let Ok(entries) = fs::read_dir(dir) else { return Vec::new(); }; let mut items: Vec<(i64, TocEntry)> = Vec::new(); let mut dir_entries: Vec<_> = entries.flatten().collect(); dir_entries.sort_by_key(|e| e.file_name()); for entry in dir_entries { let path = entry.path(); if path.is_dir() { let index_path = path.join("index.md"); let (fm, _) = if index_path.exists() { let content = fs::read_to_string(&index_path).expect("failed to read index.md"); parse_md(&content) } else { (Frontmatter::default(), String::new()) }; let title = fm.title.unwrap_or_else(|| { path.file_name() .unwrap_or_default() .to_string_lossy() .into_owned() }); let idx = fm.idx.unwrap_or(i64::MAX); let rel = path.strip_prefix(docs_dir).unwrap(); let href = format!("/{}/", rel.to_string_lossy()); let children = build_toc(&path, docs_dir); items.push(( idx, TocEntry { title, href, children, }, )); } else if path.extension().is_some_and(|e| e == "md") { let stem = path.file_stem().unwrap_or_default(); if stem == "index" { continue; } let content = fs::read_to_string(&path).expect("failed to read md file"); let (fm, _) = parse_md(&content); let title = fm .title .unwrap_or_else(|| stem.to_string_lossy().into_owned()); let idx = fm.idx.unwrap_or(i64::MAX); let rel = path.strip_prefix(docs_dir).unwrap().with_extension(""); let href = format!("/{}/", rel.to_string_lossy()); items.push(( idx, TocEntry { title, href, children: Vec::new(), }, )); } } items.sort_by_key(|(idx, _)| *idx); items.into_iter().map(|(_, entry)| entry).collect() } fn highlight_code_blocks(html: &str, hl: &mut Highlighter) -> String { let mut out = String::with_capacity(html.len()); let mut rest = html; while let Some(pre_start) = rest.find("
')
            .and_then(|i| rest[i + 1..].find('>').map(|j| i + 1 + j + 1))
        else {
            out.push_str(rest);
            return out;
        };
        let code_body = &rest[code_start..];
        let Some(code_end) = code_body.find("
") else { out.push_str(rest); return out; }; let raw_code = &code_body[..code_end]; let decoded = raw_code .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'"); match hl.highlight(lang, &decoded) { Ok(highlighted) => { out.push_str("
");
                out.push_str(&highlighted);
                out.push_str("
"); } Err(_) => { out.push_str(&rest[..code_start + code_end + 13]); } } rest = &code_body[code_end + 13..]; } out.push_str(rest); out } fn render_toc_entries(entries: &[TocEntry], current_slug: &str) -> String { if entries.is_empty() { return String::new(); } let mut out = String::from("
    "); for entry in entries { let entry_slug = entry.href.trim_matches('/'); let id = entry_slug.replace('/', "-"); let is_match = entry_slug == current_slug || (!entry_slug.is_empty() && current_slug.starts_with(entry_slug) && current_slug[entry_slug.len()..].starts_with('/')); let class = if is_match { " class=\"active\"" } else { "" }; out.push_str(&format!( "
  1. {}", entry.href, entry.title )); if !entry.children.is_empty() { out.push_str(&render_toc_entries(&entry.children, current_slug)); } out.push_str("
  2. "); } out.push_str("
"); out } fn render_page(page: &Page, toc_html: &str) -> String { format!( r#" {title}

{title}

{body}
"#, title = page.title, body = page.body_html, toc = toc_html, ) } fn collect_md_files(dir: &Path) -> Vec { let mut files = Vec::new(); let Ok(entries) = fs::read_dir(dir) else { return files; }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { files.extend(collect_md_files(&path)); } else if path.extension().is_some_and(|e| e == "md") { files.push(path); } } files.sort(); files } const EXAMPLES_DIR: &str = "docs/mutations"; #[derive(Deserialize)] struct ExamplesFile { mutation: Vec, } #[derive(Deserialize)] struct MutationExample { kind: String, snippet: String, } fn make_mutation_reference(lang: &bough_core::LanguageId) -> String { use std::collections::BTreeMap; use std::fmt::Write; let ext = lang.file_extension(); let examples_path = Path::new(EXAMPLES_DIR).join(format!("{}.examples.toml", lang.slug())); let toml_content = fs::read_to_string(&examples_path).unwrap_or_else(|e| { panic!( "failed to read examples file {}: {e}", examples_path.display() ) }); let examples_file: ExamplesFile = toml::from_str(&toml_content).unwrap_or_else(|e| { panic!( "failed to parse examples file {}: {e}", examples_path.display() ) }); // Build kind key → snippet map, checking for duplicates let mut snippets: BTreeMap = BTreeMap::new(); for example in &examples_file.mutation { if snippets.contains_key(&example.kind) { panic!( "{}: duplicate example for kind '{}'", examples_path.display(), example.kind ); } // Validate the kind key is recognised if bough_core::MutantKind::from_key(&example.kind).is_none() { panic!( "{}: unknown mutation kind '{}'", examples_path.display(), example.kind ); } snippets.insert(example.kind.clone(), example.snippet.clone()); } // Check for extraneous keys (kinds the language doesn't support) for key in snippets.keys() { let kind = bough_core::MutantKind::from_key(key).unwrap(); let subs = lang.substitutions(&kind); if subs.is_empty() { panic!( "{}: example for kind '{}' but language {} doesn't support it (empty substitutions)", examples_path.display(), key, lang.display_name() ); } } let mut out = format!("+++\ntitle = \"{}\"\n+++\n\n", lang.display_name()); for kind in bough_core::MutantKind::all_variants() { let subs = lang.substitutions(&kind); if subs.is_empty() { continue; } let key = kind.to_key(); let snippet = snippets.get(&key).unwrap_or_else(|| { panic!( "{}: missing example for supported kind '{}'", examples_path.display(), key ) }); // Parse the snippet in-memory to find mutants of this kind let source_mutants = bough_core::find_mutants_in_source(*lang, snippet.as_bytes()); let matching: Vec<_> = source_mutants.iter().filter(|m| m.kind == kind).collect(); if matching.is_empty() { panic!( "{}: snippet for kind '{}' doesn't contain any mutants of that kind when parsed", examples_path.display(), key ); } let _ = writeln!(out, "## {}\n", kind.heading()); let _ = writeln!(out, "### Before\n\n```{ext}\n{}\n```\n", snippet.trim_end()); let _ = writeln!(out, "### After\n"); for mutant in &matching { let span_start = mutant.subst_span.start().byte(); let span_end = mutant.subst_span.end().byte(); for sub in &subs { let mutated = format!("{}{}{}", &snippet[..span_start], sub, &snippet[span_end..],); let _ = writeln!(out, "```{ext}\n{}\n```\n", mutated.trim_end()); } } } out } pub fn build() { let docs_dir = Path::new(DOCS_DIR); let out_dir = Path::new(OUT_DIR); if out_dir.exists() { fs::remove_dir_all(out_dir).expect("failed to clean output dir"); } fs::create_dir_all(out_dir).expect("failed to create output dir"); fs::write(out_dir.join("layout.css"), include_str!("layout.css")) .expect("failed to write layout.css"); let generated_dir = Path::new("target/bough-docs-generated"); if generated_dir.exists() { fs::remove_dir_all(generated_dir).expect("failed to clean generated dir"); } let reference_dir = generated_dir.join("config"); fs::create_dir_all(&reference_dir).expect("failed to create generated config dir"); let reference_md = format!( "+++\ntitle = \"Configuration Reference\"\n+++\n\n{}", crate::facet_reference::make_facet_reference::() ); fs::write(reference_dir.join("reference.md"), reference_md) .expect("failed to write config reference"); let mutations_dir = generated_dir.join("mutations"); fs::create_dir_all(&mutations_dir).expect("failed to create generated mutations dir"); for lang in bough_core::LanguageId::ALL { let md = make_mutation_reference(lang); fs::write(mutations_dir.join(format!("{}.md", lang.slug())), md) .expect("failed to write mutation reference"); } let mut md_files = collect_md_files(docs_dir); md_files.extend(collect_md_files(generated_dir)); if md_files.is_empty() { eprintln!("no markdown files found in {}", docs_dir.display()); return; } let mut toc = build_toc(docs_dir, docs_dir); for gen_entry in build_toc(generated_dir, generated_dir) { if let Some(existing) = toc.iter_mut().find(|e| e.href == gen_entry.href) { existing.children.extend(gen_entry.children); } else { toc.push(gen_entry); } } let mut hl = Highlighter::new(); let mut opts = Options::default(); opts.extension.table = true; opts.extension.strikethrough = true; opts.extension.autolink = true; opts.render.unsafe_ = true; let pages: Vec = md_files .iter() .map(|path| { let content = fs::read_to_string(path).expect("failed to read md file"); let (fm, body) = parse_md(&content); let title = fm.title.unwrap_or_else(|| { path.file_stem() .unwrap_or_default() .to_string_lossy() .into_owned() }); let rel = path .strip_prefix(docs_dir) .or_else(|_| path.strip_prefix(generated_dir)) .unwrap(); let slug = if rel.file_stem().is_some_and(|s| s == "index") { rel.parent() .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_default() } else { rel.with_extension("").to_string_lossy().into_owned() }; let body_html = markdown_to_html(&body, &opts); let body_html = highlight_code_blocks(&body_html, &mut hl); Page { title, slug, body_html, } }) .collect(); for page in &pages { let toc_html = render_toc_entries(&toc, &page.slug); let out_path = if page.slug.is_empty() { out_dir.join("index.html") } else { let dir = out_dir.join(&page.slug); fs::create_dir_all(&dir).expect("failed to create page dir"); dir.join("index.html") }; let html = render_page(page, &toc_html); fs::write(&out_path, html).expect("failed to write html"); eprintln!(" wrote {}", out_path.display()); } eprintln!("built {} pages into {}", pages.len(), out_dir.display()); } #[cfg(test)] mod tests { use super::*; /// Validates that every language has a complete, well-formed examples TOML file. /// /// This test calls `make_mutation_reference` for each language, which: /// - Loads and parses the TOML file /// - Checks for duplicate keys /// - Checks for unknown or unsupported mutation kinds /// - Verifies every supported kind has an example /// - Parses each snippet and verifies it contains mutants of the expected kind #[test] fn all_example_files_are_valid() { // Tests run from crate dir; examples are relative to workspace root let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(".."); std::env::set_current_dir(&workspace_root).expect("failed to cd to workspace root"); for lang in bough_core::LanguageId::ALL { let md = make_mutation_reference(lang); // Sanity: output should contain at least one heading assert!( md.contains("## "), "{}: generated markdown has no headings", lang.display_name() ); } } }