1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#![doc = include_str!("../README.md")]

pub mod custom_types;
pub mod doc_item;
pub mod function;
pub mod glossary;
pub mod module;

pub use glossary::ModuleGlossary;
pub use module::{
    options::{options, ItemsOrder, MarkdownProcessor, SectionFormat},
    ModuleDocumentation,
};
use serde_json::json;

/// Generate documentation for the docusaurus markdown processor.
///
/// Returns a hashmap with the name of the module as the key and its raw documentation as the value.
pub fn generate_for_docusaurus(
    module: &ModuleDocumentation,
) -> Result<std::collections::HashMap<String, String>, handlebars::RenderError> {
    let mut hbs_registry = handlebars::Handlebars::new();

    hbs_registry
        .register_template_string(
            "docusaurus-module",
            include_str!("handlebars/docusaurus/header.hbs"),
        )
        .expect("template is valid");

    // A partial used to keep indentation for mdx to render correctly.
    hbs_registry
        .register_partial("ContentPartial", "{{{content}}}")
        .expect("partial is valid");

    generate(module, "docusaurus-module", &hbs_registry)
}

/// Generate documentation for the mdbook markdown processor.
///
/// Returns a hashmap with the name of the module as the key and its raw documentation as the value.
pub fn generate_for_mdbook(
    module: &ModuleDocumentation,
) -> Result<std::collections::HashMap<String, String>, handlebars::RenderError> {
    let mut hbs_registry = handlebars::Handlebars::new();

    hbs_registry
        .register_template_string(
            "mdbook-module",
            include_str!("handlebars/mdbook/header.hbs"),
        )
        .expect("template is valid");

    // A partial used to keep indentation for md to render correctly.
    hbs_registry
        .register_partial("ContentPartial", "{{{content}}}")
        .expect("partial is valid");

    generate(module, "mdbook-module", &hbs_registry)
}

fn generate(
    module: &ModuleDocumentation,
    template: &str,
    hbs_registry: &handlebars::Handlebars,
) -> Result<std::collections::HashMap<String, String>, handlebars::RenderError> {
    let mut documentation = std::collections::HashMap::default();
    let data = json!({
        "title": module.name,
        "slug": module.name,
        "description": module.documentation,
        "namespace": module.namespace,
        "items": module.items,
    });

    documentation.insert(
        module.name.to_string(),
        hbs_registry.render(template, &data)?,
    );

    for sub in &module.sub_modules {
        documentation.extend(generate(sub, template, hbs_registry)?);
    }

    Ok(documentation)
}