-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
266 lines (229 loc) · 8.1 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::ops::Deref;
use std::path::Path;
use itertools::Itertools;
use regex::Regex;
use select::document::Document;
use select::node::Data;
use select::node::Node;
use select::predicate::*;
use std::process::Command;
use quote::*;
use proc_macro2::TokenStream;
use proc_macro2::Literal;
struct Section<'a>(Node<'a>);
impl<'a> Section<'a> {
/// Generate a valid trait name from this section title
fn trait_name(&self) -> String {
let name = self.0.find(Name("h2")).nth(0).unwrap().text();
// Remove anything in parentheses
let invalid = Regex::new(r"\(.+?\)").unwrap();
let name = invalid.replace(&name, "");
let invalid = Regex::new("&").unwrap();
invalid
.replace(&name, "And")
.split_whitespace()
.collect::<Vec<_>>()
.join("")
}
/// Generate a the functions from this section
fn functions(&self) -> impl Iterator<Item=Function> {
self.0.find(Name("h4")).map(Function)
}
}
struct Function<'a>(Node<'a>);
impl<'a> Function<'a> {
/// Extract the function name from this section
fn name(&self) -> String {
self.0
.children()
.nth(0)
.unwrap()
.text()
.trim()
.to_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join("_")
}
fn raw_name(&self) -> String {
let text = self.0.children().nth(0).unwrap().text();
let name = text.trim();
// Small hack: because of inconsistencies in the HTML documentation we need to replace these names
let name = match name {
"Quote Endpoint" => "GLOBAL_QUOTE",
"Search Endpoint" => "SYMBOL_SEARCH",
_ => name,
};
name.to_owned()
}
/// Extract the function description from this section
fn description(&self) -> String {
let node = self.0;
following_nodes(node)
.filter(|node| match node.data() {
Data::Text(_) => false,
Data::Element(_, _) if node.is(Name("br")) => false,
_ => true,
})
.take_while(|node| !node.is(Name("h6")))
.map(|node| node.text())
.join(" ")
}
/// Generate the parameters for this function
fn parameters(&self) -> impl Iterator<Item=Parameter> + 'a {
let node = self.0;
following_nodes(node)
.filter(|node|
match node.data() {
Data::Text(_) => false,
Data::Element(_, _) if node.is(Name("br")) => false,
_ => true,
})
.skip_while(|node| !node.is(Name("h6"))) // skip description
.skip(1) // skip heading
.take_while(|node| !node.is(Name("h6")))
.batching(|iter|
iter.next().map(|node| (node, iter.next()))
)
.filter_map(move |(parameter, extra)| {
let extra = extra
.expect(&format!("Couldn't parse extra information for node {:?}", parameter));
let name = match parameter.find(Name("code")).nth(0) {
Some(n) => n.text(),
_ => panic!("Couldn't parse parameter name (invalid value at {:?})!", parameter),
};
let necessity = match () {
_ if parameter.text().contains("Required") => ParameterNecessity::Required,
_ if parameter.text().contains("Optional") => ParameterNecessity::Optional(
match extra.find(Name("code")).nth(0) {
Some(n) => {
let default = n.text();
default.split("=").nth(1).unwrap().to_owned()
}
_ => panic!("Couldn't parse parameter necessity default (invalid value at {:?})!", node),
}
),
_ => panic!("Couldn't parse parameter necessity (invalid value at {:?})!", node),
};
// We only want responses in JSON so we skip the datatype parameter
if name == "datatype" {
return None;
}
Some(Parameter { name, necessity })
})
}
fn to_tokens_with_body(&self) -> TokenStream {
use std::fmt::Write;
let mut lit = format!("https://www.alphavantage.co/query?");
let mut parameters = self.parameters();
write!(lit, "{}{}", parameters.next().unwrap().name, "={}").unwrap();
for parameter in parameters {
write!(lit, "&{}{}", parameter.name, "={}").unwrap();
}
let lit = Literal::string(&lit);
let args = self.parameters()
.map(|p| match p.name.deref() {
"apikey" => quote!(self.apikey),
"function" => Literal::string(&self.raw_name()).to_token_stream(),
_ => format_ident!("{}", p.name).to_token_stream(),
});
let signature = self.to_tokens_head();
quote!(
#signature {
let url = format!(#lit, #(#args),*);
self.client.get(&url)
}
)
}
fn to_tokens_head(&self) -> TokenStream {
let description = self.description();
let name = format_ident!("{}", self.name());
let parameters = self.parameters()
.filter(|p| p.name != "apikey" && p.name != "function")
.map(|x| format_ident!("{}", x.name))
.map(|x| quote!(#x: &str));
let parameters = std::iter::once(quote!(&self))
.chain(parameters);
quote!(
#[doc = #description]
fn #name(#(#parameters),*) -> Result<JsonObject, AlphavantageError>
)
}
fn to_tokens(&self) -> TokenStream {
let signature = self.to_tokens_head();
quote!(
#signature;
)
}
}
#[derive(Debug)]
enum ParameterNecessity {
Required,
Optional(String),
}
#[derive(Debug)]
struct Parameter {
name: String,
necessity: ParameterNecessity,
}
/// An Iterator which returns the Node following the current one
/// until there are no more node left.
fn following_nodes(node: Node) -> impl Iterator<Item=Node> {
let mut node = node;
std::iter::from_fn(move || {
if let Some(next) = node.next() {
node = next;
Some(next)
} else {
None
}
})
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("gen.rs");
let mut f = File::create(&dest_path).unwrap();
const DOCUMENTATION: &str = include_str!("documentation.html");
let document = Document::from(DOCUMENTATION);
let main_content = document
.find(Descendant(
Attr("class", "container-fluid"),
Name("article"),
))
.nth(0)
.unwrap();
let parsed_sections = main_content
.find(Name("section"))
.map(Section);
for section in parsed_sections {
let trait_name = format_ident!("{}", section.trait_name());
let functions = section.functions()
.map(|function| function.to_tokens());
let q = quote! {
pub trait #trait_name {
#(#functions) *
}
};
writeln!(&mut f, "{}", q).unwrap();
let functions = section.functions()
.map(|function| function.to_tokens_with_body());
let q = quote! {
impl<'a, T> #trait_name for AlphavantageClient<'a, T>
where T: RequestClient {
#(#functions) *
}
};
writeln!(&mut f, "{}", q).unwrap();
}
Command::new("rustfmt")
.arg("--backup")
// definitely add fn_params_layout=vertical once rustfmt 2 is released
.arg("--config")
.arg("edition=2018,format_strings=true,wrap_comments=true,normalize_doc_attributes=true")
.arg(&dest_path)
.spawn()
.unwrap();
}