-
Notifications
You must be signed in to change notification settings - Fork 290
/
Copy pathtemplates.go
867 lines (767 loc) · 24.2 KB
/
templates.go
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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"github.com/iancoleman/strcase"
)
func getArgsAndPaths(pluralResource, parentTypeName, action string) (colArg, colPath, resPath string) {
strToReplace := "scope"
if parentTypeName != "" {
strToReplace = parentTypeName
}
colArg = fmt.Sprintf("%sId", strcase.ToLowerCamel(strings.ReplaceAll(strToReplace, "-", "_")))
colPath = pluralResource
// append s at the end only if it isn't already present
if colPath[len(colPath)-1] != 's' {
colPath = fmt.Sprintf("%ss", colPath)
}
if action != "" {
action = fmt.Sprintf(":%s", action)
}
resPath = fmt.Sprintf("fmt.Sprintf(\"%s/%%s%s\", url.PathEscape(id))", colPath, action)
return
}
type templateInput struct {
Name string
Package string
Fields []fieldInfo
PluralResourceName string
CollectionFunctionArg string
ResourceFunctionArg string
CollectionPath string
ResourcePath string
ParentTypeName string
SliceSubtypes map[string]sliceSubtypeInfo
ExtraFields []fieldInfo
VersionEnabled bool
ExtraRequiredParams []requiredParam
CreateResponseTypes bool
RecursiveListing bool
}
func fillTemplates() {
optionsMap := map[string]map[string]fieldInfo{}
inputMap := map[string]*structInfo{}
for _, in := range inputStructs {
inputMap[in.generatedStructure.pkg] = in
outBuf := new(bytes.Buffer)
input := templateInput{
Name: in.generatedStructure.name,
Package: in.generatedStructure.pkg,
Fields: in.generatedStructure.fields,
PluralResourceName: in.pluralResourceName,
ParentTypeName: in.parentTypeName,
ExtraFields: in.extraFields,
VersionEnabled: in.versionEnabled,
ExtraRequiredParams: in.extraRequiredParams,
CreateResponseTypes: in.createResponseTypes,
RecursiveListing: in.recursiveListing,
}
if in.packageOverride != "" {
input.Package = in.packageOverride
}
if in.nameOverride != "" {
input.Name = in.nameOverride
}
if len(in.pluralResourceName) > 0 {
input.CollectionFunctionArg, input.CollectionPath, input.ResourcePath = getArgsAndPaths(in.pluralResourceName, in.parentTypeName, "")
}
for _, override := range in.fieldOverrides {
for i, field := range in.generatedStructure.fields {
if field.Name == override.Name {
if override.FieldType != "" {
field.FieldType = override.FieldType
}
in.generatedStructure.fields[i] = field
}
}
}
if err := structTemplate.Execute(outBuf, input); err != nil {
fmt.Printf("error executing struct template for resource %s: %v\n", in.generatedStructure.name, err)
os.Exit(1)
}
if len(in.sliceSubtypes) > 0 {
input.SliceSubtypes = in.sliceSubtypes
in.templates = append(in.templates, sliceSubtypeTemplate)
}
for _, t := range in.templates {
if err := t.Execute(outBuf, input); err != nil {
fmt.Printf("error executing function template for resource %s: %v\n", in.generatedStructure.name, err)
os.Exit(1)
}
}
// We want to generate options per-package, not per-struct, so we
// collate them all here for writing later. The map argument of the
// package map is to prevent duplicates since we may have multiple e.g.
// Name or Description fields.
if !in.skipOptions {
pkgOptionMap := map[string]fieldInfo{}
for _, val := range input.Fields {
if val.GenerateSdkOption {
val.SubtypeNames = append(val.SubtypeNames, in.subtypeName)
pkgOptionMap[val.Name] = val
}
}
optionMap := optionsMap[input.Package]
if optionMap == nil {
optionMap = map[string]fieldInfo{}
}
for name, val := range pkgOptionMap {
val.SubtypeNames = append(val.SubtypeNames, optionMap[name].SubtypeNames...)
optionMap[name] = val
}
optionsMap[input.Package] = optionMap
}
// Add in extra defined fields
if len(in.extraFields) > 0 {
optionMap := optionsMap[input.Package]
if optionMap == nil {
optionMap = map[string]fieldInfo{}
}
for _, val := range in.extraFields {
optionMap[val.Name] = val
}
optionsMap[input.Package] = optionMap
}
// Override some defined options
if len(in.fieldOverrides) > 0 && optionsMap != nil {
for _, override := range in.fieldOverrides {
inOpts := optionsMap[input.Package]
if inOpts != nil {
if override.SkipDefault {
fieldInfo := inOpts[override.Name]
fieldInfo.SkipDefault = true
inOpts[override.Name] = fieldInfo
}
}
}
}
outFile, err := filepath.Abs(fmt.Sprintf("%s/%s", os.Getenv("API_GEN_BASEPATH"), in.outFile))
if err != nil {
fmt.Printf("error opening file %q: %v\n", in.outFile, err)
os.Exit(1)
}
outDir := filepath.Dir(outFile)
if _, err := os.Stat(outDir); os.IsNotExist(err) {
_ = os.Mkdir(outDir, os.ModePerm)
}
if err := ioutil.WriteFile(outFile, outBuf.Bytes(), 0o644); err != nil {
fmt.Printf("error writing file %q: %v\n", outFile, err)
os.Exit(1)
}
}
// Now reconstruct options per package and write them out
for pkg, options := range optionsMap {
outBuf := new(bytes.Buffer)
var fieldNames []string
for _, v := range options {
fieldNames = append(fieldNames, v.Name)
}
sort.Strings(fieldNames)
var fields []fieldInfo
for _, v := range fieldNames {
fields = append(fields, options[v])
}
input := templateInput{
Package: pkg,
Fields: fields,
RecursiveListing: inputMap[pkg].recursiveListing,
}
if err := optionTemplate.Execute(outBuf, input); err != nil {
fmt.Printf("error executing option template for package %s: %v\n", pkg, err)
os.Exit(1)
}
outFile, err := filepath.Abs(fmt.Sprintf("%s/%s/%s", os.Getenv("API_GEN_BASEPATH"), pkg, "option.gen.go"))
if err != nil {
fmt.Printf("error opening file %q: %v\n", "option.gen.go", err)
os.Exit(1)
}
outDir := filepath.Dir(outFile)
if _, err := os.Stat(outDir); os.IsNotExist(err) {
_ = os.Mkdir(outDir, os.ModePerm)
}
if err := ioutil.WriteFile(outFile, outBuf.Bytes(), 0o644); err != nil {
fmt.Printf("error writing file %q: %v\n", outFile, err)
os.Exit(1)
}
}
}
var listTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"snakeCase": snakeCase,
},
).Parse(`
func (c *Client) List(ctx context.Context, {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}ListResult, error) {
if {{ .CollectionFunctionArg }} == "" {
return nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into List request")
}
if c.client == nil {
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
opts.queryMap["{{ snakeCase .CollectionFunctionArg }}"] = {{ .CollectionFunctionArg }}
req, err := c.client.NewRequest(ctx, "GET", "{{ .CollectionPath }}", nil, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new({{ .Name }}ListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target.response = resp
return target, nil
}
`))
var readTemplate = template.Must(template.New("").Parse(`
func (c *Client) Read(ctx context.Context, id string, opt... Option) (*{{ .Name }}ReadResult, error) {
if id == "" {
return nil, fmt.Errorf("empty id value passed into Read request")
}
if c.client == nil {
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", {{ .ResourcePath }}, nil, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new({{ .Name }}ReadResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target.response = resp
return target, nil
}
`))
var deleteTemplate = template.Must(template.New("").Parse(`
func (c *Client) Delete(ctx context.Context, id string, opt... Option) (*{{ .Name }}DeleteResult, error) {
if id == "" {
return nil, fmt.Errorf("empty id value passed into Delete request")
}
if c.client == nil {
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", {{ .ResourcePath }}, nil, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target := &{{ .Name }}DeleteResult{
response: resp,
}
return target, nil
}
`))
const createTemplateStr = `
func (c *Client) {{ funcName }} (ctx context.Context, {{ range .ExtraRequiredParams }} {{ .Name }} {{ .Typ }}, {{ end }} {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}CreateResult, error) {
if {{ .CollectionFunctionArg }} == "" {
return nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into {{ funcName }} request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, fmt.Errorf("nil client")
}
{{ range .ExtraRequiredParams }} if {{ .Name }} == "" {
return nil, fmt.Errorf("empty {{ .Name }} value passed into {{ funcName }} request")
} else {
opts.postMap["{{ .PostType }}"] = {{ .Name }}
}{{ end }}
opts.postMap["{{ snakeCase .CollectionFunctionArg }}"] = {{ .CollectionFunctionArg }}
req, err := c.client.NewRequest(ctx, "POST", "{{ .CollectionPath }}{{ apiAction }}", opts.postMap, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating {{ funcName }} request: %w", err)
}
{{ if ( eq .CollectionPath "\"scopes\"" ) }}
opts.queryMap["scope_id"] = scopeId
{{ end }}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error performing client request during {{ funcName }} call: %w", err)
}
target := new({{ .Name }}CreateResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, fmt.Errorf("error decoding {{ funcName }} response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target.response = resp
return target, nil
}
`
var commonCreateTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"snakeCase": snakeCase,
"funcName": func() string {
return "Create"
},
"apiAction": func() string {
return ""
},
},
).Parse(createTemplateStr))
var updateTemplate = template.Must(template.New("").Parse(`
func (c *Client) Update(ctx context.Context, id string, version uint32, opt... Option) (*{{ .Name }}UpdateResult, error) {
if id == "" {
return nil, fmt.Errorf("empty id value passed into Update request")
}
if c.client == nil {
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
{{ if .VersionEnabled }}
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingErr := c.Read(ctx, id, append([]Option{WithSkipCurlOutput(true)}, opt...)...)
if existingErr != nil {
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
{{ end }}
opts.postMap["version"] = version
req, err := c.client.NewRequest(ctx, "PATCH", {{ .ResourcePath }}, opts.postMap, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new({{ .Name }}UpdateResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target.response = resp
return target, nil
}
`))
var sliceSubtypeTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"makeSlice": makeSlice,
"snakeCase": snakeCase,
"kebabCase": kebabCase,
"getPathWithAction": getPathWithAction,
},
).Parse(`
{{ $input := . }}
{{ range $index, $op := makeSlice "Add" "Set" "Remove" }}
{{ range $key, $value := $input.SliceSubtypes }}
{{ $fullName := print $op $key }}
{{ $actionName := kebabCase $fullName }}
{{ $resPath := getPathWithAction $input.PluralResourceName $input.ParentTypeName $actionName }}
func (c *Client) {{ $fullName }}(ctx context.Context, id string, version uint32, {{ if ( not ( eq $value.VarName "" ) ) }}{{ $value.VarName }} {{ $value.SliceType }},{{ end }} opt... Option) (*{{ $input.Name }}UpdateResult, error) {
if id == "" {
return nil, fmt.Errorf("empty id value passed into {{ $fullName }} request")
}
{{ if ( not ( eq $op "Set" ) ) }}
{{ if ( not ( eq $value.VarName "" ) ) }}
if len({{ $value.VarName }}) == 0 {
return nil, errors.New("empty {{ $value.VarName }} passed into {{ $fullName }} request")
}
{{ end }}
{{ end }}
if c.client == nil {
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
{{ if $input.VersionEnabled }}
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, errors.New("zero version number passed into {{ $fullName }} request")
}
existingTarget, existingErr := c.Read(ctx, id, append([]Option{WithSkipCurlOutput(true)}, opt...)...)
if existingErr != nil {
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
{{ end }}
opts.postMap["version"] = version
{{ if ( not ( eq $value.VarName "" ) ) }}
opts.postMap["{{ snakeCase $value.VarName }}"] = {{ $value.VarName }}
{{ end }}
req, err := c.client.NewRequest(ctx, "POST", {{ $resPath }}, opts.postMap, apiOpts...)
if err != nil {
return nil, fmt.Errorf("error creating {{ $fullName }} request: %w", err)
}
if len(opts.queryMap) > 0 {
q := url.Values{}
for k, v := range opts.queryMap {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error performing client request during {{ $fullName }} call: %w", err)
}
target := new({{ $input.Name }}UpdateResult)
target.Item = new({{ $input.Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, fmt.Errorf("error decoding {{ $fullName }} response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
target.response = resp
return target, nil
}
{{ end }}
{{ end }}
`))
var structTemplate = template.Must(template.New("").Parse(
fmt.Sprint(`// Code generated by "make api"; DO NOT EDIT.
package {{ .Package }}
import (
"context"
"fmt"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
type {{ .Name }} struct { {{ range .Fields }}
{{ .Name }} {{ .FieldType }} `, "`json:\"{{ .ProtoName }},omitempty\"`", `{{ end }}
{{ if .CreateResponseTypes }}
response *api.Response
{{ else if ( eq .Name "Error" ) }}
response *Response
{{ end }}
}
{{ if .CreateResponseTypes }}
type {{ .Name }}ReadResult struct {
Item *{{ .Name }}
response *api.Response
}
func (n {{ .Name }}ReadResult) GetItem() *{{ .Name }} {
return n.Item
}
func (n {{ .Name }}ReadResult) GetResponse() *api.Response {
return n.response
}
type {{ .Name }}CreateResult = {{ .Name }}ReadResult
type {{ .Name }}UpdateResult = {{ .Name }}ReadResult
type {{ .Name }}DeleteResult struct {
response *api.Response
}
// GetItem will always be nil for {{ .Name }}DeleteResult
func (n {{ .Name }}DeleteResult) GetItem() interface{} {
return nil
}
func (n {{ .Name }}DeleteResult) GetResponse() *api.Response {
return n.response
}
type {{ .Name }}ListResult struct {
Items []*{{ .Name }}
response *api.Response
}
func (n {{ .Name }}ListResult) GetItems() []*{{ .Name }} {
return n.Items
}
func (n {{ .Name }}ListResult) GetResponse() *api.Response {
return n.response
}
{{ end }}
`)))
var clientTemplate = template.Must(template.New("").Parse(`
// Client is a client for this collection
type Client struct {
client *api.Client
}
// Creates a new client for this collection. The submitted API client is cloned;
// modifications to it after generating this client will not have effect. If you
// need to make changes to the underlying API client, use ApiClient() to access
// it.
func NewClient(c *api.Client) *Client {
return &Client{ client: c.Clone() }
}
// ApiClient returns the underlying API client
func (c *Client) ApiClient() *api.Client {
return c.client
}
`))
var optionTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"makeSlice": makeSlice,
"removeDups": removeDups,
},
).Parse(`
package {{ .Package }}
import (
"strconv"
"github.com/hashicorp/boundary/api"
)
// Option is a func that sets optional attributes for a call. This does not need
// to be used directly, but instead option arguments are built from the
// functions in this package. WithX options set a value to that given in the
// argument; DefaultX options indicate that the value should be set to its
// default. When an API call is made options are processed in ther order they
// appear in the function call, so for a given argument X, a succession of WithX
// or DefaultX calls will result in the last call taking effect.
type Option func(*options)
type options struct {
postMap map[string]interface{}
queryMap map[string]string
withAutomaticVersioning bool
withSkipCurlOutput bool
withFilter string
{{ if .RecursiveListing }} withRecursive bool {{ end }}
}
func getDefaultOptions() options {
return options{
postMap: make(map[string]interface{}),
queryMap: make(map[string]string),
}
}
func getOpts(opt ...Option) (options, []api.Option) {
opts := getDefaultOptions()
for _, o := range opt {
if o != nil {
o(&opts)
}
}
var apiOpts []api.Option
if opts.withSkipCurlOutput {
apiOpts = append(apiOpts, api.WithSkipCurlOutput(true))
}
if opts.withFilter != "" {
opts.queryMap["filter"] = opts.withFilter
}{{ if .RecursiveListing }}
if opts.withRecursive {
opts.queryMap["recursive"] = strconv.FormatBool(opts.withRecursive)
} {{ end }}
return opts, apiOpts
}
// If set, and if the version is zero during an update, the API will perform a
// fetch to get the current version of the resource and populate it during the
// update call. This is convenient but opens up the possibility for subtle
// order-of-modification issues, so use carefully.
func WithAutomaticVersioning(enable bool) Option {
return func(o *options) {
o.withAutomaticVersioning = enable
}
}
// WithSkipCurlOutput tells the API to not use the current call for cURL output.
// Useful for when we need to look up versions.
func WithSkipCurlOutput(skip bool) Option {
return func(o *options) {
o.withSkipCurlOutput = true
}
}
// WithFilter tells the API to filter the items returned using the provided
// filter term. The filter should be in a format supported by
// hashicorp/go-bexpr.
func WithFilter(filter string) Option {
return func(o *options) {
o.withFilter = strings.TrimSpace(filter)
}
}
{{ if .RecursiveListing }}
// WithRecursive tells the API to use recursion for listing operations on this
// resource
func WithRecursive(recurse bool) Option {
return func(o *options) {
o.withRecursive = true
}
}
{{ end }}
{{ range $fieldIndex, $field := .Fields }}
{{ $subtypes := (removeDups $field.SubtypeNames ) }}
{{ if ( eq ( len ( $subtypes ) ) 0 )}}
{{ $subtypes = ( makeSlice "" ) }}
{{ end }}
{{ range $subtypeIndex, $subtypeName := $subtypes }}
func With{{ $subtypeName }}{{ $field.Name }}(in{{ $field.Name }} {{ $field.FieldType }}) Option {
return func(o *options) { {{ if ( not ( eq $subtypeName "" ) ) }}
raw, ok := o.postMap["attributes"]
if !ok {
raw = interface{}(map[string]interface{}{})
}
val := raw.(map[string]interface{})
val["{{ $field.ProtoName }}"] = in{{ $field.Name }}
o.postMap["attributes"] = val
{{ else if $field.Query }}
o.queryMap["{{ $field.ProtoName }}"] = fmt.Sprintf("%v", in{{ $field.Name }})
{{ else }}
o.postMap["{{ $field.ProtoName }}"] = in{{ $field.Name }}
{{ end }} }
}
{{ if ( not $field.SkipDefault ) }}
func Default{{ $subtypeName }}{{ $field.Name }}() Option {
return func(o *options) { {{ if ( not ( eq $subtypeName "" ) ) }}
raw, ok := o.postMap["attributes"]
if !ok {
raw = interface{}(map[string]interface{}{})
}
val := raw.(map[string]interface{})
val["{{ $field.ProtoName }}"] = nil
o.postMap["attributes"] = val
{{ else }}
o.postMap["{{ $field.ProtoName }}"] = nil
{{ end }} }
}
{{ end }}
{{ end }}
{{ end }}
`))
var mapstructureConversionTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"typeFromSubtype": typeFromSubtype,
"kebabCase": kebabCase,
},
).Parse(`
func AttributesMapTo{{ .Name }}(in map[string]interface{}) (*{{ .Name }}, error) {
if in == nil {
return nil, fmt.Errorf("nil input map")
}
var out {{ .Name }}
dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: &out,
TagName: "json",
})
if err != nil {
return nil, fmt.Errorf("error creating mapstructure decoder: %w", err)
}
if err := dec.Decode(in); err != nil {
return nil, fmt.Errorf("error decoding: %w", err)
}
return &out, nil
}
func (pt *{{ .ParentTypeName }}) Get{{ .Name }}() (*{{ .Name }}, error) {
if pt.Type != "{{ typeFromSubtype .Name .ParentTypeName "Attributes"}}" {
return nil, fmt.Errorf("asked to fetch %s-type attributes but {{ kebabCase .ParentTypeName }} is of type %s", "{{ typeFromSubtype .Name .ParentTypeName "Attributes"}}", pt.Type)
}
return AttributesMapTo{{ .Name }}(pt.Attributes)
}
`))
func makeSlice(strs ...string) []string {
return strs
}
func snakeCase(in string) string {
return strcase.ToSnake(in)
}
func kebabCase(in string) string {
return strcase.ToKebab(in)
}
func getPathWithAction(plResName, parentTypeName, action string) string {
_, _, resPath := getArgsAndPaths(plResName, parentTypeName, action)
return resPath
}
func removeDups(in []string) []string {
if in == nil {
return nil
}
if len(in) == 0 {
return []string{}
}
vals := make(map[string]struct{}, len(in))
for _, val := range in {
vals[val] = struct{}{}
}
ret := make([]string, 0, len(vals))
for val := range vals {
ret = append(ret, val)
}
sort.Strings(ret)
return ret
}
func typeFromSubtype(in, parent, extraSuffix string) string {
return strings.ToLower(strings.TrimSuffix(strings.TrimSuffix(in, extraSuffix), parent))
}