|
| 1 | +//! Codama IDL build script. |
| 2 | +
|
| 3 | +use { |
| 4 | + codama::Codama, |
| 5 | + codama_korok_plugins::DefaultPlugin, |
| 6 | + std::{env, fs, path::Path}, |
| 7 | +}; |
| 8 | + |
| 9 | +fn main() { |
| 10 | + // Run the build script if the source files have changed, or if the |
| 11 | + // developer provides the GENERATE_IDL environment variable. |
| 12 | + // |
| 13 | + // ``` |
| 14 | + // `GENERATE_IDL=1 cargo build` |
| 15 | + // ``` |
| 16 | + // |
| 17 | + // The environment variable approach is useful if the local Codama has been |
| 18 | + // updated. |
| 19 | + println!("cargo:rerun-if-changed=src/"); |
| 20 | + println!("cargo:rerun-if-env-changed=GENERATE_IDL"); |
| 21 | + |
| 22 | + if let Err(e) = generate_idl() { |
| 23 | + println!("cargo:warning=Failed to generate IDL: {}", e); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +fn generate_idl() -> Result<(), Box<dyn std::error::Error>> { |
| 28 | + let manifest_dir = env::var("CARGO_MANIFEST_DIR")?; |
| 29 | + let crate_path = Path::new(&manifest_dir); |
| 30 | + |
| 31 | + let codama = Codama::load(crate_path)? |
| 32 | + .without_default_plugin() |
| 33 | + .add_plugin(DefaultPlugin); // Standard parsing |
| 34 | + |
| 35 | + let idl_json = codama.get_json_idl()?; |
| 36 | + |
| 37 | + // Parse and format the JSON with pretty printing. |
| 38 | + let parsed: serde_json::Value = serde_json::from_str(&idl_json)?; |
| 39 | + let mut formatted_json = serde_json::to_string_pretty(&parsed)?; |
| 40 | + |
| 41 | + // Add newline at the end to match standard formatting. |
| 42 | + formatted_json.push('\n'); |
| 43 | + |
| 44 | + // Define output directory |
| 45 | + let out_dir = Path::new(&manifest_dir).join("idl"); |
| 46 | + fs::create_dir_all(&out_dir)?; |
| 47 | + |
| 48 | + // Write to `spl_record.json` |
| 49 | + let idl_path = out_dir.join("spl_record.json"); |
| 50 | + fs::write(&idl_path, formatted_json)?; |
| 51 | + |
| 52 | + println!("cargo:warning=IDL written to: {}", idl_path.display()); |
| 53 | + |
| 54 | + Ok(()) |
| 55 | +} |
0 commit comments