Skip to main content

mdbook_fishextract/
lib.rs

1mod mermaid;
2
3use crate::errors::Error;
4use fs_err as fs;
5use mdbook::book::SectionNumber;
6use mermaid::replace_mermaid_charts;
7use std::io::Write;
8use std::path::Path;
9use std::path::PathBuf;
10use std::str::FromStr;
11
12use mdbook::book::{Book, BookItem};
13use mdbook::preprocess::{Preprocessor, PreprocessorContext};
14
15pub mod errors;
16pub use self::errors::*;
17
18pub mod types;
19pub use self::types::*;
20
21pub struct Fishextract;
22
23impl Fishextract {
24    pub fn new() -> Fishextract {
25        Fishextract
26    }
27}
28
29impl Preprocessor for Fishextract {
30    fn name(&self) -> &str {
31        "fishextract"
32    }
33
34    fn supports_renderer(&self, renderer: &str) -> bool {
35        SupportedRenderer::from_str(renderer).is_ok()
36    }
37
38    fn run(
39        &self,
40        ctx: &PreprocessorContext,
41        book: Book,
42    ) -> std::result::Result<Book, mdbook::errors::Error> {
43        self.run_inner(ctx, book)
44            .map_err(mdbook::errors::Error::new)
45    }
46}
47
48fn get_config_value(cfg: &toml::value::Table, key: &str, default: impl Into<PathBuf>) -> PathBuf {
49    cfg.get(key)
50        .map(|x| x.as_str().expect("Config path is valid UTF8. qed"))
51        .map(PathBuf::from)
52        .unwrap_or(default.into())
53}
54
55fn fragment_path(cfg: &toml::value::Table) -> PathBuf {
56    get_config_value(cfg, "fragment_path", "fragments")
57}
58
59fn asset_path(cfg: &toml::value::Table) -> PathBuf {
60    get_config_value(cfg, "assets", PathBuf::from("src").join("assets"))
61}
62
63impl Fishextract {
64    fn run_inner(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
65        if let Some(cfg) = ctx.config.get_preprocessor(self.name()) {
66            let renderer = SupportedRenderer::from_str(ctx.renderer.as_str())?;
67
68            let fragment_path = fragment_path(cfg);
69            fs::create_dir_all(&fragment_path)?;
70
71            let fragment_path = fs::canonicalize(fragment_path)?;
72            log::info!("Using fragment path: {}", fragment_path.display());
73
74            // track all generated assets in a temporary dir
75            let mut used_fragments = Vec::new();
76
77            // error acc, only prints the first encountered error
78            let mut error = Ok::<_, Error>(());
79
80            // replace mermaid charts with prerendered svgs
81            book.for_each_mut(|item| {
82                if let BookItem::Chapter(ref mut ch) = item {
83                    log::info!(
84                        "Processing chapter {} - {}",
85                        ch.number
86                            .as_ref()
87                            .map(|sn| sn.to_string())
88                            .unwrap_or("Pre".to_owned()),
89                        ch.name.as_str()
90                    );
91                    log::debug!(
92                        "Chapter resides at {}",
93                        ch.path
94                            .as_ref()
95                            .map(|p| p.display().to_string())
96                            .unwrap_or_else(|| { "?".to_owned() })
97                    );
98
99                    let chapter_number = ch
100                        .number
101                        .as_ref()
102                        .unwrap_or(&SectionNumber::default())
103                        .to_string();
104
105                    match replace_mermaid_charts(
106                        ch.content.as_str(),
107                        &chapter_number,
108                        &ch.name,
109                        ch.path.as_ref().unwrap_or(&PathBuf::new()),
110                        &fragment_path,
111                        renderer,
112                        &mut used_fragments,
113                    ) {
114                        Ok(replace_with) => {
115                            ch.content = replace_with;
116                        }
117                        err if error.is_ok() => {
118                            error = err.map(|_| ()).map_err(Error::from);
119                        }
120                        _ => {}
121                    };
122                }
123            });
124
125            error?;
126
127            // copy fragments over to the asset path
128            let asset_path = asset_path(cfg);
129
130            fs::create_dir_all(&asset_path)?;
131
132            // copy all used fragments
133            if fragment_path != asset_path {
134                for fragment in used_fragments {
135                    let from = fragment_path.join(&fragment);
136                    let to = asset_path.join(&fragment);
137                    log::info!("Copying fishextract to assets dir: {} -> {}", from.display(), to.display());
138                    fs::copy(from, to)?;
139                }
140            } else {
141                log::debug!(
142                    "Fragments already in the right place, copying nothing {}",
143                    fragment_path.display()
144                )
145            }
146
147            Ok(book)
148        } else {
149            Err(Error::KeySectionNotFound)
150        }
151    }
152}