| 1 |
#![cfg(feature = "schemars")] |
| 2 |
|
| 3 |
use fs_err as fs; |
| 4 |
use std::path::PathBuf; |
| 5 |
|
| 6 |
use anyhow::{bail, Result}; |
| 7 |
use pretty_assertions::StrComparison; |
| 8 |
use schemars::schema_for; |
| 9 |
|
| 10 |
use crate::pyproject_toml::ToolMaturin; |
| 11 |
|
| 12 |
#[derive(Debug, Copy, Clone, PartialEq, Eq, clap::ValueEnum, Default)] |
| 13 |
/// The mode to use when generating the JSON schema. |
| 14 |
pub enum Mode { |
| 15 |
/// Write the JSON schema to the file. |
| 16 |
#[default] |
| 17 |
Write, |
| 18 |
/// Check if the JSON schema is up-to-date. |
| 19 |
Check, |
| 20 |
/// Print the JSON schema to stdout. |
| 21 |
DryRun, |
| 22 |
} |
| 23 |
|
| 24 |
/// Generate the JSON schema for the `pyproject.toml` file. |
| 25 |
#[derive(Debug, clap::Parser)] |
| 26 |
pub struct GenerateJsonSchemaOptions { |
| 27 |
/// The mode to use when generating the JSON schema. |
| 28 |
#[arg(long, default_value_t, value_enum)] |
| 29 |
pub mode: Mode, |
| 30 |
} |
| 31 |
|
| 32 |
/// Generate the JSON schema for the `pyproject.toml` file. |
| 33 |
pub fn generate_json_schema(args: GenerateJsonSchemaOptions) -> Result<()> { |
| 34 |
let schema = schema_for!(ToolMaturin); |
| 35 |
let schema_string = serde_json::to_string_pretty(&schema).unwrap(); |
| 36 |
let filename = "maturin.schema.json"; |
| 37 |
let schema_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(filename); |
| 38 |
|
| 39 |
match args.mode { |
| 40 |
Mode::DryRun => { |
| 41 |
println!("{schema_string}"); |
| 42 |
} |
| 43 |
Mode::Check => { |
| 44 |
let current = fs::read_to_string(schema_path)?; |
| 45 |
if current == schema_string { |
| 46 |
println!("Up-to-date: {filename}"); |
| 47 |
} else { |
| 48 |
let comparison = StrComparison::new(¤t, &schema_string); |
| 49 |
bail!("{filename} changed, please run `cargo run --features schemars -- generate-json-schema`:\n{comparison}",); |
| 50 |
} |
| 51 |
} |
| 52 |
Mode::Write => { |
| 53 |
let current = fs::read_to_string(&schema_path)?; |
| 54 |
if current == schema_string { |
| 55 |
println!("Up-to-date: {filename}"); |
| 56 |
} else { |
| 57 |
println!("Updating: {filename}"); |
| 58 |
fs::write(schema_path, schema_string.as_bytes())?; |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
Ok(()) |
| 64 |
} |