1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
// Copyright 2023 Oxide Computer Company
use std::collections::BTreeMap;
use heck::ToKebabCase;
use openapiv3::OpenAPI;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use typify::{Type, TypeEnumVariant, TypeSpaceImpl, TypeStructPropInfo};
use crate::{
method::{
OperationParameterKind, OperationParameterType, OperationResponseStatus,
},
to_schema::ToSchema,
util::{sanitize, Case},
validate_openapi, Generator, Result,
};
struct CliOperation {
cli_fn: TokenStream,
execute_fn: TokenStream,
execute_trait: TokenStream,
}
impl Generator {
/// Generate a `clap`-based CLI.
pub fn cli(
&mut self,
spec: &OpenAPI,
crate_name: &str,
) -> Result<TokenStream> {
validate_openapi(spec)?;
// Convert our components dictionary to schemars
let schemas = spec.components.iter().flat_map(|components| {
components.schemas.iter().map(|(name, ref_or_schema)| {
(name.clone(), ref_or_schema.to_schema())
})
});
self.type_space.add_ref_types(schemas)?;
let raw_methods = spec
.paths
.iter()
.flat_map(|(path, ref_or_item)| {
// Exclude externally defined path items.
let item = ref_or_item.as_item().unwrap();
item.iter().map(move |(method, operation)| {
(path.as_str(), method, operation, &item.parameters)
})
})
.map(|(path, method, operation, path_parameters)| {
self.process_operation(
operation,
&spec.components,
path,
method,
path_parameters,
)
})
.collect::<Result<Vec<_>>>()?;
let methods = raw_methods
.iter()
.map(|method| self.cli_method(method))
.collect::<Vec<_>>();
let cli_ops = methods.iter().map(|op| &op.cli_fn);
let execute_ops = methods.iter().map(|op| &op.execute_fn);
let trait_ops = methods.iter().map(|op| &op.execute_trait);
let cli_fns = raw_methods
.iter()
.map(|method| {
format_ident!(
"cli_{}",
sanitize(&method.operation_id, Case::Snake)
)
})
.collect::<Vec<_>>();
let execute_fns = raw_methods
.iter()
.map(|method| {
format_ident!(
"execute_{}",
sanitize(&method.operation_id, Case::Snake)
)
})
.collect::<Vec<_>>();
let cli_variants = raw_methods
.iter()
.map(|method| {
format_ident!(
"{}",
sanitize(&method.operation_id, Case::Pascal)
)
})
.collect::<Vec<_>>();
let crate_ident = format_ident!("{}", crate_name);
let code = quote! {
pub struct Cli<T: CliOverride = ()> {
client: #crate_ident::Client,
over: T,
}
impl Cli {
pub fn new(client: #crate_ident::Client) -> Self {
Self { client, over: () }
}
pub fn get_command(cmd: CliCommand) -> clap::Command {
match cmd {
#(
CliCommand::#cli_variants => Self::#cli_fns(),
)*
}
}
#(#cli_ops)*
}
impl<T: CliOverride> Cli<T> {
pub fn new_with_override(
client: #crate_ident::Client,
over: T,
) -> Self {
Self { client, over }
}
pub async fn execute(
&self,
cmd: CliCommand,
matches: &clap::ArgMatches,
) {
match cmd {
#(
CliCommand::#cli_variants => {
// TODO ... do something with output
self.#execute_fns(matches).await;
}
)*
}
}
#(#execute_ops)*
}
pub trait CliOverride {
#(#trait_ops)*
}
impl CliOverride for () {}
#[derive(Copy, Clone, Debug)]
pub enum CliCommand {
#(#cli_variants,)*
}
impl CliCommand {
pub fn iter() -> impl Iterator<Item = CliCommand> {
vec![
#(
CliCommand::#cli_variants,
)*
].into_iter()
}
}
};
Ok(code)
}
fn cli_method(
&mut self,
method: &crate::method::OperationMethod,
) -> CliOperation {
let CliArg {
parser: parser_args,
consumer: consumer_args,
} = self.cli_method_args(method);
let about = method.summary.as_ref().map(|summary| {
quote! {
.about(#summary)
}
});
let long_about = method.description.as_ref().map(|description| {
quote! {
.long_about(#description)
}
});
let fn_name = format_ident!("cli_{}", &method.operation_id);
let cli_fn = quote! {
pub fn #fn_name() -> clap::Command
{
clap::Command::new("")
#parser_args
#about
#long_about
}
};
let fn_name = format_ident!("execute_{}", &method.operation_id);
let op_name = format_ident!("{}", &method.operation_id);
let (_, success_type) = self.extract_responses(
method,
OperationResponseStatus::is_success_or_default,
);
let (_, error_type) = self.extract_responses(
method,
OperationResponseStatus::is_error_or_default,
);
let success_output = match success_type {
crate::method::OperationResponseType::Type(_) => {
quote! { println!("success\n{:#?}", r) }
}
crate::method::OperationResponseType::None => {
quote! { println!("success\n{:#?}", r) }
}
crate::method::OperationResponseType::Raw => quote! { todo!() },
crate::method::OperationResponseType::Upgrade => quote! { todo!() },
};
let error_output = match error_type {
crate::method::OperationResponseType::Type(_) => {
quote! { println!("error\n{:#?}", r) }
}
crate::method::OperationResponseType::None => {
quote! { println!("success\n{:#?}", r) }
}
crate::method::OperationResponseType::Raw => quote! { todo!() },
crate::method::OperationResponseType::Upgrade => quote! { todo!() },
};
let execute_and_output = match method.dropshot_paginated {
None => {
quote! {
let result = request.send().await;
match result {
Ok(r) => {
#success_output
}
Err(r) => {
#error_output
}
}
}
}
Some(_) => {
quote! {
let mut stream = request.stream();
loop {
match futures::TryStreamExt::try_next(&mut stream).await {
Err(r) => {
#error_output;
break;
}
Ok(None) => {
break;
}
Ok(Some(value)) => {
println!("{:#?}", value);
}
}
}
}
}
};
let execute_fn = quote! {
pub async fn #fn_name(&self, matches: &clap::ArgMatches)
// ->
// Result<ResponseValue<#success_type>, Error<#error_type>>
{
let mut request = self.client.#op_name();
#consumer_args
// Call the override function.
// TODO don't want to unwrap.
self.over
.#fn_name(matches, &mut request)
.unwrap();
#execute_and_output
}
};
// TODO this is copy-pasted--unwisely?
let struct_name = sanitize(&method.operation_id, Case::Pascal);
let struct_ident = format_ident!("{}", struct_name);
let execute_trait = quote! {
fn #fn_name(
&self,
matches: &clap::ArgMatches,
request: &mut builder :: #struct_ident,
) -> Result<(), String> {
Ok(())
}
};
CliOperation {
cli_fn,
execute_fn,
execute_trait,
}
}
fn cli_method_args(
&self,
method: &crate::method::OperationMethod,
) -> CliArg {
let mut args = CliOperationArgs::default();
let first_page_required_set = method
.dropshot_paginated
.as_ref()
.map(|d| &d.first_page_params);
for param in &method.params {
let innately_required = match ¶m.kind {
// We're not interetested in the body parameter yet.
OperationParameterKind::Body(_) => continue,
OperationParameterKind::Path => true,
OperationParameterKind::Query(required) => *required,
OperationParameterKind::Header(required) => *required,
};
// For paginated endpoints, we don't generate 'page_token' args.
if method.dropshot_paginated.is_some()
&& param.name.as_str() == "page_token"
{
continue;
}
let first_page_required = first_page_required_set
.map_or(false, |required| required.contains(¶m.api_name));
let volitionality = if innately_required || first_page_required {
Volitionality::Required
} else {
Volitionality::Optional
};
let OperationParameterType::Type(arg_type_id) = ¶m.typ else {
unreachable!("query and path parameters must be typed")
};
let arg_type = self.type_space.get_type(arg_type_id).unwrap();
let arg_name = param.name.to_kebab_case();
// There should be no conflicting path or query parameters.
assert!(!args.has_arg(&arg_name));
let parser = clap_arg(
&arg_name,
volitionality,
¶m.description,
&arg_type,
);
let arg_fn_name = sanitize(¶m.name, Case::Snake);
let arg_fn = format_ident!("{}", arg_fn_name);
let OperationParameterType::Type(arg_type_id) = ¶m.typ else {
panic!()
};
let arg_type = self.type_space.get_type(arg_type_id).unwrap();
let arg_type_name = arg_type.ident();
let consumer = quote! {
if let Some(value) =
matches.get_one::<#arg_type_name>(#arg_name)
{
// clone here in case the arg type doesn't impl
// From<&T>
request = request.#arg_fn(value.clone());
}
};
args.add_arg(arg_name, CliArg { parser, consumer })
}
let maybe_body_type_id = method
.params
.iter()
.find(|param| {
matches!(¶m.kind, OperationParameterKind::Body(_))
})
.and_then(|param| match ¶m.typ {
// TODO not sure how to deal with raw bodies, but we definitely
// need **some** input so we shouldn't just ignore it... as we
// are currently...
OperationParameterType::RawBody => None,
OperationParameterType::Type(body_type_id) => {
Some(body_type_id)
}
});
if let Some(body_type_id) = maybe_body_type_id {
args.body_present();
let body_type = self.type_space.get_type(body_type_id).unwrap();
let details = body_type.details();
match details {
typify::TypeDetails::Struct(struct_info) => {
for prop_info in struct_info.properties_info() {
self.cli_method_body_arg(&mut args, prop_info)
}
}
_ => {
// If the body is not a struct, we don't know what's
// required or how to generate it
args.body_required()
}
}
}
let parser_args =
args.args.values().map(|CliArg { parser, .. }| parser);
// TODO do this as args we add in.
let body_json_args = (match args.body {
CliBodyArg::None => None,
CliBodyArg::Required => Some(true),
CliBodyArg::Optional => Some(false),
})
.map(|required| {
let help = "Path to a file that contains the full json body.";
quote! {
.arg(
clap::Arg::new("json-body")
.long("json-body")
.value_name("JSON-FILE")
// Required if we can't turn the body into individual
// parameters.
.required(#required)
.value_parser(clap::value_parser!(std::path::PathBuf))
.help(#help)
)
.arg(
clap::Arg::new("json-body-template")
.long("json-body-template")
.action(clap::ArgAction::SetTrue)
.help("XXX")
)
}
});
let parser = quote! {
#(
.arg(#parser_args)
)*
#body_json_args
};
let consumer_args =
args.args.values().map(|CliArg { consumer, .. }| consumer);
let body_json_consumer = maybe_body_type_id.map(|body_type_id| {
let body_type = self.type_space.get_type(body_type_id).unwrap();
let body_type_ident = body_type.ident();
quote! {
if let Some(value) =
matches.get_one::<std::path::PathBuf>("json-body")
{
let body_txt = std::fs::read_to_string(value).unwrap();
let body_value =
serde_json::from_str::<#body_type_ident>(
&body_txt,
)
.unwrap();
request = request.body(body_value);
}
}
});
let consumer = quote! {
#(
#consumer_args
)*
#body_json_consumer
};
CliArg { parser, consumer }
}
fn cli_method_body_arg(
&self,
args: &mut CliOperationArgs,
prop_info: TypeStructPropInfo<'_>,
) {
let TypeStructPropInfo {
name,
description,
required,
type_id,
} = prop_info;
let prop_type = self.type_space.get_type(&type_id).unwrap();
// TODO this is maybe a kludge--not completely sure of the right way to
// handle option types. On one hand, we could want types from this
// interface to never show us Option<T> types--we could let the
// `required` field give us that information. On the other hand, there
// might be Option types that are required ... at least in the JSON
// sense, meaning that we need to include `"foo": null` rather than
// omitting the field. Back to the first hand: is that last point just
// a serde issue rather than an interface one?
let maybe_inner_type =
if let typify::TypeDetails::Option(inner_type_id) =
prop_type.details()
{
let inner_type =
self.type_space.get_type(&inner_type_id).unwrap();
Some(inner_type)
} else {
None
};
let prop_type = if let Some(inner_type) = maybe_inner_type {
inner_type
} else {
prop_type
};
let scalar = prop_type.has_impl(TypeSpaceImpl::FromStr);
if scalar {
let volitionality = if required {
Volitionality::RequiredIfNoBody
} else {
Volitionality::Optional
};
let prop_name = name.to_kebab_case();
let parser = clap_arg(
&prop_name,
volitionality,
&description.map(str::to_string),
&prop_type,
);
let prop_fn = format_ident!("{}", sanitize(name, Case::Snake));
let prop_type_ident = prop_type.ident();
let consumer = quote! {
if let Some(value) =
matches.get_one::<#prop_type_ident>(
#prop_name,
)
{
// clone here in case the arg type
// doesn't impl TryFrom<&T>
request = request.body_map(|body| {
body.#prop_fn(value.clone())
})
}
};
args.add_arg(prop_name, CliArg { parser, consumer })
} else if required {
args.body_required()
}
// Cases
// 1. If the type can be represented as a string, great
//
// 2. If it's a substruct then we can try to glue the names together
// and hope?
//
// 3. enums
// 3.1 simple enums (should be covered by 1 above)
// e.g. enum { A, B }
// args for --a and --b that are in a group
}
}
enum Volitionality {
Optional,
Required,
RequiredIfNoBody,
}
fn clap_arg(
arg_name: &str,
volitionality: Volitionality,
description: &Option<String>,
arg_type: &Type,
) -> TokenStream {
let help = description.as_ref().map(|description| {
quote! {
.help(#description)
}
});
let arg_type_name = arg_type.ident();
// For enums that have **only** simple variants, we do some slightly
// fancier argument handling to expose the possible values. In particular,
// we use clap's `PossibleValuesParser` with each variant converted to a
// string. Then we use TypedValueParser::map to translate that into the
// actual type of the enum.
let maybe_enum_parser =
if let typify::TypeDetails::Enum(e) = arg_type.details() {
let maybe_var_names = e
.variants()
.map(|(var_name, var_details)| {
if let TypeEnumVariant::Simple = var_details {
Some(format_ident!("{}", var_name))
} else {
None
}
})
.collect::<Option<Vec<_>>>();
maybe_var_names.map(|var_names| {
quote! {
clap::builder::TypedValueParser::map(
clap::builder::PossibleValuesParser::new([
#( #arg_type_name :: #var_names.to_string(), )*
]),
|s| #arg_type_name :: try_from(s).unwrap()
)
}
})
} else {
None
};
let value_parser = if let Some(enum_parser) = maybe_enum_parser {
enum_parser
} else {
// Let clap pick a value parser for us. This has the benefit of
// allowing for override implementations. A generated client may
// implement ValueParserFactory for a type to create a custom parser.
quote! {
clap::value_parser!(#arg_type_name)
}
};
let required = match volitionality {
Volitionality::Optional => quote! { .required(false) },
Volitionality::Required => quote! { .required(true) },
Volitionality::RequiredIfNoBody => {
quote! { .required_unless_present("json-body") }
}
};
quote! {
clap::Arg::new(#arg_name)
.long(#arg_name)
.value_parser(#value_parser)
#required
#help
}
}
#[derive(Debug)]
struct CliArg {
/// Code to parse the argument
parser: TokenStream,
/// Code to consume the argument
consumer: TokenStream,
}
#[derive(Debug, Default, PartialEq, Eq)]
enum CliBodyArg {
#[default]
None,
Required,
Optional,
}
#[derive(Default, Debug)]
struct CliOperationArgs {
args: BTreeMap<String, CliArg>,
body: CliBodyArg,
}
impl CliOperationArgs {
fn has_arg(&self, name: &String) -> bool {
self.args.contains_key(name)
}
fn add_arg(&mut self, name: String, arg: CliArg) {
self.args.insert(name, arg);
}
fn body_present(&mut self) {
assert_eq!(self.body, CliBodyArg::None);
self.body = CliBodyArg::Optional;
}
fn body_required(&mut self) {
assert!(
self.body == CliBodyArg::Optional
|| self.body == CliBodyArg::Required
);
self.body = CliBodyArg::Required;
}
}