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
use glob::glob;
use quote::quote;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
type Locale = String;
type Value = serde_json::Value;
type Translations = HashMap<Locale, Value>;
fn is_debug() -> bool {
std::env::var("RUST_I18N_DEBUG").unwrap_or_else(|_| "0".to_string()) == "1"
}
#[derive(Debug)]
struct Option {
locales_path: String,
}
impl syn::parse::Parse for Option {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let locales_path = input.parse::<syn::LitStr>()?.value();
Ok(Self { locales_path })
}
}
fn merge_value(a: &mut Value, b: &Value) {
match (a, b) {
(&mut Value::Object(ref mut a), &Value::Object(ref b)) => {
for (k, v) in b {
merge_value(a.entry(k.clone()).or_insert(Value::Null), v);
}
}
(a, b) => {
*a = b.clone();
}
}
}
#[proc_macro]
pub fn i18n(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let option = match syn::parse::<Option>(input) {
Ok(input) => input,
Err(err) => return err.to_compile_error().into(),
};
let cargo_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is empty");
let current_dir = std::path::PathBuf::from(cargo_dir);
let locales_path = current_dir.join(option.locales_path);
let translations = load_locales(&locales_path.display().to_string());
let code = generate_code(translations);
if is_debug() {
println!("{}", code.to_string());
}
code.into()
}
fn load_locales(locales_path: &str) -> Translations {
let mut translations: Translations = HashMap::new();
let path_pattern = format!("{}/**/*.yml", locales_path);
if is_debug() {
println!("cargo:i18n-locale={}", &path_pattern);
}
for entry in glob(&path_pattern).expect("Failed to read glob pattern") {
let entry = entry.unwrap();
if is_debug() {
println!("cargo:i18n-load={}", &entry.display());
}
let file = File::open(entry).expect("Failed to open the YAML file");
let mut reader = std::io::BufReader::new(file);
let mut content = String::new();
reader
.read_to_string(&mut content)
.expect("Read YAML file failed.");
let trs: Translations =
serde_yaml::from_str(&content).expect("Invalid YAML format, parse error");
trs.into_iter().for_each(|(k, new_value)| {
translations
.entry(k)
.and_modify(|old_value| merge_value(old_value, &new_value))
.or_insert(new_value);
});
}
translations
}
fn extract_vars(prefix: &str, trs: &Value) -> HashMap<String, String> {
let mut v = HashMap::<String, String>::new();
let prefix = prefix.to_string();
match &trs {
serde_json::Value::String(s) => {
v.insert(prefix, s.to_string());
}
serde_json::Value::Object(o) => {
for (k, vv) in o {
let key = format!("{}.{}", prefix, k);
v.extend(extract_vars(key.as_str(), vv));
}
}
serde_json::Value::Null => {
v.insert(prefix, "".into());
}
serde_json::Value::Bool(s) => {
v.insert(prefix, format!("{}", s));
}
serde_json::Value::Number(s) => {
v.insert(prefix, format!("{}", s));
}
serde_json::Value::Array(_) => {
v.insert(prefix, "".into());
}
}
v
}
fn generate_code(translations: Translations) -> proc_macro2::TokenStream {
let mut locales = Vec::<proc_macro2::TokenStream>::new();
let mut locale_vars = HashMap::<String, String>::new();
translations.iter().for_each(|(locale, trs)| {
let new_vars = extract_vars(locale.as_str(), &trs);
locale_vars.extend(new_vars);
});
locale_vars.iter().for_each(|(k, v)| {
let k = k.to_string();
let v = v.to_string();
locales.push(quote! {
#k => #v,
});
});
quote! {
lazy_static::lazy_static! {
static ref LOCALES: std::collections::HashMap<&'static str, &'static str> = map! [
#(#locales)*
"" => ""
];
}
pub fn translate(locale: &str, key: &str) -> String {
let key = format!("{}.{}", locale, key);
match LOCALES.get(key.as_str()) {
Some(value) => value.to_string(),
None => key.to_string(),
}
}
}
}