-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
403 lines (340 loc) · 12.1 KB
/
build.rs
File metadata and controls
403 lines (340 loc) · 12.1 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Build script for Goldy.
//!
//! Embeds Slang compiler binaries into the library using include_bytes!.
//! Downloads Slang if vendored binaries are not present.
//! Reads from slang/manifest.json for version and file lists.
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Slang manifest structure (subset we need)
#[derive(Debug)]
struct SlangManifest {
version: String,
platforms: std::collections::HashMap<String, PlatformInfo>,
}
#[derive(Debug)]
struct PlatformInfo {
files: Vec<String>,
primary: String,
}
fn main() {
println!("cargo:rerun-if-env-changed=GOLDY_SLANG_PATH");
println!("cargo:rerun-if-changed=slang/manifest.json");
// Load manifest
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let manifest_path = manifest_dir.join("slang").join("manifest.json");
let manifest = match load_manifest(&manifest_path) {
Ok(m) => m,
Err(e) => {
println!("cargo:warning=Failed to load slang/manifest.json: {}", e);
generate_empty_embedded_module();
return;
}
};
let platform_dir = get_platform_dir();
let platform_info = match manifest.platforms.get(platform_dir) {
Some(info) => info,
None => {
println!("cargo:warning=Platform {} not in manifest", platform_dir);
generate_empty_embedded_module();
return;
}
};
// Check vendored binaries directory
let vendored_dir = manifest_dir.join("slang").join("bin").join(platform_dir);
// Mark all vendored files as dependencies for rebuild
for file in &platform_info.files {
let file_path = vendored_dir.join(file);
println!("cargo:rerun-if-changed={}", file_path.display());
}
// If vendored binaries don't exist, try to download them
if !vendored_dir.join(&platform_info.primary).exists() {
println!(
"cargo:warning=Vendored Slang binaries not found at {}",
vendored_dir.display()
);
println!(
"cargo:warning=Downloading Slang v{} for {}...",
manifest.version, platform_dir
);
if let Err(e) = download_slang_to_vendored(
&vendored_dir,
platform_dir,
&manifest.version,
&platform_info.files,
) {
println!("cargo:warning=Failed to download Slang: {}", e);
println!("cargo:warning=Run: cd slang && ./download.sh");
generate_empty_embedded_module();
return;
}
}
// Generate the embedded module
generate_embedded_module(&manifest.version, &vendored_dir, platform_info);
}
/// Generate an empty embedded module (for unsupported platforms or missing binaries)
fn generate_empty_embedded_module() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let embedded_path = out_dir.join("slang_embedded.rs");
let content = r#"// Auto-generated: Slang binaries not available for this platform.
/// Slang version (empty - not available)
pub const SLANG_VERSION: &str = "";
/// Embedded Slang library files (empty - not available)
pub const SLANG_FILES: &[(&str, &[u8])] = &[];
/// Primary library name (empty - not available)
pub const SLANG_PRIMARY: &str = "";
"#;
fs::write(&embedded_path, content).expect("Failed to write slang_embedded.rs");
}
/// Generate the embedded module with include_bytes! for all Slang files
fn generate_embedded_module(version: &str, vendored_dir: &Path, platform_info: &PlatformInfo) {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let embedded_path = out_dir.join("slang_embedded.rs");
let mut content = String::new();
content.push_str("// Auto-generated: Embedded Slang compiler binaries.\n");
content.push_str("// Do not edit manually - regenerated by build.rs\n\n");
// Version constant
content.push_str(&format!(
"/// Slang version embedded in this build\n\
pub const SLANG_VERSION: &str = \"{}\";\n\n",
version
));
// Primary library name
content.push_str(&format!(
"/// Primary Slang library filename\n\
pub const SLANG_PRIMARY: &str = \"{}\";\n\n",
platform_info.primary
));
// Embedded files array
content.push_str("/// Embedded Slang library files (filename, bytes)\n");
content.push_str("pub const SLANG_FILES: &[(&str, &[u8])] = &[\n");
for file in &platform_info.files {
let file_path = vendored_dir.join(file);
if file_path.exists() {
// Use absolute path for include_bytes!
let abs_path = file_path
.canonicalize()
.unwrap_or_else(|_| file_path.clone());
// On Windows, canonicalize adds \\?\ prefix, which we need to handle
let path_str = abs_path.display().to_string();
let path_str = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
// Escape backslashes for the string literal
let escaped_path = path_str.replace('\\', "/");
content.push_str(&format!(
" (\"{}\", include_bytes!(\"{}\")),\n",
file, escaped_path
));
} else {
println!(
"cargo:warning=Slang file not found: {}",
file_path.display()
);
}
}
content.push_str("];\n");
fs::write(&embedded_path, content).expect("Failed to write slang_embedded.rs");
println!(
"cargo:warning=Generated slang_embedded.rs with {} files",
platform_info.files.len()
);
}
fn load_manifest(path: &Path) -> io::Result<SlangManifest> {
let content = fs::read_to_string(path)?;
// Simple JSON parsing without serde (to avoid build dependency)
let version = extract_json_string(&content, "version")
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version"))?;
let mut platforms = std::collections::HashMap::new();
for platform in &[
"windows-x86_64",
"linux-x86_64",
"linux-aarch64",
"macos-x86_64",
"macos-aarch64",
] {
if let Some(info) = extract_platform_info(&content, platform) {
platforms.insert(platform.to_string(), info);
}
}
Ok(SlangManifest { version, platforms })
}
fn extract_json_string(json: &str, key: &str) -> Option<String> {
let pattern = format!("\"{}\"", key);
let start = json.find(&pattern)?;
let after_key = &json[start + pattern.len()..];
let colon = after_key.find(':')?;
let after_colon = &after_key[colon + 1..];
let quote_start = after_colon.find('"')?;
let value_start = &after_colon[quote_start + 1..];
let quote_end = value_start.find('"')?;
Some(value_start[..quote_end].to_string())
}
fn extract_platform_info(json: &str, platform: &str) -> Option<PlatformInfo> {
let pattern = format!("\"{}\"", platform);
let start = json.find(&pattern)?;
let section = &json[start..];
let files_start = section.find("\"files\"")?;
let after_files = §ion[files_start..];
let array_start = after_files.find('[')?;
let array_end = after_files.find(']')?;
let array_content = &after_files[array_start + 1..array_end];
let files: Vec<String> = array_content
.split(',')
.filter_map(|s| {
let s = s.trim();
if s.starts_with('"') && s.ends_with('"') {
Some(s[1..s.len() - 1].to_string())
} else {
None
}
})
.collect();
let primary = extract_json_string(section, "primary")?;
Some(PlatformInfo { files, primary })
}
fn get_platform_dir() -> &'static str {
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
{
"windows-x86_64"
}
#[cfg(all(target_os = "windows", target_arch = "aarch64"))]
{
"windows-aarch64"
}
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
{
"linux-x86_64"
}
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
{
"linux-aarch64"
}
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
"macos-x86_64"
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
"macos-aarch64"
}
#[cfg(not(any(
all(target_os = "windows", target_arch = "x86_64"),
all(target_os = "windows", target_arch = "aarch64"),
all(target_os = "linux", target_arch = "x86_64"),
all(target_os = "linux", target_arch = "aarch64"),
all(target_os = "macos", target_arch = "x86_64"),
all(target_os = "macos", target_arch = "aarch64"),
)))]
compile_error!("Unsupported platform for Slang")
}
/// Download Slang binaries directly to the vendored directory
fn download_slang_to_vendored(
vendored_dir: &Path,
platform_dir: &str,
version: &str,
required_files: &[String],
) -> io::Result<()> {
fs::create_dir_all(vendored_dir)?;
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let zip_name = format!("slang-{}-{}.zip", version, platform_dir);
let url = format!(
"https://github.com/shader-slang/slang/releases/download/v{}/{}",
version, zip_name
);
let zip_path = out_dir.join(&zip_name);
// Download using curl
let status = std::process::Command::new("curl")
.args(["-fsSL", "-o"])
.arg(&zip_path)
.arg(&url)
.status()?;
if !status.success() {
return Err(io::Error::other(format!(
"curl download failed for {}",
url
)));
}
// Create temp extraction directory
let extract_dir = out_dir.join("slang_extract");
let _ = fs::remove_dir_all(&extract_dir);
fs::create_dir_all(&extract_dir)?;
// Extract using platform tools
#[cfg(target_os = "windows")]
{
let status = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
&format!(
"Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
zip_path.display(),
extract_dir.display()
),
])
.status()?;
if !status.success() {
return Err(io::Error::other("PowerShell extract failed"));
}
}
#[cfg(not(target_os = "windows"))]
{
let status = std::process::Command::new("unzip")
.args(["-o", "-q"])
.arg(&zip_path)
.arg("-d")
.arg(&extract_dir)
.status()?;
if !status.success() {
return Err(io::Error::other("unzip failed"));
}
}
// Find and copy all required files to vendored directory
let mut copied = 0;
for file_name in required_files {
if let Some(src_path) = find_file_recursive(&extract_dir, file_name) {
let dest = vendored_dir.join(file_name);
fs::copy(&src_path, &dest)?;
copied += 1;
} else {
println!(
"cargo:warning=Slang file not found in archive: {}",
file_name
);
}
}
if copied == 0 {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"No Slang libraries found in downloaded archive",
));
}
println!(
"cargo:warning=Downloaded {}/{} Slang libraries to {}",
copied,
required_files.len(),
vendored_dir.display()
);
// Cleanup
let _ = fs::remove_file(&zip_path);
let _ = fs::remove_dir_all(&extract_dir);
Ok(())
}
fn find_file_recursive(dir: &Path, name: &str) -> Option<PathBuf> {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.filter_map(|e| e.ok()) {
let path = entry.path();
if path.is_file() {
if let Some(file_name) = path.file_name() {
if file_name.to_string_lossy() == name {
return Some(path);
}
}
} else if path.is_dir() {
if let Some(found) = find_file_recursive(&path, name) {
return Some(found);
}
}
}
}
None
}