-
Notifications
You must be signed in to change notification settings - Fork 208
/
build.rs
235 lines (202 loc) · 6.92 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
use gdnative_bindings_generator::*;
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write as _};
use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
let just_generated_api = generate_api_if_needed();
let api_data = std::fs::read_to_string("api.json").expect("Unable to read api.json");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
let generated_rs = out_path.join("generated.rs");
let icalls_rs = out_path.join("icalls.rs");
let api = Api::new(&api_data);
let docs = GodotXmlDocs::new("docs");
let binding_res = generate_bindings(&api, Some(&docs));
{
let mut output = BufWriter::new(File::create(&generated_rs).unwrap());
generate(&out_path, &mut output, &binding_res);
}
{
let mut output = BufWriter::new(File::create(&icalls_rs).unwrap());
write!(&mut output, "{}", binding_res.icalls).unwrap();
}
if cfg!(feature = "formatted") {
format_file(&generated_rs);
format_file(&icalls_rs);
}
// build.rs will automatically be recompiled and run if it's dependencies are updated.
// Ignoring all but build.rs will keep from needless rebuilds.
// Manually rebuilding the crate will ignore this.
println!("cargo:rerun-if-changed=docs/");
println!("cargo:rerun-if-changed=build.rs");
// Avoid endless recompiling, if this script generates api.json
if !just_generated_api {
println!("cargo:rerun-if-changed=api.json");
}
}
/// Output all the class bindings into the `generated.rs` file.
#[cfg(not(feature = "one-class-one-file"))]
fn generate(
_out_path: &std::path::Path,
generated_file: &mut BufWriter<File>,
binding_res: &BindingResult,
) {
// Note: 'use super::*;' needs to be after content, as the latter may contain #![doc] attributes,
// which need to be at the beginning of the module
for (class, code) in &binding_res.class_bindings {
let modifier = if class.has_related_module() {
"pub"
} else {
"pub(crate)"
};
write!(
generated_file,
r#"
{modifier} mod {mod_name} {{
{content}
use super::*;
}}
pub use crate::generated::{mod_name}::private::{class_name};
"#,
modifier = modifier,
mod_name = module_name_from_class_name(&class.name),
class_name = class.name,
content = code,
)
.unwrap();
}
}
/// Output one file for each class and add `mod` and `use` declarations in
/// the `generated.rs` file.
#[cfg(feature = "one-class-one-file")]
fn generate(
out_path: &std::path::Path,
generated_file: &mut BufWriter<File>,
binding_res: &BindingResult,
) {
for (class, code) in &binding_res.class_bindings {
let mod_name = module_name_from_class_name(&class.name);
let mod_path = out_path.join(format!("{}.rs", mod_name));
let mut mod_output = BufWriter::new(File::create(&mod_path).unwrap());
write!(
&mut mod_output,
r#"
{content}
use super::*;
"#,
content = code,
)
.unwrap();
drop(mod_output);
if cfg!(feature = "formatted") {
format_file(&mod_path);
}
let modifier = if class.has_related_module() {
"pub"
} else {
"pub(crate)"
};
writeln!(
generated_file,
r#"
#[path = {:?}]
{modifier} mod {mod_name};
pub use crate::generated::{mod_name}::private::{class_name};
"#,
mod_path.display(),
modifier = modifier,
mod_name = mod_name,
class_name = class.name,
)
.unwrap();
}
}
fn format_file(output_rs: &Path) {
print!(
"Formatting generated file: {}... ",
output_rs.file_name().and_then(|s| s.to_str()).unwrap()
);
match Command::new("rustup")
.arg("run")
.arg("stable")
.arg("rustfmt")
.arg("--edition=2018")
.arg(output_rs)
.output()
{
Ok(_) => println!("Done"),
Err(err) => {
println!("Failed");
println!("Error: {}", err);
}
}
}
#[cfg(not(feature = "custom-godot"))]
fn generate_api_if_needed() -> bool {
false
}
#[cfg(feature = "custom-godot")]
fn generate_api_if_needed() -> bool {
let godot_bin: PathBuf = if let Ok(string) = env::var("GODOT_BIN") {
println!("Found GODOT_BIN with path to executable: '{}'", string);
PathBuf::from(string)
} else if let Ok(path) = which::which("godot") {
println!("Found 'godot' executable in PATH: {}", path.display());
path
} else {
panic!(
"Feature 'custom-godot' requires an accessible 'godot' executable or \
a GODOT_BIN environment variable (with the path to the executable)."
);
};
let version = exec(1, Command::new(&godot_bin).arg("--version"));
let has_generate_bug = match godot_version::parse_version(&version) {
Ok(parsed) => {
assert!(
parsed.major == 3 && parsed.minor >= 2,
"Only Godot versions >= 3.2 and < 4.0 are supported."
);
// bug for versions < 3.3.1
parsed.major == 2 || parsed.major == 3 && parsed.minor == 0
}
Err(e) => {
// Don't treat this as fatal error
eprintln!("Warning, failed to parse version: {}", e);
true // version not known, conservatively assume bug
}
};
// Workaround for Godot bug, where the generate command crashes the engine.
// Try 10 times (should be reasonably high confidence that at least 1 run succeeds).
println!("Found Godot version < 3.3.1 with potential generate bug; trying multiple times...");
exec(
if has_generate_bug { 10 } else { 1 },
Command::new(&godot_bin)
.arg("--gdnative-generate-json-api")
.arg("api.json"),
);
true
}
/// Executes a command and returns stdout. Panics on failure.
#[cfg(feature = "custom-godot")]
fn exec(attempts: i32, command: &mut Command) -> String {
let command_line = format!("{:?}", command);
for _attempt in 0..attempts {
match command.output() {
Ok(output) => return String::from_utf8(output.stdout).expect("parse UTF8 string"),
Err(err) => {
eprintln!(
"Godot command failed:\n command: {}\n error: {}",
command_line, err
)
}
}
}
panic!("Could not execute Godot command (see above).")
}
#[cfg(feature = "custom-godot")]
#[allow(unused_variables, dead_code)]
mod godot_version {
// Not very nice, but there's no idiomatic approach to split build.rs, and #[path] freezes build.rs
include!("src/godot_version.rs");
}