build.rs

 1use std::env;
 2use std::fs;
 3use std::path::PathBuf;
 4
 5fn main() -> Result<(), Box<dyn std::error::Error>> {
 6    copy_extension_api_rust_files()
 7}
 8
 9// rust-analyzer doesn't support include! for files from outside the crate.
10// Copy them to the OUT_DIR, so we can include them from there, which is supported.
11fn copy_extension_api_rust_files() -> Result<(), Box<dyn std::error::Error>> {
12    let out_dir = env::var("OUT_DIR")?;
13    let input_dir = PathBuf::from("../extension_api/wit");
14    let output_dir = PathBuf::from(out_dir);
15
16    for entry in fs::read_dir(&input_dir)? {
17        let entry = entry?;
18        let path = entry.path();
19        if path.is_dir() {
20            for subentry in fs::read_dir(&path)? {
21                let subentry = subentry?;
22                let subpath = subentry.path();
23                if subpath.extension() == Some(std::ffi::OsStr::new("rs")) {
24                    let relative_path = subpath.strip_prefix(&input_dir)?;
25                    let destination = output_dir.join(relative_path);
26
27                    fs::create_dir_all(destination.parent().unwrap())?;
28                    fs::copy(&subpath, &destination)?;
29                    println!("cargo:rerun-if-changed={}", subpath.display());
30                }
31            }
32        } else if path.extension() == Some(std::ffi::OsStr::new("rs")) {
33            let relative_path = path.strip_prefix(&input_dir)?;
34            let destination = output_dir.join(relative_path);
35
36            fs::create_dir_all(destination.parent().unwrap())?;
37            fs::copy(&path, &destination)?;
38            println!("cargo:rerun-if-changed={}", path.display());
39        }
40    }
41
42    Ok(())
43}