|
| 1 | +//! Preprocessor for the mdBook guide. |
| 2 | +
|
| 3 | +use mdbook_preprocessor::book::{Book, BookItem}; |
| 4 | +use mdbook_preprocessor::errors::Result; |
| 5 | +use mdbook_preprocessor::{Preprocessor, PreprocessorContext}; |
| 6 | +use semver::{Version, VersionReq}; |
| 7 | +use std::io; |
| 8 | + |
| 9 | +/// Preprocessing entry point. |
| 10 | +pub fn handle_preprocessing() -> Result<()> { |
| 11 | + let pre = GuideHelper; |
| 12 | + let (ctx, book) = mdbook_preprocessor::parse_input(io::stdin())?; |
| 13 | + |
| 14 | + let book_version = Version::parse(&ctx.mdbook_version)?; |
| 15 | + let version_req = VersionReq::parse(mdbook_preprocessor::MDBOOK_VERSION)?; |
| 16 | + |
| 17 | + if !version_req.matches(&book_version) { |
| 18 | + eprintln!( |
| 19 | + "warning: The {} plugin was built against version {} of mdbook, \ |
| 20 | + but we're being called from version {}", |
| 21 | + pre.name(), |
| 22 | + mdbook_preprocessor::MDBOOK_VERSION, |
| 23 | + ctx.mdbook_version |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + let processed_book = pre.run(&ctx, book)?; |
| 28 | + serde_json::to_writer(io::stdout(), &processed_book)?; |
| 29 | + |
| 30 | + Ok(()) |
| 31 | +} |
| 32 | + |
| 33 | +struct GuideHelper; |
| 34 | + |
| 35 | +impl Preprocessor for GuideHelper { |
| 36 | + fn name(&self) -> &str { |
| 37 | + "guide-helper" |
| 38 | + } |
| 39 | + |
| 40 | + fn run(&self, _ctx: &PreprocessorContext, mut book: Book) -> Result<Book> { |
| 41 | + insert_version(&mut book); |
| 42 | + Ok(book) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +fn insert_version(book: &mut Book) { |
| 47 | + let path = std::env::current_dir() |
| 48 | + .unwrap() |
| 49 | + .parent() |
| 50 | + .unwrap() |
| 51 | + .join("Cargo.toml"); |
| 52 | + let manifest_contents = std::fs::read_to_string(&path).unwrap(); |
| 53 | + let manifest: toml::Value = toml::from_str(&manifest_contents).unwrap(); |
| 54 | + let version = manifest["package"]["version"].as_str().unwrap(); |
| 55 | + const MARKER: &str = "{{ mdbook-version }}"; |
| 56 | + book.for_each_mut(|item| { |
| 57 | + let BookItem::Chapter(ch) = item else { |
| 58 | + return; |
| 59 | + }; |
| 60 | + if ch.is_draft_chapter() { |
| 61 | + return; |
| 62 | + } |
| 63 | + if ch.content.contains(MARKER) { |
| 64 | + ch.content = ch.content.replace(MARKER, version); |
| 65 | + } |
| 66 | + }); |
| 67 | +} |
0 commit comments