1use std::collections::BTreeMap;
4
5use heck::ToKebabCase;
6use openapiv3::OpenAPI;
7use proc_macro2::TokenStream;
8use quote::{format_ident, quote};
9use typify::{Type, TypeEnumVariant, TypeSpaceImpl, TypeStructPropInfo};
10
11use crate::{
12 method::{OperationParameterKind, OperationParameterType, OperationResponseStatus},
13 to_schema::ToSchema,
14 util::{sanitize, Case},
15 validate_openapi, Generator, Result,
16};
17
18struct CliOperation {
19 cli_fn: TokenStream,
20 execute_fn: TokenStream,
21 execute_trait: TokenStream,
22}
23
24impl Generator {
25 pub fn cli(&mut self, spec: &OpenAPI, crate_name: &str) -> Result<TokenStream> {
27 validate_openapi(spec)?;
28
29 let schemas = spec.components.iter().flat_map(|components| {
31 components
32 .schemas
33 .iter()
34 .map(|(name, ref_or_schema)| (name.clone(), ref_or_schema.to_schema()))
35 });
36
37 self.type_space.add_ref_types(schemas)?;
38
39 let raw_methods = spec
40 .paths
41 .iter()
42 .flat_map(|(path, ref_or_item)| {
43 let item = ref_or_item.as_item().unwrap();
45 item.iter().map(move |(method, operation)| {
46 (path.as_str(), method, operation, &item.parameters)
47 })
48 })
49 .map(|(path, method, operation, path_parameters)| {
50 self.process_operation(operation, &spec.components, path, method, path_parameters)
51 })
52 .collect::<Result<Vec<_>>>()?;
53
54 let methods = raw_methods
55 .iter()
56 .map(|method| self.cli_method(method))
57 .collect::<Vec<_>>();
58
59 let cli_ops = methods.iter().map(|op| &op.cli_fn);
60 let execute_ops = methods.iter().map(|op| &op.execute_fn);
61 let trait_ops = methods.iter().map(|op| &op.execute_trait);
62
63 let cli_fns = raw_methods
64 .iter()
65 .map(|method| format_ident!("cli_{}", sanitize(&method.operation_id, Case::Snake)))
66 .collect::<Vec<_>>();
67 let execute_fns = raw_methods
68 .iter()
69 .map(|method| format_ident!("execute_{}", sanitize(&method.operation_id, Case::Snake)))
70 .collect::<Vec<_>>();
71
72 let cli_variants = raw_methods
73 .iter()
74 .map(|method| format_ident!("{}", sanitize(&method.operation_id, Case::Pascal)))
75 .collect::<Vec<_>>();
76
77 let crate_path = syn::TypePath {
78 qself: None,
79 path: syn::parse_str(crate_name).unwrap(),
80 };
81
82 let code = quote! {
83 use #crate_path::*;
84
85 pub struct Cli<T: CliConfig> {
86 client: Client,
87 config: T,
88 }
89 impl<T: CliConfig> Cli<T> {
90 pub fn new(
91 client: Client,
92 config: T,
93 ) -> Self {
94 Self { client, config }
95 }
96
97 pub fn get_command(cmd: CliCommand) -> ::clap::Command {
98 match cmd {
99 #(
100 CliCommand::#cli_variants => Self::#cli_fns(),
101 )*
102 }
103 }
104
105 #(#cli_ops)*
106
107 pub async fn execute(
108 &self,
109 cmd: CliCommand,
110 matches: &::clap::ArgMatches,
111 ) -> anyhow::Result<()> {
112 match cmd {
113 #(
114 CliCommand::#cli_variants => {
115 self.#execute_fns(matches).await
117 }
118 )*
119 }
120 }
121
122 #(#execute_ops)*
123 }
124
125 pub trait CliConfig {
126 fn success_item<T>(&self, value: &ResponseValue<T>)
127 where
128 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
129 fn success_no_item(&self, value: &ResponseValue<()>);
130 fn error<T>(&self, value: &Error<T>)
131 where
132 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
133
134 fn list_start<T>(&self)
135 where
136 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
137 fn list_item<T>(&self, value: &T)
138 where
139 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
140 fn list_end_success<T>(&self)
141 where
142 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
143 fn list_end_error<T>(&self, value: &Error<T>)
144 where
145 T: schemars::JsonSchema + serde::Serialize + std::fmt::Debug;
146
147 #(#trait_ops)*
148 }
149
150 #[derive(Copy, Clone, Debug)]
151 pub enum CliCommand {
152 #(#cli_variants,)*
153 }
154
155 impl CliCommand {
156 pub fn iter() -> impl Iterator<Item = CliCommand> {
157 vec![
158 #(
159 CliCommand::#cli_variants,
160 )*
161 ].into_iter()
162 }
163 }
164
165 };
166
167 Ok(code)
168 }
169
170 fn cli_method(&mut self, method: &crate::method::OperationMethod) -> CliOperation {
171 let CliArg {
172 parser: parser_args,
173 consumer: consumer_args,
174 } = self.cli_method_args(method);
175
176 let about = method.summary.as_ref().map(|summary| {
177 quote! {
178 .about(#summary)
179 }
180 });
181
182 let long_about = method.description.as_ref().map(|description| {
183 quote! {
184 .long_about(#description)
185 }
186 });
187
188 let fn_name = format_ident!("cli_{}", &method.operation_id);
189
190 let cli_fn = quote! {
191 pub fn #fn_name() -> ::clap::Command
192 {
193 ::clap::Command::new("")
194 #parser_args
195 #about
196 #long_about
197 }
198 };
199
200 let fn_name = format_ident!("execute_{}", &method.operation_id);
201 let op_name = format_ident!("{}", &method.operation_id);
202
203 let (_, success_kind) =
204 self.extract_responses(method, OperationResponseStatus::is_success_or_default);
205 let (_, error_kind) =
206 self.extract_responses(method, OperationResponseStatus::is_error_or_default);
207
208 let execute_and_output = match method.dropshot_paginated {
209 None => {
211 let success_output = match success_kind {
212 crate::method::OperationResponseKind::Type(_) => {
213 quote! {
214 {
215 self.config.success_item(&r);
216 Ok(())
217 }
218 }
219 }
220 crate::method::OperationResponseKind::None => {
221 quote! {
222 {
223 self.config.success_no_item(&r);
224 Ok(())
225 }
226 }
227 }
228 crate::method::OperationResponseKind::Raw
229 | crate::method::OperationResponseKind::Upgrade => {
230 quote! {
231 {
232 todo!()
233 }
234 }
235 }
236 };
237
238 let error_output = match error_kind {
239 crate::method::OperationResponseKind::Type(_)
240 | crate::method::OperationResponseKind::None => {
241 quote! {
242 {
243 self.config.error(&r);
244 Err(anyhow::Error::new(r))
245 }
246 }
247 }
248 crate::method::OperationResponseKind::Raw
249 | crate::method::OperationResponseKind::Upgrade => {
250 quote! {
251 {
252 todo!()
253 }
254 }
255 }
256 };
257
258 quote! {
259 let result = request.send().await;
260
261 match result {
262 Ok(r) => #success_output
263 Err(r) => #error_output
264 }
265 }
266 }
267
268 Some(_) => {
270 let success_type = match success_kind {
271 crate::method::OperationResponseKind::Type(type_id) => {
272 self.type_space.get_type(&type_id).unwrap().ident()
273 }
274 crate::method::OperationResponseKind::None => quote! { () },
275 crate::method::OperationResponseKind::Raw => todo!(),
276 crate::method::OperationResponseKind::Upgrade => todo!(),
277 };
278 let error_output = match error_kind {
279 crate::method::OperationResponseKind::Type(_)
280 | crate::method::OperationResponseKind::None => {
281 quote! {
282 {
283 self.config.list_end_error(&r);
284 return Err(anyhow::Error::new(r))
285 }
286 }
287 }
288 crate::method::OperationResponseKind::Raw
289 | crate::method::OperationResponseKind::Upgrade => {
290 quote! {
291 {
292 todo!()
293 }
294 }
295 }
296 };
297 quote! {
298 self.config.list_start::<#success_type>();
299
300 let mut stream = futures::StreamExt::take(
305 request.stream(),
306 matches
307 .get_one::<std::num::NonZeroU32>("limit")
308 .map_or(usize::MAX, |x| x.get() as usize));
309
310 loop {
311 match futures::TryStreamExt::try_next(&mut stream).await {
312 Err(r) => #error_output
313 Ok(None) => {
314 self.config.list_end_success::<#success_type>();
315 return Ok(());
316 }
317 Ok(Some(value)) => {
318 self.config.list_item(&value);
319 }
320 }
321 }
322 }
323 }
324 };
325
326 let execute_fn = quote! {
327 pub async fn #fn_name(&self, matches: &::clap::ArgMatches)
328 -> anyhow::Result<()>
329 {
330 let mut request = self.client.#op_name();
331 #consumer_args
332
333 self.config.#fn_name(matches, &mut request)?;
335
336 #execute_and_output
337 }
338 };
339
340 let struct_name = sanitize(&method.operation_id, Case::Pascal);
342 let struct_ident = format_ident!("{}", struct_name);
343
344 let execute_trait = quote! {
345 fn #fn_name(
346 &self,
347 matches: &::clap::ArgMatches,
348 request: &mut builder :: #struct_ident,
349 ) -> anyhow::Result<()> {
350 Ok(())
351 }
352 };
353
354 CliOperation {
355 cli_fn,
356 execute_fn,
357 execute_trait,
358 }
359 }
360
361 fn cli_method_args(&self, method: &crate::method::OperationMethod) -> CliArg {
362 let mut args = CliOperationArgs::default();
363
364 let first_page_required_set = method
365 .dropshot_paginated
366 .as_ref()
367 .map(|d| &d.first_page_params);
368
369 for param in &method.params {
370 let innately_required = match ¶m.kind {
371 OperationParameterKind::Body(_) => continue,
373
374 OperationParameterKind::Path => true,
375 OperationParameterKind::Query(required) => *required,
376 OperationParameterKind::Header(required) => *required,
377 };
378
379 if method.dropshot_paginated.is_some() && param.name.as_str() == "page_token" {
381 continue;
382 }
383
384 let first_page_required = first_page_required_set
385 .map_or(false, |required| required.contains(¶m.api_name));
386
387 let volitionality = if innately_required || first_page_required {
388 Volitionality::Required
389 } else {
390 Volitionality::Optional
391 };
392
393 let OperationParameterType::Type(arg_type_id) = ¶m.typ else {
394 unreachable!("query and path parameters must be typed")
395 };
396 let arg_type = self.type_space.get_type(arg_type_id).unwrap();
397
398 let arg_name = param.name.to_kebab_case();
399
400 assert!(!args.has_arg(&arg_name));
402
403 let parser = clap_arg(&arg_name, volitionality, ¶m.description, &arg_type);
404
405 let arg_fn_name = sanitize(¶m.name, Case::Snake);
406 let arg_fn = format_ident!("{}", arg_fn_name);
407 let OperationParameterType::Type(arg_type_id) = ¶m.typ else {
408 panic!()
409 };
410 let arg_type = self.type_space.get_type(arg_type_id).unwrap();
411 let arg_type_name = arg_type.ident();
412
413 let consumer = quote! {
414 if let Some(value) =
415 matches.get_one::<#arg_type_name>(#arg_name)
416 {
417 request = request.#arg_fn(value.clone());
420 }
421 };
422
423 args.add_arg(arg_name, CliArg { parser, consumer })
424 }
425
426 let maybe_body_type_id = method
427 .params
428 .iter()
429 .find(|param| matches!(¶m.kind, OperationParameterKind::Body(_)))
430 .and_then(|param| match ¶m.typ {
431 OperationParameterType::RawBody => None,
435
436 OperationParameterType::Type(body_type_id) => Some(body_type_id),
437 });
438
439 if let Some(body_type_id) = maybe_body_type_id {
440 args.body_present();
441 let body_type = self.type_space.get_type(body_type_id).unwrap();
442 let details = body_type.details();
443
444 match details {
445 typify::TypeDetails::Struct(struct_info) => {
446 for prop_info in struct_info.properties_info() {
447 self.cli_method_body_arg(&mut args, prop_info)
448 }
449 }
450
451 _ => {
452 args.body_required()
455 }
456 }
457 }
458
459 let parser_args = args.args.values().map(|CliArg { parser, .. }| parser);
460
461 let body_json_args = (match args.body {
463 CliBodyArg::None => None,
464 CliBodyArg::Required => Some(true),
465 CliBodyArg::Optional => Some(false),
466 })
467 .map(|required| {
468 let help = "Path to a file that contains the full json body.";
469
470 quote! {
471 .arg(
472 ::clap::Arg::new("json-body")
473 .long("json-body")
474 .value_name("JSON-FILE")
475 .required(#required)
478 .value_parser(::clap::value_parser!(std::path::PathBuf))
479 .help(#help)
480 )
481 .arg(
482 ::clap::Arg::new("json-body-template")
483 .long("json-body-template")
484 .action(::clap::ArgAction::SetTrue)
485 .help("XXX")
486 )
487 }
488 });
489
490 let parser = quote! {
491 #(
492 .arg(#parser_args)
493 )*
494 #body_json_args
495 };
496
497 let consumer_args = args.args.values().map(|CliArg { consumer, .. }| consumer);
498
499 let body_json_consumer = maybe_body_type_id.map(|body_type_id| {
500 let body_type = self.type_space.get_type(body_type_id).unwrap();
501 let body_type_ident = body_type.ident();
502 quote! {
503 if let Some(value) =
504 matches.get_one::<std::path::PathBuf>("json-body")
505 {
506 let body_txt = std::fs::read_to_string(value).unwrap();
507 let body_value =
508 serde_json::from_str::<#body_type_ident>(
509 &body_txt,
510 )
511 .unwrap();
512 request = request.body(body_value);
513 }
514 }
515 });
516
517 let consumer = quote! {
518 #(
519 #consumer_args
520 )*
521 #body_json_consumer
522 };
523
524 CliArg { parser, consumer }
525 }
526
527 fn cli_method_body_arg(&self, args: &mut CliOperationArgs, prop_info: TypeStructPropInfo<'_>) {
528 let TypeStructPropInfo {
529 name,
530 description,
531 required,
532 type_id,
533 } = prop_info;
534
535 let prop_type = self.type_space.get_type(&type_id).unwrap();
536
537 let maybe_inner_type =
546 if let typify::TypeDetails::Option(inner_type_id) = prop_type.details() {
547 let inner_type = self.type_space.get_type(&inner_type_id).unwrap();
548 Some(inner_type)
549 } else {
550 None
551 };
552
553 let prop_type = if let Some(inner_type) = maybe_inner_type {
554 inner_type
555 } else {
556 prop_type
557 };
558
559 let scalar = prop_type.has_impl(TypeSpaceImpl::FromStr);
560
561 let prop_name = name.to_kebab_case();
562 if scalar && !args.has_arg(&prop_name) {
563 let volitionality = if required {
564 Volitionality::RequiredIfNoBody
565 } else {
566 Volitionality::Optional
567 };
568 let parser = clap_arg(
569 &prop_name,
570 volitionality,
571 &description.map(str::to_string),
572 &prop_type,
573 );
574
575 let prop_fn = format_ident!("{}", sanitize(name, Case::Snake));
576 let prop_type_ident = prop_type.ident();
577 let consumer = quote! {
578 if let Some(value) =
579 matches.get_one::<#prop_type_ident>(
580 #prop_name,
581 )
582 {
583 request = request.body_map(|body| {
586 body.#prop_fn(value.clone())
587 })
588 }
589 };
590 args.add_arg(prop_name, CliArg { parser, consumer })
591 } else if required {
592 args.body_required()
593 }
594
595 }
606}
607
608enum Volitionality {
609 Optional,
610 Required,
611 RequiredIfNoBody,
612}
613
614fn clap_arg(
615 arg_name: &str,
616 volitionality: Volitionality,
617 description: &Option<String>,
618 arg_type: &Type,
619) -> TokenStream {
620 let help = description.as_ref().map(|description| {
621 quote! {
622 .help(#description)
623 }
624 });
625 let arg_type_name = arg_type.ident();
626
627 let maybe_enum_parser = if let typify::TypeDetails::Enum(e) = arg_type.details() {
633 let maybe_var_names = e
634 .variants()
635 .map(|(var_name, var_details)| {
636 if let TypeEnumVariant::Simple = var_details {
637 Some(format_ident!("{}", var_name))
638 } else {
639 None
640 }
641 })
642 .collect::<Option<Vec<_>>>();
643
644 maybe_var_names.map(|var_names| {
645 quote! {
646 ::clap::builder::TypedValueParser::map(
647 ::clap::builder::PossibleValuesParser::new([
648 #( #arg_type_name :: #var_names.to_string(), )*
649 ]),
650 |s| #arg_type_name :: try_from(s).unwrap()
651 )
652 }
653 })
654 } else {
655 None
656 };
657
658 let value_parser = if let Some(enum_parser) = maybe_enum_parser {
659 enum_parser
660 } else {
661 quote! {
665 ::clap::value_parser!(#arg_type_name)
666 }
667 };
668
669 let required = match volitionality {
670 Volitionality::Optional => quote! { .required(false) },
671 Volitionality::Required => quote! { .required(true) },
672 Volitionality::RequiredIfNoBody => {
673 quote! { .required_unless_present("json-body") }
674 }
675 };
676
677 quote! {
678 ::clap::Arg::new(#arg_name)
679 .long(#arg_name)
680 .value_parser(#value_parser)
681 #required
682 #help
683 }
684}
685
686#[derive(Debug)]
687struct CliArg {
688 parser: TokenStream,
690
691 consumer: TokenStream,
693}
694
695#[derive(Debug, Default, PartialEq, Eq)]
696enum CliBodyArg {
697 #[default]
698 None,
699 Required,
700 Optional,
701}
702
703#[derive(Default, Debug)]
704struct CliOperationArgs {
705 args: BTreeMap<String, CliArg>,
706 body: CliBodyArg,
707}
708
709impl CliOperationArgs {
710 fn has_arg(&self, name: &String) -> bool {
711 self.args.contains_key(name)
712 }
713 fn add_arg(&mut self, name: String, arg: CliArg) {
714 self.args.insert(name, arg);
715 }
716
717 fn body_present(&mut self) {
718 assert_eq!(self.body, CliBodyArg::None);
719 self.body = CliBodyArg::Optional;
720 }
721
722 fn body_required(&mut self) {
723 assert!(self.body == CliBodyArg::Optional || self.body == CliBodyArg::Required);
724 self.body = CliBodyArg::Required;
725 }
726}