1
use std::env;
2
use std::fs;
3
use std::process::Command;
4

            
5
const RUSTC_WASM_ARGS: &str = "--target wasm32-unknown-unknown \
6
                               --crate-type cdylib \
7
                               --emit link \
8
                               -C embed-bitcode=no \
9
                               -C opt-level=z \
10
                               -C link-args=-zstack-size,0x1000,-zheap-size=0x1000 \
11
                               --edition 2024";
12

            
13
2
fn main() {
14
2
    let output = Command::new("git")
15
2
        .args(["rev-parse", "HEAD"])
16
2
        .output()
17
2
        .expect("Can't get git revision");
18
2
    let git_hash = String::from_utf8(output.stdout).expect("Can't parse git revision");
19
2
    println!("cargo:rustc-env=GIT_HASH={git_hash}");
20
2
    let build_date = chrono::Utc::now().to_rfc3339();
21
2
    println!("cargo:rustc-env=BUILD_DATE={build_date}");
22
2
    println!("cargo:rerun-if-changed=locales");
23
2
    println!("cargo:rerun-if-changed=testdata");
24

            
25
    // OUT_DIR, not `../target`: that hardcodes the DEFAULT target directory, so
26
    // any build with CARGO_TARGET_DIR set writes into a directory that does not
27
    // exist. The path is published as an env var for the tests that read it.
28
2
    let out_dir = env::var("OUT_DIR").expect("cargo always sets OUT_DIR for a build script");
29

            
30
2
    let buildwasm = |name: &str| {
31
2
        let output_path = format!("{out_dir}/{name}.wasm");
32
2
        println!("cargo:rustc-env=WASM_{}={output_path}", name.to_uppercase());
33
2
        let source_path = format!("testdata/{name}.rs");
34

            
35
2
        let status = Command::new("rustc")
36
2
            .args(RUSTC_WASM_ARGS.split_whitespace()) // Split the arguments string by whitespace
37
2
            .arg(&source_path)
38
2
            .arg("-o")
39
2
            .arg(&output_path)
40
2
            .status()
41
2
            .expect("Failed to build wasmscript");
42

            
43
2
        assert!(status.success(), "Building wasmscript {name} failed");
44
2
    };
45

            
46
2
    fs::read_dir("testdata")
47
2
        .unwrap_or_else(|_| fs::read_dir("").unwrap())
48
2
        .flatten()
49
10
        .filter_map(|entry| {
50
10
            let path = entry.path();
51
10
            if path.extension() == Some("rs".as_ref()) {
52
2
                path.file_stem()
53
2
                    .map(|stem| stem.to_string_lossy().into_owned())
54
            } else {
55
8
                None
56
            }
57
10
        })
58
2
        .for_each(|filename| buildwasm(&filename));
59
2
}