Skip to content

Commit 1d409cd

Browse files
committed
add idl build script
1 parent 8141a43 commit 1d409cd

4 files changed

Lines changed: 190 additions & 128 deletions

File tree

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

program/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ solana-system-interface = "2"
3434
solana-transaction = "3.0.0"
3535
solana-transaction-error = "3.0.0"
3636

37+
[build-dependencies]
38+
codama = "0.6.4"
39+
codama-korok-plugins = "0.6.4"
40+
serde_json = "1.0"
41+
3742
[lib]
3843
crate-type = ["cdylib", "lib"]
3944

program/build.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)