|
| 1 | +//! Infrastructure to test the mdbook documentation. |
| 2 | +//! |
| 3 | +//! Generates a module for each Markdown file in the `src/` directory, and includes |
| 4 | +//! the contents of each file as a doc comment for that module. |
| 5 | +
|
| 6 | +use std::env; |
| 7 | +use std::fs; |
| 8 | +use std::io; |
| 9 | +use std::path::{Path, PathBuf}; |
| 10 | + |
| 11 | +/// Recursively finds all Markdown files in the given path and collects their paths into `mds`. |
| 12 | +fn find_mds(dir: impl AsRef<Path>, mds: &mut Vec<PathBuf>) -> io::Result<()> { |
| 13 | + for entry in fs::read_dir(dir)? { |
| 14 | + let path = entry?.path(); |
| 15 | + if path.is_dir() { |
| 16 | + find_mds(path, mds)?; |
| 17 | + } else if path.extension().and_then(|s| s.to_str()) == Some("md") { |
| 18 | + mds.push(path); |
| 19 | + } |
| 20 | + } |
| 21 | + Ok(()) |
| 22 | +} |
| 23 | + |
| 24 | +fn main() -> io::Result<()> { |
| 25 | + let mut mds = Vec::new(); |
| 26 | + find_mds("src", &mut mds)?; |
| 27 | + |
| 28 | + let mut lib = String::new(); |
| 29 | + |
| 30 | + for md in mds { |
| 31 | + let md_path = md.to_str().unwrap(); |
| 32 | + println!("cargo::rerun-if-changed={md_path}"); |
| 33 | + let mod_name = md_path.replace(['/', '\\', '-', '.'], "_"); |
| 34 | + use std::fmt::Write; |
| 35 | + writeln!( |
| 36 | + &mut lib, |
| 37 | + "#[allow(non_snake_case)] #[doc = include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), r\"{}{md_path}\"))] mod {mod_name} {{}}", |
| 38 | + std::path::MAIN_SEPARATOR, |
| 39 | + ).unwrap(); |
| 40 | + } |
| 41 | + |
| 42 | + let dest_path = Path::new(&env::var("OUT_DIR").unwrap()).join("mdbook.rs"); |
| 43 | + fs::write(&dest_path, lib)?; |
| 44 | + println!("cargo::rerun-if-changed=build.rs"); |
| 45 | + Ok(()) |
| 46 | +} |
0 commit comments