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
use crate::formatter::{
CountryCode, Formatter, NewComponent, PlaceBuilder, ReplaceRule, Replacement, Rules, Template,
Templates,
};
use crate::Component;
use failure::{format_err, Error};
use std::collections::HashMap;
use std::str::FromStr;
pub fn read_configuration() -> Formatter {
let templates_file = include_str!("../address-formatting/conf/countries/worldwide.yaml");
let raw_templates = yaml_rust::YamlLoader::load_from_str(templates_file)
.expect("impossible to read worldwide.yaml file");
let default_template = build_template(&raw_templates[0]["default"]["address_template"])
.expect("no default address_template provided");
let fallback_template = build_template(&raw_templates[0]["default"]["fallback_template"])
.expect("no fallback address_template provided");
let mut overrided_countries = HashMap::new();
let mut fallback_templates_by_country = HashMap::new();
let mut rules_by_country = HashMap::new();
let mut templates_by_country: HashMap<CountryCode, Template> = raw_templates[0]
.as_hash()
.unwrap()
.iter()
.filter_map(|(k, v)| {
k.as_str()
.and_then(|k| CountryCode::from_str(k).ok())
.map(|c| (c, v))
})
.filter_map(|(country_code, v)| {
if let Ok(fallback_template) = build_template(&v["fallback_template"]) {
fallback_templates_by_country.insert(country_code.clone(), fallback_template);
}
if let Some(parent_country) = v["use_country"]
.as_str()
.and_then(|k| CountryCode::from_str(k).ok())
{
overrided_countries.insert(country_code, (parent_country, v.clone()));
None
} else {
let replace_rules = read_replace(&v["replace"]);
let post_format_replace_rules = read_replace(&v["postformat_replace"])
.into_iter()
.map(|r| match r {
ReplaceRule::All(r) => r,
_ => panic!("postformat rules cannot be applied on only one element"),
})
.collect();
let template = build_template(&v["address_template"]).expect(&format!(
"no address_template found for country {}",
country_code
));
let rules = Rules {
replace: replace_rules,
postformat_replace: post_format_replace_rules,
..Default::default()
};
rules_by_country.insert(country_code.clone(), rules);
Some((country_code, template))
}
})
.collect();
for (country_code, (parent_country_code, template)) in overrided_countries.into_iter() {
let overrided_template = templates_by_country[&parent_country_code].clone();
templates_by_country.insert(country_code.clone(), overrided_template);
let mut add_component = None;
if let Some(ac) = template["add_component"].as_str() {
let part: Vec<_> = ac.split('=').collect();
assert_eq!(part.len(), 2);
let component = Component::from_str(part[0]);
if let Ok(c) = component {
if c == Component::State {
add_component = Some(NewComponent {
component: c,
new_value: part[1].to_owned(),
});
}
}
}
let mut new_rules = rules_by_country
.get(&parent_country_code)
.map(|r| r.clone())
.unwrap_or_else(|| Rules::default());
new_rules.change_country_code = Some(parent_country_code.as_str().to_owned());
new_rules.change_country = template["change_country"].as_str().map(|s| s.to_string());
new_rules.add_component = add_component;
rules_by_country.insert(country_code.clone(), new_rules);
}
let state_codes_file = include_str!("../address-formatting/conf/state_codes.yaml");
let state_codes: HashMap<String, HashMap<String, String>> =
serde_yaml::from_str(state_codes_file).expect("invalid state_codes.yaml file");
let state_codes = state_codes
.into_iter()
.flat_map(|(country, states)| {
states.into_iter().map(move |(state_code, state_name)| {
(
(
CountryCode::from_str(&country).expect("invalid country code"),
state_name,
),
state_code,
)
})
})
.collect();
let county_codes_file = include_str!("../address-formatting/conf/county_codes.yaml");
let county_codes: HashMap<String, HashMap<String, String>> =
serde_yaml::from_str(county_codes_file).expect("invalid county_codes.yaml file");
let county_codes = county_codes
.into_iter()
.flat_map(|(country, counties)| {
counties.into_iter().map(move |(county_code, county_name)| {
(
(
CountryCode::from_str(&country).expect("invalid country code"),
county_name,
),
county_code,
)
})
})
.collect();
let templates = Templates {
default_template,
fallback_template,
templates_by_country,
fallback_templates_by_country,
rules_by_country,
fallback_rules: Rules::default(),
};
Formatter {
templates,
state_codes,
county_codes,
}
}
pub fn read_place_builder_configuration() -> PlaceBuilder {
let component_file = include_str!("../address-formatting/conf/components.yaml");
let raw_components = yaml_rust::YamlLoader::load_from_str(component_file)
.expect("impossible to read components.yaml file");
let mut component_aliases = HashMap::<_, _>::new();
for c in &raw_components {
if let Some(aliases) = c["aliases"].as_vec() {
let name = c["name"].as_str().unwrap();
let component =
Component::from_str(name).expect(&format!("{} is not a valid component", name));
for a in aliases {
component_aliases
.entry(component)
.or_insert_with(|| vec![])
.push(a.as_str().unwrap().to_string());
}
}
}
PlaceBuilder { component_aliases }
}
fn build_template(yaml_value: &yaml_rust::Yaml) -> Result<Template, Error> {
let addr_template = yaml_value
.as_str()
.ok_or_else(|| format_err!("no value to build template"))?;
Ok(Template::new(addr_template))
}
fn read_replace(yaml_rules: &yaml_rust::Yaml) -> Vec<ReplaceRule> {
yaml_rules
.as_vec()
.map(|v| {
v.iter()
.map(|r| {
let r = r.as_vec().expect("replace should be a list");
assert_eq!(r.len(), 2);
let first_val = r[0].as_str().expect("invalid replace rule");
if first_val.contains('=') {
let parts = first_val.split('=').collect::<Vec<_>>();
let component = Component::from_str(parts[0]).expect(&format!(
"in replace '{}' is not a valid component",
parts[0]
));
ReplaceRule::Component((
component,
Replacement {
regex: regex::RegexBuilder::new(parts[1])
.multi_line(true)
.build()
.expect("invalid regex"),
replacement_value: r[1]
.as_str()
.expect("invalid replace rule")
.to_owned(),
},
))
} else {
ReplaceRule::All(Replacement {
regex: regex::RegexBuilder::new(first_val)
.multi_line(true)
.build()
.expect("invalid regex"),
replacement_value: r[1]
.as_str()
.expect("invalid replace rule")
.to_owned(),
})
}
})
.collect()
})
.unwrap_or_else(|| vec![])
}