generated from emilk/eframe_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
90 lines (75 loc) · 2.82 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
use std::env;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
/// Build script to include any wasm component binaries in the build.
///
/// Add builtin_components.rs to your lib.rs or main.rs:
///
/// # Example
///
/// ```ignore
/// include!(concat!(env!("OUT_DIR"), "/builtin_components.rs"));
/// ```
fn main() {
eprintln!("Running build.rs");
let out_dir = env::var_os("OUT_DIR").unwrap_or_default();
let dest_path = Path::new(&out_dir).join("builtin_components.rs");
let target = "wasm32-unknown-unknown";
// always use the release build, it's so much smaller and faster
let dir_path = format!("target/{}/release", target);
let project_root = std::env::current_dir().expect("Failed to get current directory");
eprintln!(
"Looking for wasm files in {}",
project_root.join(&dir_path).display()
);
let mut code = "pub static BUILTIN_PLUGINS: [(&str, &[u8]); 0] = [];".to_string();
if let Ok(dir) = std::fs::read_dir(project_root.join(dir_path)) {
let this_root_crate = env::var("CARGO_PKG_NAME").unwrap_or_default();
let file_paths: Vec<PathBuf> = dir
.filter_map(|entry| {
let path = entry.ok()?.path();
path.extension()
// filter on 1) wasm files only, 2) not named the same as root crate
.filter(|&ext| {
let Some(bytes) = fs::read(&path).ok() else {
return false;
};
ext == "wasm"
&& *path.file_stem().unwrap() != *this_root_crate
&& wasmparser::Parser::is_component(&bytes)
})
.map(|_| path.to_path_buf())
})
.collect();
let count = file_paths.len();
if count == 0 {
return;
}
code = format!("pub static BUILTIN_PLUGINS: [(&str, &[u8]); {count}] = [");
for path in file_paths.iter() {
let name = path
.file_name()
.unwrap_or_else(|| path.as_os_str())
.to_str()
.unwrap_or_else(|| path.as_os_str().to_str().unwrap_or_default());
code.push_str(&format!(
"(\"{name}\", include_bytes!(\"{}\")),",
path.to_string_lossy()
));
}
code.push_str("];");
println!("cargo:rerun-if-changed=build.rs");
for path in file_paths.iter() {
println!(
"cargo:rerun-if-changed={}",
path.to_str().unwrap_or_default()
);
}
};
if let Err(e) = fs::write(&dest_path, code) {
eprintln!("Failed to write to {}: {}", dest_path.display(), e);
} else {
eprintln!("Wrote {}", dest_path.display());
}
}