/
build.rs
242 lines (227 loc) · 9.19 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
extern crate zoneinfo_parse;
use zoneinfo_parse::line::Line;
use zoneinfo_parse::table::{TableBuilder, Table};
use zoneinfo_parse::transitions::TableTransitions;
use zoneinfo_parse::structure::{Structure, Child};
use zoneinfo_parse::transitions::FixedTimespan;
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::collections::BTreeSet;
// This function is needed until zoneinfo_parse handles comments correctly.
// Technically a '#' symbol could occur between double quotes and should be
// ignored in this case, however this never happens in the tz database as it
// stands.
fn strip_comments(mut line: String) -> String {
line.find('#').map(|pos| line.truncate(pos));
line
}
// Generate a list of the time zone periods beyond the first that apply
// to this zone, as a string representation of a static slice.
fn format_rest(rest: Vec<(i64, FixedTimespan)>) -> String {
let mut ret = "&[\n".to_string();
for (start, FixedTimespan { utc_offset, dst_offset, name }) in rest {
ret.push_str(&format!(
" ({start}, FixedTimespan {{ utc_offset: {utc}, dst_offset: {dst}, name: \"{name}\" }}),\n",
start = start,
utc = utc_offset,
dst = dst_offset,
name = name,
));
}
ret.push_str(" ]");
ret
}
// Convert all '/' to '__', all '+' to 'Plus' and '-' to 'Minus', unless
// it's a hyphen, in which case remove it. This is so the names can be used
// as rust identifiers.
fn convert_bad_chars(name: &str) -> String {
let name = name.replace("/", "__").replace("+", "Plus");
if let Some(pos) = name.find('-') {
if name[pos+1..].chars().next().map(char::is_numeric).unwrap_or(false) {
name.replace("-", "Minus")
} else {
name.replace("-", "")
}
} else {
name
}
}
// The timezone file contains impls of `Timespans` for all timezones in the
// database. The `Wrap` wrapper in the `timezone_impl` module then implements
// TimeZone for any contained struct that implements `Timespans`.
fn write_timezone_file(timezone_file: &mut File, table: &Table) {
let zones = table.zonesets.keys().chain(table.links.keys()).collect::<BTreeSet<_>>();
write!(timezone_file, "use ::timezone_impl::{{TimeSpans, FixedTimespanSet, FixedTimespan}};\n",).unwrap();
write!(timezone_file, "use std::fmt::{{Debug, Formatter, Error}};\n\n",).unwrap();
write!(timezone_file, "use std::str::FromStr;\n\n",).unwrap();
write!(timezone_file, "#[derive(Clone, Copy, PartialEq, Eq)]\npub enum Tz {{\n").unwrap();
for zone in &zones {
let zone_name = convert_bad_chars(zone);
write!(timezone_file, " {zone},\n", zone = zone_name).unwrap();
}
write!(timezone_file, "}}\n\n").unwrap();
write!(timezone_file,
"impl FromStr for Tz {{
type Err = String;
fn from_str(s: &str) -> Result<Self, String> {{
match s {{\n").unwrap();
for zone in &zones {
let zone_name = convert_bad_chars(zone);
write!(timezone_file,
" \"{raw_zone_name}\" => Ok(Tz::{zone}),\n",
zone = zone_name,
raw_zone_name = zone).unwrap();
}
write!(timezone_file,
" s => Err(s.to_string())
}}
}}
}}\n\n").unwrap();
write!(timezone_file,
"impl Debug for Tz {{
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {{
match *self {{\n").unwrap();
for zone in &zones {
let zone_name = convert_bad_chars(zone);
write!(timezone_file,
" Tz::{zone} => write!(f, \"{raw_zone_name}\"),\n",
zone = zone_name,
raw_zone_name = zone).unwrap();
}
write!(timezone_file,
" }}
}}
}}\n\n").unwrap();
write!(timezone_file,
"impl TimeSpans for Tz {{
fn timespans(&self) -> FixedTimespanSet {{
match *self {{\n").unwrap();
for zone in &zones {
let timespans = table.timespans(&zone).unwrap();
let zone_name = convert_bad_chars(zone);
write!(
timezone_file,
" Tz::{zone} => {{
const REST: &'static [(i64, FixedTimespan)] = {rest};
FixedTimespanSet {{
first: FixedTimespan {{
utc_offset: {utc},
dst_offset: {dst},
name: \"{name}\",
}},
rest: REST
}}
}},\n\n",
zone = zone_name,
rest = format_rest(timespans.rest),
utc = timespans.first.utc_offset,
dst = timespans.first.dst_offset,
name = timespans.first.name,
).unwrap();
}
write!(timezone_file,
" }}
}}
}}\n").unwrap();
}
// Create a file containing nice-looking re-exports such as Europe::London
// instead of having to use chrono_tz::timezones::Europe__London
fn write_directory_file(directory_file: &mut File, table: &Table) {
// add the `loose' zone definitions first at the top of the file
write!(directory_file, "use timezones::Tz;\n\n").unwrap();
let zones = table.zonesets.keys().chain(table.links.keys())
.filter(|zone| !zone.contains('/'))
.collect::<BTreeSet<_>>();
for zone in zones {
let zone = convert_bad_chars(zone);
write!(directory_file,
"pub const {name} : Tz = Tz::{name};\n",
name = zone).unwrap();
}
write!(directory_file, "\n").unwrap();
// now add the `structured' zone names in submodules
for entry in table.structure() {
if entry.name.contains('/') { continue; }
let module_name = convert_bad_chars(entry.name);
write!(directory_file, "pub mod {name} {{\n", name = module_name).unwrap();
write!(directory_file, " use timezones::Tz;\n\n",).unwrap();
for child in entry.children {
match child {
Child::Submodule(name) => {
let submodule_name = convert_bad_chars(name);
write!(directory_file, " pub mod {name} {{\n", name = submodule_name).unwrap();
write!(directory_file, " use timezones::Tz;\n\n",).unwrap();
let full_name = entry.name.to_string() + "/" + name;
for entry in table.structure() {
if entry.name == full_name {
for child in entry.children {
match child {
Child::Submodule(_) => panic!("Depth of > 3 nested submodules not implemented!"),
Child::TimeZone(name) => {
let converted_name = convert_bad_chars(name);
write!(directory_file,
" pub const {name} : Tz = Tz::{module_name}__{submodule_name}__{name};\n",
module_name = module_name,
submodule_name = submodule_name,
name = converted_name,
).unwrap();
}
}
}
}
}
write!(directory_file, " }}\n\n").unwrap();
},
Child::TimeZone(name) => {
let name = convert_bad_chars(name);
write!(directory_file,
" pub const {name} : Tz = Tz::{module_name}__{name};\n",
module_name = module_name,
name = name).unwrap();
}
}
}
write!(directory_file, "}}\n\n").unwrap();
}
}
fn main() {
let mut table = TableBuilder::new();
let tzfiles = [
"tz/africa",
"tz/antarctica",
"tz/asia",
"tz/australasia",
"tz/backward",
"tz/etcetera",
"tz/europe",
"tz/northamerica",
"tz/pacificnew",
"tz/southamerica",
];
let lines = tzfiles.iter()
.map(Path::new)
.map(File::open)
.map(Result::unwrap)
.map(BufReader::new)
.flat_map(BufRead::lines)
.map(Result::unwrap)
.map(strip_comments);
for line in lines {
match Line::from_str(&line).unwrap() {
Line::Zone(zone) => table.add_zone_line(zone).unwrap(),
Line::Continuation(cont) => table.add_continuation_line(cont).unwrap(),
Line::Rule(rule) => table.add_rule_line(rule).unwrap(),
Line::Link(link) => table.add_link_line(link).unwrap(),
Line::Space => {},
}
}
let table = table.build();
let timezone_path = Path::new(&env::var("OUT_DIR").unwrap()).join("timezones.rs");
let mut timezone_file = File::create(&timezone_path).unwrap();
write_timezone_file(&mut timezone_file, &table);
let directory_path = Path::new(&env::var("OUT_DIR").unwrap()).join("directory.rs");
let mut directory_file = File::create(&directory_path).unwrap();
write_directory_file(&mut directory_file, &table);
}