cosmwasm_schema/
export.rs

1//! Export schema to file
2
3use std::fs::write;
4use std::path::Path;
5
6use schemars::schema::RootSchema;
7
8use crate::casing::to_snake_case;
9
10/// Exports a schema, auto-generating filename based on the metadata title of the generated schema.
11pub fn export_schema(schema: &RootSchema, out_dir: &Path) {
12    let title = schema
13        .schema
14        .metadata
15        .as_ref()
16        .map(|b| b.title.clone().unwrap_or_else(|| "untitled".to_string()))
17        .unwrap_or_else(|| "unknown".to_string());
18    write_schema(schema, out_dir, &title);
19}
20
21/// Use this if you want to override the auto-detected name of the object.
22/// very useful when creating an alias for a type-alias.
23pub fn export_schema_with_title(schema: &RootSchema, out_dir: &Path, title: &str) {
24    let mut schema = schema.clone();
25    // set the title explicitly on the schema's metadata
26    if let Some(metadata) = &mut schema.schema.metadata {
27        metadata.title = Some(title.to_string());
28    }
29    write_schema(&schema, out_dir, title);
30}
31
32/// Writes schema to file. Overwrites existing file.
33/// Panics on any error writing out the schema.
34fn write_schema(schema: &RootSchema, out_dir: &Path, title: &str) {
35    // first, we set the title as we wish
36    let path = out_dir.join(format!("{}.json", to_snake_case(title)));
37    let json = serde_json::to_string_pretty(schema).unwrap();
38    write(&path, json + "\n").unwrap();
39    println!("Created {}", path.to_str().unwrap());
40}