forked from rust-lang/www.rust-lang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.rs
255 lines (232 loc) · 7.39 KB
/
i18n.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
use handlebars::{
Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderErrorReason,
};
use rocket::request::FromParam;
use std::collections::HashSet;
use handlebars_fluent::{
fluent_bundle::{concurrent::FluentBundle, FluentResource, FluentValue},
loader::SimpleLoader,
simple_loader,
};
simple_loader!(create_loader, "./locales/", "en-US", core: "./locales/core.ftl",
customizer: add_bundle_functions);
fn add_bundle_functions(bundle: &mut FluentBundle<&'static FluentResource>) {
bundle
.add_function("EMAIL", |values, _named| {
let email = match values.first() {
Some(FluentValue::String(ref s)) => s,
_ => return FluentValue::None,
};
FluentValue::String(format!("<a href='mailto:{0}' lang='en-US'>{0}</a>", email).into())
})
.expect("could not add function");
bundle
.add_function("ENGLISH", |values, _named| {
let text = match values.first() {
Some(FluentValue::String(ref s)) => s,
_ => return FluentValue::None,
};
FluentValue::String(format!("<span lang='en-US'>{0}</span>", text).into())
})
.expect("could not add function");
}
#[derive(Serialize)]
pub struct LocaleInfo {
pub lang: &'static str,
pub text: &'static str,
}
pub const EXPLICIT_LOCALE_INFO: &[LocaleInfo] = &[
LocaleInfo {
lang: "en-US",
text: "English",
},
LocaleInfo {
lang: "es",
text: "Español",
},
LocaleInfo {
lang: "fr",
text: "Français",
},
LocaleInfo {
lang: "it",
text: "Italiano",
},
LocaleInfo {
lang: "ja",
text: "日本語",
},
LocaleInfo {
lang: "pt-BR",
text: "Português",
},
LocaleInfo {
lang: "ru",
text: "Русский",
},
LocaleInfo {
lang: "tr",
text: "Türkçe",
},
LocaleInfo {
lang: "uz",
text: "O'zbek",
},
LocaleInfo {
lang: "zh-CN",
text: "简体中文",
},
LocaleInfo {
lang: "zh-TW",
text: "正體中文",
},
];
lazy_static! {
pub static ref SUPPORTED_LOCALES: HashSet<&'static str> =
EXPLICIT_LOCALE_INFO.iter().map(|x| x.lang).collect();
}
pub struct TeamHelper {
i18n: SimpleLoader,
}
impl TeamHelper {
pub fn new() -> Self {
Self::default()
}
}
impl Default for TeamHelper {
fn default() -> Self {
Self {
i18n: create_loader(),
}
}
}
enum TeamHelperParam {
/// `{{team-text team name}}`
Name,
/// `{{team-text team description}}`
Description,
/// `{{team-text team role (lookup member.roles 0)}}`
Role(String),
}
impl TeamHelperParam {
fn fluent_id(&self, team_name: &str) -> String {
match self {
TeamHelperParam::Name => format!("governance-team-{team_name}-name"),
TeamHelperParam::Description => format!("governance-team-{team_name}-description"),
TeamHelperParam::Role(role_id) => format!("governance-role-{role_id}"),
}
}
fn english<'a>(&'a self, team: &'a serde_json::Value) -> &'a str {
match self {
TeamHelperParam::Name => team["website_data"]["name"].as_str().unwrap(),
TeamHelperParam::Description => team["website_data"]["description"].as_str().unwrap(),
TeamHelperParam::Role(role_id) => {
for role in team["roles"].as_array().unwrap() {
if role["id"] == *role_id {
return role["description"].as_str().unwrap();
}
}
// This should never happen. The `validate_member_roles` test in
// the team repo enforces that `.members.*.roles.*` lines up
// with exactly one `.roles.*.id`.
role_id
}
}
}
}
impl HelperDef for TeamHelper {
fn call<'reg: 'rc, 'rc>(
&self,
h: &Helper<'rc>,
_: &'reg Handlebars,
context: &'rc Context,
rcx: &mut RenderContext<'reg, 'rc>,
out: &mut dyn Output,
) -> HelperResult {
let Some(name) = h.param(0) else {
return Err(RenderErrorReason::ParamNotFoundForIndex(
"{{team-text}} must have at least two parameters",
0,
)
.into());
};
let Some(name) = name.relative_path() else {
return Err(RenderErrorReason::InvalidParamType(
"{{team-text}} takes only identifier parameters",
)
.into());
};
let Some(id) = h.param(1) else {
return Err(RenderErrorReason::ParamNotFoundForIndex(
"{{team-text}} must have at least two parameters",
1,
)
.into());
};
let Some(id) = id.relative_path() else {
return Err(RenderErrorReason::InvalidParamType(
"{{team-text}} takes only identifier parameters",
)
.into());
};
let param = match id.as_str() {
"name" => TeamHelperParam::Name,
"description" => TeamHelperParam::Description,
"role" => {
let Some(role_id) = h.param(2) else {
return Err(RenderErrorReason::ParamNotFoundForIndex(
"{{team-text}} requires a third parameter for the role id",
2,
)
.into());
};
TeamHelperParam::Role(role_id.value().as_str().unwrap().to_owned())
}
unrecognized => {
return Err(RenderErrorReason::Other(format!(
"unrecognized {{{{team-text}}}} param {unrecognized:?}",
))
.into());
}
};
let team = rcx
.evaluate(context, name)
.map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;
let lang = context
.data()
.get("lang")
.expect("Language not set in context")
.as_str()
.expect("Language must be string");
let team_name = team.as_json()["name"].as_str().unwrap();
// English uses the team data directly, so that it gets autoupdated
if lang == "en-US" {
let english = param.english(team.as_json());
out.write(english)
.map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;
} else if let Some(value) = self.i18n.lookup_no_default_fallback(
&lang.parse().expect("language must be valid"),
¶m.fluent_id(team_name),
None,
) {
out.write(&value)
.map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;
} else {
let english = param.english(team.as_json());
out.write(english)
.map_err(|e| RenderErrorReason::NestedError(Box::new(e)))?;
}
Ok(())
}
}
pub struct SupportedLocale(pub String);
impl<'r> FromParam<'r> for SupportedLocale {
type Error = ();
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
if SUPPORTED_LOCALES.contains(param) {
Ok(SupportedLocale(param.parse().map_err(|_| ())?))
} else {
Err(())
}
}
}