-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdocs_build.rs
68 lines (61 loc) · 2 KB
/
docs_build.rs
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
#!/usr/bin/env run-cargo-script
//! This is a regular crate doc comment, but it also contains a partial
//! Cargo manifest. Note the use of a *fenced* code block, and the
//! `cargo` "language".
//!
//! ```cargo
//! [dependencies]
//! heck = "0.3.1"
//! pulldown-cmark = "0.5.2"
//! ```
extern crate heck;
extern crate pulldown_cmark;
use heck::KebabCase;
use pulldown_cmark::{html, CowStr, Event, Options, Parser, Tag};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
fn main() -> std::io::Result<()> {
let file = File::open("README.md")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
let options = Options::all();
let parser = Parser::new_ext(contents.as_str(), options);
let mut in_header_level = 0;
let parser = parser.map(|event| match event {
Event::Start(Tag::Header(num)) => {
in_header_level = num;
Event::Html(CowStr::Borrowed(""))
}
Event::Text(text) => {
if in_header_level > 0 {
let result_html = format!(
"<h{} id=\"{}\">{}</h{}>",
in_header_level,
text.to_kebab_case(),
text,
in_header_level
);
Event::Html(result_html.into())
} else {
Event::Text(text)
}
}
Event::End(Tag::Header(_)) => {
in_header_level = 0;
event
}
_ => event,
});
// Write to String buffer.
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
let template = File::open("docs_template.html")?;
let mut contents = String::new();
buf_reader = BufReader::new(template);
buf_reader.read_to_string(&mut contents)?;
contents = contents.replace("%%content%%", &html_output);
let mut file = File::create("docs/index.html")?;
file.write_all(contents.as_bytes())
}