use std::convert::Infallible;
use clap::{Arg, Command};
use clap_schema::{ContractBuilder, schema_handler};
use schemars::JsonSchema;
use serde::Serialize;
#[derive(Debug, Serialize, JsonSchema)]
struct Widget {
id: u64,
name: String,
}
struct CreateCommand;
#[schema_handler(CreateCommand)]
fn create(_command: CreateCommand) -> Result<Widget, Infallible> {
Ok(Widget { id: 1, name: "example".to_owned() })
}
fn cli() -> Command {
Command::new("widgetctl").subcommand(
Command::new("create")
.about("Create a widget")
.arg(Arg::new("name").long("name").required(true)),
)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let contract = ContractBuilder::new(cli()).command::<CreateCommand>(["create"]).build()?;
let command = contract.command_for::<CreateCommand>().expect("create command is registered");
println!("Builder-derived command contract:");
println!("{}", serde_json::to_string_pretty(&command)?);
let created = create(CreateCommand)?;
println!("\nRuntime value from the same handler:");
println!("{}", serde_json::to_string_pretty(&created)?);
Ok(())
}