-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.rs
187 lines (152 loc) · 5.43 KB
/
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use std::fs;
use std::fs::{File, read_dir};
use std::io;
use std::io::Write;
use std::path::Path;
use quote::quote;
use proc_macro2::{TokenStream, Ident, Span};
use serde::Deserialize;
use syntect::{
highlighting::ThemeSet,
html::highlighted_html_for_string,
parsing::SyntaxSet
};
/// pre-process a code snippet to add html
/// syntax-highlighting
fn highlight(code: &str) -> String {
let ps = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();
let syntax = ps.find_syntax_by_extension("rs").unwrap();
let theme = &ts.themes["base16-ocean.light"];
highlighted_html_for_string(code, &ps, syntax, &theme).unwrap()
}
/// the `example.toml` representation
#[derive(Debug, Deserialize)]
struct Info {
description: String,
motivation: String,
related: Option<String>,
}
fn extract_toml_info(file_name: &str) -> std::result::Result<Info, toml::de::Error> {
let raw_toml_info = fs::read(format!("examples/{file_name}.toml"))
.expect("please create examples/{file_name}.toml to provide some documentation");
let toml_info = String::from_utf8_lossy(&raw_toml_info);
toml::from_str(&toml_info)
}
fn quote_option(text: Option<String>) -> TokenStream {
match text {
Some(x) => quote!{Some(#x)},
None => quote!{None}
}
}
fn html_from_markdown(file_name: &str, input: String) -> String {
use pulldown_cmark::{Tag, Event};
let parser = pulldown_cmark::Parser::new(&input);
let checked_parser = parser
.map(|x| match x {
Event::Start(Tag::Heading(_,_,_)) => panic!(
"{file_name}.toml: headings are not allowed in this field"
),
_ => x,
});
// Write to a new String buffer.
let mut html_output = String::new();
pulldown_cmark::html::push_html(&mut html_output, checked_parser);
html_output
}
/// reads the `example` directory.
/// For each `foo.rs`, it will read it,
/// preprocess for syntax-highlighting,
/// read and parse corresponding `foo.toml` metadata
/// and eventually load `foo.css`
fn read_examples(path: &Path,
includes: &mut TokenStream,
examples: &mut TokenStream,
n_examples: &mut usize) -> Result<(), io::Error>{
for f in read_dir(path)? {
let f = f?;
let meta = f.metadata()?;
if meta.is_file() && f.path().extension().unwrap()=="rs" {
let file_name = f.path()
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string();
let raw_css = fs::read(format!("examples/{file_name}.css")).unwrap_or(Vec::new());
let css = String::from_utf8_lossy(&raw_css);
let info = match extract_toml_info(&file_name) {
Ok(x) => x,
Err(e) => {
eprintln!("please provide all the required fields in {file_name}.toml");
eprintln!("The missing field is {:?}", e.message());
panic!()
}
};
let description = info.description;
let motivation = html_from_markdown(&file_name, info.motivation);
let related=quote_option(
info.related.map(|x| html_from_markdown(&file_name, x))
);
format!("examples/{file_name}.css");
let example_name = Ident::new(&file_name, Span::call_site());
let relative_path = format!("../examples/{file_name}.rs");
let source =
std::str::from_utf8(
&fs::read(f.path())?
).unwrap().to_string();
let highlighted_source = highlight(&source);
examples.extend(
quote!{
Example {
name: #file_name,
source: #source,
highlighted_source: #highlighted_source,
code: pack_example(#example_name::showcase),
css: stylist::style!(#css).unwrap(),
description: #description,
motivation: #motivation,
related: #related,
},
}
);
includes.extend(
quote!{
mod #example_name {
include!(#relative_path);
}
}
);
*n_examples += 1;
}
};
Ok(())
}
fn main() -> Result<(), io::Error> {
let mut includes = TokenStream::new();
let mut examples = TokenStream::new();
let mut n_examples = 0usize;
read_examples(Path::new("./examples"),
&mut includes,
&mut examples,
&mut n_examples)?;
let generated_rust = quote!{
//! generated automatically by build.rs
#includes
use super::{Example, pack_example};
pub const N_EXAMPLES: usize = #n_examples;
pub type Examples = std::collections::HashMap<&'static str, std::rc::Rc<Example>>;
pub fn examples() -> Examples {
[
#examples
]
.into_iter()
.map(|e| (e.name, std::rc::Rc::new(e)))
.collect()
}
};
let pretty = prettyplease::unparse(&syn::parse2(generated_rust).unwrap());
File::create("src/examples.rs")?
.write_all(pretty.as_bytes())?;
Ok(())
}