-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
build.rs
95 lines (81 loc) · 2.91 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
use std::{
collections::BTreeMap,
fs::File,
io::{BufWriter, Write},
process::Command,
};
use serde::{Deserialize, Serialize};
/// Source: https://raw.githubusercontent.com/jshttp/mime-db/master/db.json
const DB_URL: &str = "https://unpkg.com/[email protected]/db.json";
const TPL_E: &str = "pub const {{name}}: [(&str, usize); {{len}}] = [{{items}}];";
const TPL_T: &str = "pub const {{name}}: [(&str, usize, usize); {{len}}] = [{{items}}];";
#[derive(Debug, Deserialize, Serialize)]
struct Kind {
source: Option<String>,
compressible: Option<bool>,
extensions: Option<Vec<String>>,
}
type Kinds = BTreeMap<String, Kind>;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let body: Kinds = reqwest::get(DB_URL).await?.json().await?;
let db: Kinds = body
.into_iter()
.filter(|(_k, v)| v.extensions.is_some())
.collect();
let types_file = File::create("src/types.rs")?;
let exts_file = File::create("src/extensions.rs")?;
{
let mut keys = Vec::new();
let mut values = Vec::new();
for (n, (key, value)) in db.iter().enumerate() {
let extensions: Vec<(String, usize)> = value
.extensions
.as_ref()
.unwrap()
.iter()
.map(|e| (e.to_owned(), n))
.collect();
// extensions.sort_by_key(|e| e.0.to_owned());
keys.push((key, values.len(), extensions.len()));
values.append(&mut extensions.clone());
}
let mut exts_writer = BufWriter::new(exts_file);
let exts: Vec<String> = values
.iter()
.map(|e| {
r#"("{{ext}}", {{pos}})"#
.replace("{{ext}}", &e.0)
.replace("{{pos}}", &e.1.to_string())
})
.collect();
exts_writer.write(
TPL_E
.replace("{{name}}", "EXTENSIONS")
.replace("{{len}}", &exts.len().to_string())
.replace("{{items}}", &exts.join(", "))
.as_bytes(),
)?;
exts_writer.flush()?;
let mut types_writer = BufWriter::new(types_file);
let types: Vec<String> = keys
.iter()
.map(|e| {
r#"("{{ext}}", {{start}}, {{end}})"#
.replace("{{ext}}", e.0)
.replace("{{start}}", &e.1.to_string())
.replace("{{end}}", &e.2.to_string())
})
.collect();
types_writer.write(
TPL_T
.replace("{{name}}", "TYPES")
.replace("{{len}}", &types.len().to_string())
.replace("{{items}}", &types.join(", "))
.as_bytes(),
)?;
types_writer.flush()?;
}
Command::new("cargo").args(&["fmt", "--all"]).output()?;
Ok(())
}