-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlib.rs
More file actions
1452 lines (1180 loc) · 47 KB
/
lib.rs
File metadata and controls
1452 lines (1180 loc) · 47 KB
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::BTreeMap;
use anyhow::Result;
use inflector::cases::{kebabcase::to_kebab_case, titlecase::to_title_case};
use openapitor::types::exts::{ParameterExt, ParameterSchemaOrContentExt, ReferenceOrExt, TokenStreamExt};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
use serde_tokenstream::from_tokenstream;
use syn::ItemEnum;
/// The parameters passed to our macro.
#[derive(Deserialize, Debug)]
struct Params {
/// The name of the tag that the commands are grouped buy.
tag: String,
}
pub fn do_gen(attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
// Get the data from the parameters.
let params = from_tokenstream::<Params>(&attr)?;
// Lets get the Open API spec.
let api = openapitor::load_json_spec(include_str!("../../spec.json"))?;
let ops = get_operations_with_tag(&api, ¶ms.tag)?;
let og_enum: ItemEnum = syn::parse2(item).unwrap();
let mut variants = og_enum.variants.clone();
let mut commands = quote!();
// Let's iterate over the paths and generate the code.
for op in ops {
// Let's generate the delete command if it exists.
if op.is_root_level_operation(¶ms.tag) && op.method == "DELETE" {
let (delete_cmd, delete_enum_item) = op.generate_delete_command(¶ms.tag)?;
commands = quote! {
#commands
#delete_cmd
};
// Clap with alphabetize the help text subcommands so it is fine to just shove
// the variants on the end.
variants.push(delete_enum_item);
} else if op.is_root_level_operation(¶ms.tag) && op.method == "GET" {
let (view_cmd, view_enum_item) = op.generate_view_command(¶ms.tag)?;
commands = quote! {
#commands
#view_cmd
};
// Clap with alphabetize the help text subcommands so it is fine to just shove
// the variants on the end.
variants.push(view_enum_item);
} else if op.is_root_level_operation(¶ms.tag) && op.method == "PUT" {
let (edit_cmd, edit_enum_item) = op.generate_edit_command(¶ms.tag)?;
commands = quote! {
#commands
#edit_cmd
};
// Clap with alphabetize the help text subcommands so it is fine to just shove
// the variants on the end.
variants.push(edit_enum_item);
} else if op.is_root_create_operation(¶ms.tag) {
let (create_cmd, create_enum_item) = op.generate_create_command(¶ms.tag)?;
commands = quote! {
#commands
#create_cmd
};
// Clap with alphabetize the help text subcommands so it is fine to just shove
// the variants on the end.
variants.push(create_enum_item);
} else if op.is_root_list_operation(¶ms.tag) {
let (list_cmd, list_enum_item) = op.generate_list_command(¶ms.tag)?;
commands = quote! {
#commands
#list_cmd
};
// Clap with alphabetize the help text subcommands so it is fine to just shove
// the variants on the end.
variants.push(list_enum_item);
}
}
let attrs = og_enum.attrs;
let code = quote!(
use num_traits::identities::Zero;
#(#attrs);*
enum SubCommand {
#variants
}
#commands
);
Ok(code)
}
struct Operation {
op: openapiv3::Operation,
method: String,
path: String,
id: String,
spec: openapiv3::OpenAPI,
}
struct Property {
schema: openapiv3::ReferenceOr<openapiv3::Schema>,
required: bool,
description: Option<String>,
}
struct Parameter {
parameter: openapiv3::Parameter,
required: bool,
}
impl Parameter {
fn data(&self) -> Result<openapiv3::ParameterData> {
(&self.parameter).data()
}
}
impl Operation {
/// Returns if the given operation is a root level operation on a specific tag.
fn is_root_level_operation(&self, tag: &str) -> bool {
let method = if self.method == "PUT" {
"update".to_string()
} else {
self.method.to_lowercase()
};
(self.id.ends_with(&format!("{}_{}", method, singular(tag)))
|| self.id.ends_with(&format!("{}_{}_self", method, singular(tag))))
&& !self.op.tags.contains(&"hidden".to_string())
}
/// Returns if the given operation is a root list operation on a specific tag.
fn is_root_list_operation(&self, tag: &str) -> bool {
let pagination =
if let Some(serde_json::value::Value::Bool(b)) = self.op.extensions.get("x-dropshot-pagination") {
*b
} else {
return false;
};
self.id.ends_with(&format!("{}_{}", tag, self.method.to_lowercase())) && pagination && self.method == "GET"
}
/// Returns if the given operation is a root create operation on a specific tag.
fn is_root_create_operation(&self, tag: &str) -> bool {
self.id.ends_with(&format!("{}_{}", tag, self.method.to_lowercase())) && self.method == "POST"
}
fn get_parameters(&self) -> Result<BTreeMap<String, Parameter>> {
let mut parameters = BTreeMap::new();
for param in self.op.parameters.iter() {
let param = param.item()?;
let parameter_data = match param.data() {
Ok(s) => s,
Err(_) => return Ok(parameters),
};
parameters.insert(
parameter_data.name.to_string(),
Parameter {
parameter: param.clone(),
required: parameter_data.required,
},
);
}
Ok(parameters)
}
fn is_parameter(&self, parameter: &str) -> bool {
for param in self.op.parameters.iter() {
let param = match param.item() {
Ok(i) => i,
Err(_) => return false,
};
let parameter_data = match param.data() {
Ok(s) => s,
Err(_) => return false,
};
if parameter_data.name == parameter || parameter_data.name.starts_with(&format!("{}_", parameter)) {
return true;
}
}
false
}
fn get_request_body_name(&self) -> Result<String> {
let request_body = match self.op.request_body.as_ref() {
Some(r) => r,
None => anyhow::bail!("no request_body found"),
}
.item()?;
let content = match request_body.content.get("application/json") {
Some(c) => c,
None => anyhow::bail!("no `application/json` found"),
};
let schema = match content.schema.as_ref() {
Some(s) => s,
None => anyhow::bail!("no content schema found"),
};
schema.reference()
}
fn get_request_body_properties(&self) -> Result<BTreeMap<String, Property>> {
let mut properties = BTreeMap::new();
let request_body = match self.op.request_body.as_ref() {
Some(r) => r,
None => return Ok(properties),
}
.item()?;
let content = match request_body.content.get("application/json") {
Some(c) => c,
None => return Ok(properties),
};
let schema = match content.schema.as_ref() {
Some(s) => s,
None => return Ok(properties),
};
let schema = match schema.item() {
Ok(b) => b.clone(),
Err(e) => {
if e.to_string().contains("reference") {
schema.get_schema_from_reference(&self.spec, false)?
} else {
anyhow::bail!("could not get schema from request body: {}", e);
}
}
};
let obj = match &schema.schema_kind {
openapiv3::SchemaKind::Type(openapiv3::Type::Object(o)) => o,
_ => return Ok(properties),
};
for (key, prop) in obj.properties.iter() {
let mut key = key.to_string();
let s = match prop.item() {
Ok(s) => *s.clone(),
Err(e) => {
if e.to_string().contains("reference") {
prop.get_schema_from_reference(&self.spec, false)?
} else {
anyhow::bail!("could not get schema from prop `{}`: {}", key, e);
}
}
};
if self.method == "PUT" {
// We add the `new_` part onto the parameter since it will be
// overwriting an existing field.
key = format!("new_{}", key);
}
properties.insert(
key.clone(),
Property {
schema: prop.clone().unbox(),
required: obj.required.contains(&key)
|| obj.required.contains(&key.trim_start_matches("new_").to_string()),
description: s.schema_data.description,
},
);
}
Ok(properties)
}
/// Gets a list of all the string parameters for the operation.
/// This includes the path parameters, query parameters, and request_body parameters.
fn get_all_param_names(&self) -> Result<Vec<String>> {
let mut param_names = Vec::new();
for param in self.get_parameters()?.keys() {
param_names.push(param.to_string());
}
for param in self.get_request_body_properties()?.keys() {
param_names.push(param.to_string());
}
param_names.sort();
Ok(param_names)
}
/// Gets all the api call params for the operation.
/// This includes the path parameters, query parameters, and request_body parameters.
fn get_api_call_params(&self, tag: &str) -> Result<Vec<TokenStream>> {
let mut api_call_params: Vec<TokenStream> = Vec::new();
let params = self.get_parameters()?;
let mut params = params.keys().collect::<Vec<_>>();
params.sort();
for p in params {
let mut p = p.to_string();
if p == "page_token" {
api_call_params.push(quote!(""));
continue;
}
if p == "limit" {
api_call_params.push(quote!(self.limit));
continue;
}
p = clean_param_name(&p);
let p = format_ident!("{}", p);
if p == "sort_by" {
// Sort by is an enum so we don't want to "&" it
api_call_params.push(quote!(self.#p.clone()));
continue;
}
api_call_params.push(quote!(&self.#p));
}
let req_body_properties = self.get_request_body_properties()?;
if !req_body_properties.is_empty() {
let mut req_body_rendered = Vec::new();
for (p, v) in req_body_properties {
let mut n = p.to_string();
if self.method == "PUT" {
n = n.trim_start_matches("new_").to_string();
}
let p_og = format_ident!("{}", n);
let mut new = if p == "id" { singular(tag) } else { p.to_string() };
new = clean_param_name(&new);
let p_short = format_ident!("{}", new);
let type_name = self.render_type(v.schema, v.required)?;
let rendered = type_name.rendered()?;
if type_name.is_option()? && v.required {
// If the rendered property is an option, we want to unwrap it before
// sending the request since we were only doing that for the oneOf types.
// And we should only unwrap it if it is a required property.
if self.method == "PUT" {
req_body_rendered.push(quote!(#p_og: self.#p_short.as_ref().unwrap().clone()));
} else {
req_body_rendered.push(quote!(#p_og: #p_short.unwrap()));
}
} else if rendered.starts_with("Vec<") {
// We parse all Vec's as strings and so now we have to convert them back to the
// original type.
req_body_rendered
.push(quote!(#p_og: self.#p_short.iter().map(|v| serde_json::from_str(v).unwrap()).collect()));
} else if rendered == "uuid::Uuid" {
//if v.required {
req_body_rendered.push(quote!(#p_og: "".to_string()));
} else if v.required {
if self.method == "PUT" {
req_body_rendered.push(quote!(#p_og: self.#p_short.clone()));
} else {
req_body_rendered.push(quote!(#p_og: #p_short.clone()));
}
} else {
// We can use self here since we aren't chaing the value from
// a prompt.
// In the future should we prompt for everything we would change this.
req_body_rendered.push(quote!(#p_og: self.#p_short.clone()));
}
}
let type_name = self.get_request_body_name()?;
let type_name = format_ident!("{}", type_name);
api_call_params.push(quote! {
&kittycad::types::#type_name {
#(#req_body_rendered),*
}
});
}
Ok(api_call_params)
}
/// Gets a list of all the string parameters for the operation.
/// This includes the path parameters, query parameters, and request_body parameters.
#[allow(dead_code)]
fn get_all_param_names_and_types(&self) -> Result<Vec<(String, openapiv3::ReferenceOr<openapiv3::Schema>)>> {
let mut param_names = Vec::new();
for (param, p) in self.get_parameters()? {
let data = if let Ok(data) = p.data() {
data
} else {
continue;
};
param_names.push((param.to_string(), data.format.schema()?));
}
for (param, p) in self.get_request_body_properties()? {
param_names.push((param.to_string(), p.schema));
}
param_names.sort_by(|a, b| a.0.cmp(&b.0));
Ok(param_names)
}
/// Gets a list of all the required string parameters for the operation.
/// This includes the path parameters, query parameters, and request_body parameters.
fn get_all_required_param_names_and_types(
&self,
) -> Result<Vec<(String, openapiv3::ReferenceOr<openapiv3::Schema>)>> {
let mut param_names = Vec::new();
for (param, p) in self.get_parameters()? {
if p.data().unwrap().required {
let data = if let Ok(data) = p.data() {
data
} else {
continue;
};
param_names.push((param.to_string(), data.format.schema()?));
}
}
for (param, p) in self.get_request_body_properties()? {
if p.required {
param_names.push((param.to_string(), p.schema));
}
}
param_names.sort_by(|a, b| a.0.cmp(&b.0));
Ok(param_names)
}
fn render_struct_param(
&self,
name: &str,
tag: &str,
schema: openapiv3::ReferenceOr<openapiv3::Schema>,
description: Option<String>,
required: bool,
) -> Result<TokenStream> {
if skip_defaults(name, tag)
|| name == format!("{}_name", singular(tag))
|| name == format!("{}_id", singular(tag))
|| name == "limit"
|| name == "page_token"
{
// Return early and empty, we don't care about these.
return Ok(quote!());
}
let name_cleaned = clean_param_name(name);
let name_ident = format_ident!("{}", name_cleaned);
let n = if name_cleaned == "vpc" {
name_cleaned.to_uppercase()
} else {
name_cleaned
};
let singular_tag = singular(tag);
let prop = if singular_tag == "vpc" {
singular_tag.to_uppercase()
} else {
singular_tag
};
let doc = if let Some(desc) = description {
desc
} else if name == "sort_by" {
"The order in which to sort the results.".to_string()
} else if name.starts_with("new_") {
format!(
"The new {} for the {}.",
n.trim_start_matches("new_").replace('_', " "),
prop
)
.replace(" dns ", " DNS ")
} else if name == "description" {
format!("The description for the {}.", prop)
} else if self.is_root_list_operation(tag) {
format!("The {} that holds the {}.", n, plural(&prop))
} else {
format!("The {} that holds the {}.", n, prop)
};
let mut type_name = self.render_type(schema, required)?;
let rendered = type_name.rendered()?;
let flags = get_flags(name)?;
let short_flag = flags.get_short_token();
let long_flag = flags.get_long_token();
let requiredq = if required {
quote!(true)
} else if !rendered.starts_with("Option<") {
// Default value is meaningless for Option types.
quote!(false, default_value_t)
} else {
quote!(false)
};
if rendered.starts_with("Vec<") {
type_name = quote!(Vec<String>);
}
let clap_line = if self.method == "POST" || name == "sort_by" {
// On create, we want to set default values for the parameters.
if rendered.starts_with("Option<") {
// A default value there is pretty much always going to be None.
quote! {
#[clap(#long_flag, #short_flag)]
}
} else if rendered.starts_with("Vec<") {
// A default value there is pretty much always going to be None.
quote! {
#[clap(#long_flag, #short_flag multiple_values = true)]
}
} else {
quote! {
#[clap(#long_flag, #short_flag default_value_t)]
}
}
} else {
quote! {
#[clap(#long_flag, #short_flag required = #requiredq)]
}
};
Ok(quote! {
#[doc = #doc]
#clap_line
pub #name_ident: #type_name,
})
}
/// Get additional struct parameters.
fn get_additional_struct_params(&self, tag: &str) -> Result<Vec<TokenStream>> {
let mut params = Vec::new();
for (param, p) in self.get_parameters()? {
let data = if let Ok(data) = p.data() {
data
} else {
continue;
};
// Let's get the type.
let schema = data.format.schema()?;
params.push(self.render_struct_param(¶m, tag, schema, data.description, p.required)?);
}
for (param, p) in self.get_request_body_properties()? {
params.push(self.render_struct_param(¶m, tag, p.schema, p.description, p.required)?);
}
Ok(params)
}
/// Generate the create command.
// TODO remove below once we have examples that need an extra prompt.
#[allow(clippy::match_single_binding)]
fn generate_create_command(&self, tag: &str) -> Result<(TokenStream, syn::Variant)> {
let tag_ident = format_ident!("{}", tag);
let singular_tag_str = singular(tag);
let singular_tag_lc = format_ident!("{}", singular(tag));
let struct_name = format_ident!("Cmd{}Create", to_title_case(&singular(tag)));
let struct_doc = format!(
"Create a new {}.\n\nTo create a {} interactively, use `zoo {} create` with no arguments.",
singular_tag_str,
singular_tag_str,
&singular(tag)
);
let struct_inner_name_doc = format!("The name of the {} to create.", singular_tag_str);
let mut mutable_variables: Vec<TokenStream> = Vec::new();
for (p, _) in self.get_all_required_param_names_and_types()? {
let mut p = if p == "id" { singular(tag) } else { p };
p = clean_param_name(&p);
let ident = format_ident!("{}", p);
mutable_variables.push(quote!(
let mut #ident = self.#ident.clone();
));
}
let api_call_params = self.get_api_call_params(tag)?;
let mut required_checks: Vec<TokenStream> = Vec::new();
for (p, t) in self.get_all_required_param_names_and_types()? {
let p = if p == "id" { singular(tag) } else { p };
let n = clean_param_name(&p);
let p = format_ident!("{}", n);
let formatted = if n == singular(tag) {
// Format like an argument not a flag.
format!("[{}]", n)
} else {
let flags = get_flags(&n)?;
flags.format_help()
};
let error_msg = format!("{} required in non-interactive mode", formatted);
let is_check = self.get_is_check_fn(t, true)?;
required_checks.push(quote!(
if #p.#is_check() && !ctx.io.can_prompt() {
return Err(anyhow::anyhow!(#error_msg));
}
));
}
let name_prompt = quote!(
// Prompt for the resource name.
if #singular_tag_lc.is_empty() {
match dialoguer::Input::<String>::new()
.with_prompt(&format!("{} name:", #singular_tag_str))
.interact_text()
{
Ok(name) => #singular_tag_lc = name,
Err(err) => {
return Err(anyhow::anyhow!("prompt failed: {}", err));
}
}
}
);
let mut additional_prompts: Vec<TokenStream> = Vec::new();
for (p, v) in self.get_all_required_param_names_and_types()? {
let n = clean_param_name(&p);
if skip_defaults(&n, tag) {
// Skip the prompt.
continue;
}
let p = format_ident!("{}", n);
let title = format!("{} {}", singular_tag_str, n);
let is_check = self.get_is_check_fn(v.clone(), true)?;
let rendered = self.render_type(v, true)?;
let rendered_str = openapitor::types::get_text(&rendered)?
.trim_start_matches("Option<")
.trim_start_matches("kittycad::types::")
.trim_end_matches('>')
.to_string();
let rendered = format_ident!("{}", rendered_str);
let needs_extra_prompt: Option<(&str, bool)> = match rendered_str.as_str() {
_ => None,
};
// Any weird OneOfs and other types that have a custom prompt should be
// handled here.
if let Some((base_prompt, is_optional)) = needs_extra_prompt {
let prompt = if is_optional {
quote! { Some(kittycad::types::#rendered::prompt(#base_prompt)?) }
} else {
quote! { kittycad::types::#rendered::prompt(#base_prompt)? }
};
additional_prompts.push(quote! {
// Prompt if they didn't provide the value.
if #p.#is_check() {
{
use crate::prompt_ext::PromptExt;
#p = #prompt;
}
}
});
// Continue through the loop early.
continue;
}
additional_prompts.push(quote! {
// Propmt if they didn't provide the value.
if #p.#is_check() {
match dialoguer::Input::<_>::new()
.with_prompt(#title)
.interact_text()
{
Ok(input) => #p = input,
Err(err) => {
return Err(anyhow::anyhow!("prompt failed: {}", err));
}
}
}
});
}
// We need to form the output back to the client.
let output = if self.is_parameter("organization") && (self.is_parameter("project") || tag == "projects") {
let start = quote! {
let full_name = format!("{}/{}", organization, project);
};
if tag != "projects" {
quote! {
#start
writeln!(
ctx.io.out,
"{} Created {} {} in {}",
cs.success_icon(),
#singular_tag_str,
#singular_tag_lc,
full_name
)?;
}
} else {
quote! {
#start
writeln!(
ctx.io.out,
"{} Created {} {}",
cs.success_icon(),
#singular_tag_str,
full_name
)?;
}
}
} else {
quote! {
writeln!(
ctx.io.out,
"{} Created {} {}",
cs.success_icon(),
#singular_tag_str,
#singular_tag_lc
)?;
}
};
let additional_struct_params = self.get_additional_struct_params(tag)?;
let cmd = quote!(
#[doc = #struct_doc]
#[derive(clap::Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct #struct_name {
#[doc = #struct_inner_name_doc]
#[clap(name = #singular_tag_str, required = true)]
pub #singular_tag_lc: String,
#(#additional_struct_params)*
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for #struct_name {
async fn run(&self, ctx: &mut crate::context::Context) -> anyhow::Result<()> {
#(#mutable_variables)*
#(#required_checks)*
let client = ctx.api_client("")?;
// Prompt for various parameters if we can, and the user passed them as empty.
if ctx.io.can_prompt() {
#name_prompt
#(#additional_prompts)*
}
client
.#tag_ident()
.post(
#(#api_call_params),*
)
.await?;
let cs = ctx.io.color_scheme();
#output
Ok(())
}
}
);
let enum_item: syn::Variant = syn::parse2(quote!(Create(#struct_name)))?;
Ok((cmd, enum_item))
}
/// Generate the edit command.
fn generate_edit_command(&self, tag: &str) -> Result<(TokenStream, syn::Variant)> {
let tag_ident = format_ident!("{}", tag);
let fn_name_ident = if tag == "users" {
format_ident!("{}_self", "update")
} else {
format_ident!("{}", "update")
};
let singular_tag_str = singular(tag);
let singular_tag_lc = format_ident!("{}", singular(tag));
let struct_name = format_ident!("Cmd{}Edit", to_title_case(&singular(tag)));
let struct_doc = format!("Edit {} settings.", singular_tag_str,);
let struct_inner_name_doc = format!("The {} to edit. Can be an ID or name.", singular_tag_str);
let api_call_params = self.get_api_call_params(tag)?;
let mut check_nothing_to_edit = quote!(if);
let mut i = 0;
let req_body_properties = self.get_request_body_properties()?;
for (p, v) in &req_body_properties {
if skip_defaults(p, tag) {
// Skip the defaults.
continue;
}
let n = clean_param_name(p);
let p = format_ident!("{}", n);
let is_check = self.get_is_check_fn(v.schema.clone(), v.required)?;
check_nothing_to_edit = quote! {
#check_nothing_to_edit self.#p.#is_check()
};
if i < req_body_properties.len() - 1 {
// Add the && if we need it.
check_nothing_to_edit = quote! {
#check_nothing_to_edit &&
};
} else {
check_nothing_to_edit = quote! {
#check_nothing_to_edit {
return Err(anyhow::anyhow!("nothing to edit"));
}
};
}
i += 1;
}
// We need to form the output back to the client.
let output = quote! {
writeln!(
ctx.io.out,
"{} Edited {}",
cs.success_icon_with_color(nu_ansi_term::Color::Red),
#singular_tag_str,
)?;
};
let additional_struct_params = self.get_additional_struct_params(tag)?;
let params = if tag == "users" {
quote!()
} else {
quote!(
#[doc = #struct_inner_name_doc]
#[clap(name = #singular_tag_str, required = true)]
pub #singular_tag_lc: String,
)
};
let cmd = quote!(
#[doc = #struct_doc]
#[derive(clap::Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct #struct_name {
#params
#(#additional_struct_params)*
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for #struct_name {
async fn run(&self, ctx: &mut crate::context::Context) -> anyhow::Result<()> {
#check_nothing_to_edit
let client = ctx.api_client("")?;
let result = client.#tag_ident().#fn_name_ident(#(#api_call_params),*).await?;
let cs = ctx.io.color_scheme();
#output
Ok(())
}
}
);
let enum_item: syn::Variant = syn::parse2(quote!(
Edit(#struct_name)
))?;
Ok((cmd, enum_item))
}
/// Generate the view command.
fn generate_view_command(&self, tag: &str) -> Result<(TokenStream, syn::Variant)> {
let tag_ident = format_ident!("{}", tag);
let fn_name_ident = if tag == "users" {
format_ident!("{}_self", "get")
} else {
format_ident!("{}", "get")
};
let singular_tag_str = singular(tag);
let singular_tag_lc = format_ident!("{}", singular(tag));
let struct_name = format_ident!("Cmd{}View", to_title_case(&singular(tag)));
let struct_doc = format!(
"View {}.\n\nDisplay information about a Zoo {}.\n\nWith `--web`, open the {} in a web browser instead.",
singular_tag_str, singular_tag_str, singular_tag_str
);
let struct_inner_web_doc = format!("Open the {} in the browser.", singular_tag_str);
let struct_inner_name_doc = format!("The {} to view. Can be an ID or name.", singular_tag_str);
let api_call_params = self.get_api_call_params(tag)?;
let additional_struct_params = self.get_additional_struct_params(tag)?;
let params = if tag == "users" {
quote!()
} else {
quote!(
#[doc = #struct_inner_name_doc]
#[clap(name = #singular_tag_str, required = true)]
pub #singular_tag_lc: String,
)
};
let url = if tag == "users" {
quote!(
let url = "https://zoo.dev/account".to_string();
)
} else {
let path = &self.path;
quote!(
let url = format!(
"https://{}{}",
ctx.config.default_host()?,
#path
);
)
};
let format_flag = format_flag();
let cmd = quote!(
#[doc = #struct_doc]
#[derive(clap::Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]