forked from ankitects/anki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
253 lines (220 loc) · 7.16 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
243
244
245
246
247
248
249
250
251
252
253
use std::fmt::Write;
use std::fs;
use std::path::Path;
use std::process::Command;
use fluent_syntax::ast::{Entry::Message, ResourceEntry};
use fluent_syntax::parser::parse;
use std::collections::HashMap;
fn get_identifiers(ftl_text: &str) -> Vec<String> {
let res = parse(ftl_text).unwrap();
let mut idents = vec![];
for entry in res.body {
if let ResourceEntry::Entry(Message(m)) = entry {
idents.push(m.id.name.to_string());
}
}
idents.sort();
idents
}
fn proto_enum(idents: &[String]) -> String {
let mut buf = String::from(
r#"// This file is automatically generated as part of the build process.
syntax = "proto3";
package BackendProto;
enum FluentString {
"#,
);
for (idx, s) in idents.iter().enumerate() {
let name = s.replace("-", "_").to_uppercase();
buf += &format!(" {} = {};\n", name, idx);
}
buf += "}\n";
buf
}
fn rust_string_vec(idents: &[String]) -> String {
let mut buf = String::from(
r#"// This file is automatically generated as part of the build process.
pub(super) const FLUENT_KEYS: &[&str] = &[
"#,
);
for s in idents {
buf += &format!(" \"{}\",\n", s);
}
buf += "];\n";
buf
}
#[cfg(test)]
mod test {
use crate::i18n::extract_idents::{get_identifiers, proto_enum, rust_string_vec};
#[test]
fn all() {
let idents = get_identifiers("key-one = foo\nkey-two = bar");
assert_eq!(idents, vec!["key-one", "key-two"]);
assert_eq!(
proto_enum(&idents),
r#"// This file is automatically generated as part of the build process.
syntax = "proto3";
package backend_strings;
enum FluentString {
KEY_ONE = 0;
KEY_TWO = 1;
}
"#
);
assert_eq!(
rust_string_vec(&idents),
r#"// This file is automatically generated as part of the build process.
const FLUENT_KEYS: &[&str] = &[
"key-one",
"key-two",
];
"#
);
}
}
struct CustomGenerator {}
fn write_method_enum(buf: &mut String, service: &prost_build::Service) {
buf.push_str(
r#"
use num_enum::TryFromPrimitive;
#[derive(PartialEq,TryFromPrimitive)]
#[repr(u32)]
pub enum BackendMethod {
"#,
);
for (idx, method) in service.methods.iter().enumerate() {
writeln!(buf, " {} = {},", method.proto_name, idx + 1).unwrap();
}
buf.push_str("}\n\n");
}
fn write_method_trait(buf: &mut String, service: &prost_build::Service) {
buf.push_str(
r#"
use prost::Message;
pub type BackendResult<T> = std::result::Result<T, crate::err::AnkiError>;
pub trait BackendService {
fn run_command_bytes2_inner(&self, method: u32, input: &[u8]) -> std::result::Result<Vec<u8>, crate::err::AnkiError> {
match method {
"#,
);
for (idx, method) in service.methods.iter().enumerate() {
write!(
buf,
concat!(" ",
"{idx} => {{ let input = {input_type}::decode(input)?;\n",
"let output = self.{rust_method}(input)?;\n",
"let mut out_bytes = Vec::new(); output.encode(&mut out_bytes)?; Ok(out_bytes) }}, "),
idx = idx + 1,
input_type = method.input_type,
rust_method = method.name
)
.unwrap();
}
buf.push_str(
r#"
_ => Err(crate::err::AnkiError::invalid_input("invalid command")),
}
}
"#,
);
for method in &service.methods {
write!(
buf,
concat!(
" fn {method_name}(&self, input: {input_type}) -> ",
"BackendResult<{output_type}>;\n"
),
method_name = method.name,
input_type = method.input_type,
output_type = method.output_type
)
.unwrap();
}
buf.push_str("}\n");
}
impl prost_build::ServiceGenerator for CustomGenerator {
fn generate(&mut self, service: prost_build::Service, buf: &mut String) {
write_method_enum(buf, &service);
write_method_trait(buf, &service);
}
}
fn service_generator() -> Box<dyn prost_build::ServiceGenerator> {
Box::new(CustomGenerator {})
}
fn main() -> std::io::Result<()> {
// write template.ftl
let mut buf = String::new();
let mut ftl_template_dirs = vec!["./ftl".to_string()];
if let Ok(paths) = std::env::var("FTL_TEMPLATE_DIRS") {
ftl_template_dirs.extend(paths.split(',').map(|s| s.to_string()));
}
for ftl_dir in ftl_template_dirs {
let ftl_dir = Path::new(&ftl_dir);
for entry in fs::read_dir(ftl_dir)? {
let entry = entry?;
let fname = entry.file_name().into_string().unwrap();
if !fname.ends_with(".ftl") {
continue;
}
let path = entry.path();
println!("cargo:rerun-if-changed=./ftl/{}", fname);
buf += &fs::read_to_string(path)?;
buf.push('\n');
}
}
let combined_ftl = Path::new("src/i18n/ftl/template.ftl");
fs::write(combined_ftl, &buf)?;
// generate code completion for ftl strings
let idents = get_identifiers(&buf);
let string_proto_path = Path::new("../proto/fluent.proto");
fs::write(string_proto_path, proto_enum(&idents))?;
let rust_string_path = Path::new("src/i18n/autogen.rs");
fs::write(rust_string_path, rust_string_vec(&idents))?;
// output protobuf generated code
println!("cargo:rerun-if-changed=../proto/backend.proto");
println!("cargo:rerun-if-changed=../proto/sqlite.proto");
let mut config = prost_build::Config::new();
config
// we avoid default OUT_DIR for now, as it breaks code completion
.out_dir("src")
.service_generator(service_generator())
.compile_protos(&["../proto/backend.proto", "../proto/sqlite.proto"], &["../proto"])
.unwrap();
// rustfmt the protobuf code
let rustfmt = Command::new("rustfmt")
.arg(Path::new("src/backend_proto.rs"))
.status()
.unwrap();
assert!(rustfmt.success(), "rustfmt backend_proto.rs failed");
// write the other language ftl files
let mut ftl_lang_dirs = vec!["./ftl/anki-core-i18n/core".to_string()];
if let Ok(paths) = std::env::var("FTL_LOCALE_DIRS") {
ftl_lang_dirs.extend(paths.split(',').map(|s| s.to_string()));
}
let mut langs = HashMap::new();
for ftl_dir in ftl_lang_dirs {
for ftl_dir in fs::read_dir(ftl_dir)? {
let lang_dir = ftl_dir?;
if lang_dir.file_name() == "templates" {
continue;
}
let mut buf = String::new();
let lang_name = lang_dir.file_name().into_string().unwrap();
for entry in fs::read_dir(lang_dir.path())? {
let entry = entry?;
let path = entry.path();
println!("cargo:rerun-if-changed={}", entry.path().to_string_lossy());
buf += &fs::read_to_string(path)?;
buf.push('\n');
}
langs
.entry(lang_name)
.or_insert_with(String::new)
.push_str(&buf)
}
}
for (lang, text) in langs {
fs::write(format!("src/i18n/ftl/{}.ftl", lang), text)?;
}
Ok(())
}