forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype.go
More file actions
1601 lines (1343 loc) · 49.1 KB
/
type.go
File metadata and controls
1601 lines (1343 loc) · 49.1 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
// Copyright 2024 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"fmt"
"log"
"strings"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/api/product"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/api/resource"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/api/utils"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/google"
"golang.org/x/exp/slices"
"gopkg.in/yaml.v3"
)
// Represents a property type
type Type struct {
Name string `yaml:"name,omitempty"`
// original value of :name before the provider override happens
// same as :name if not overridden in provider
ApiName string `yaml:"api_name,omitempty"`
// TODO rewrite: improve the parsing of properties based on type in resource yaml files.
Type string `yaml:"type"`
// For nested fields, this only applies within the parent.
// For example, an optional parent can contain a required child.
Required bool `yaml:"required,omitempty"`
DefaultValue interface{} `yaml:"default_value,omitempty"`
// Expected to follow the format as follows:
//
// description: |
// This is a description of a field.
// If it comprises multiple lines, it must continue to be indented.
//
Description string `yaml:"description,omitempty"`
Exclude bool `yaml:"exclude,omitempty"`
// Add a deprecation message for a field that's been deprecated in the API
// use the YAML chomping folding indicator (>-) if this is a multiline
// string, as providers expect a single-line one w/o a newline.
DeprecationMessage string `yaml:"deprecation_message,omitempty"`
// Add a removed message for fields no longer supported in the API. This should
// be used for fields supported in one version but have been removed from
// a different version.
RemovedMessage string `yaml:"removed_message,omitempty"`
// If set value will not be sent to server on sync.
// For nested fields, this also needs to be set on each descendant (ie. self,
// child, etc.).
Output bool `yaml:"output,omitempty"`
// If set to true, changes in the field's value require recreating the
// resource.
// For nested fields, this only applies at the current level. This means
// it should be explicitly added to each field that needs the ForceNew
// behavior.
Immutable bool `yaml:"immutable,omitempty"`
// Indicates that this field is client-side only (aka virtual.)
ClientSide bool `yaml:"client_side,omitempty"`
// url_param_only will not send the field in the resource body and will
// not attempt to read the field from the API response.
// NOTE - this doesn't work for nested fields
UrlParamOnly bool `yaml:"url_param_only,omitempty"`
// Additional query Parameters to append to GET calls.
ReadQueryParams string `yaml:"read_query_params,omitempty"`
UpdateVerb string `yaml:"update_verb,omitempty"`
UpdateUrl string `yaml:"update_url,omitempty"`
// Some updates only allow updating certain fields at once (generally each
// top-level field can be updated one-at-a-time). If this is set, we group
// fields to update by (verb, url, fingerprint, id) instead of just
// (verb, url, fingerprint), to allow multiple fields to reuse the same
// endpoints.
UpdateId string `yaml:"update_id,omitempty"`
// The fingerprint value required to update this field. Downstreams should
// GET the resource and parse the fingerprint value while doing each update
// call. This ensures we can supply the fingerprint to each distinct
// request.
FingerprintName string `yaml:"fingerprint_name,omitempty"`
// If true, we will include the empty value in requests made including
// this attribute (both creates and updates). This rarely needs to be
// set to true, and corresponds to both the "NullFields" and
// "ForceSendFields" concepts in the autogenerated API clients.
SendEmptyValue bool `yaml:"send_empty_value,omitempty"`
// [Optional] If true, empty nested objects are sent to / read from the
// API instead of flattened to null.
// The difference between this and send_empty_value is that send_empty_value
// applies when the key of an object is empty; this applies when the values
// are all nil / default. eg: "expiration: null" vs "expiration: {}"
// In the case of Terraform, this occurs when a block in config has optional
// values, and none of them are used. Terraform returns a nil instead of an
// empty map[string]interface{} like we'd expect.
AllowEmptyObject bool `yaml:"allow_empty_object,omitempty"`
MinVersion string `yaml:"min_version,omitempty"`
ExactVersion string `yaml:"exact_version,omitempty"`
// A list of properties that conflict with this property. Uses the "lineage"
// field to identify the property eg: parent.meta.label.foo
Conflicts []string `yaml:"conflicts,omitempty"`
// A list of properties that at least one of must be set.
AtLeastOneOf []string `yaml:"at_least_one_of,omitempty"`
// A list of properties that exactly one of must be set.
ExactlyOneOf []string `yaml:"exactly_one_of,omitempty"`
// A list of properties that are required to be set together.
RequiredWith []string `yaml:"required_with,omitempty"`
// Shared constraint group pointers (populated post-unmarshal)
ConflictsGroup *([]string) `yaml:"-"`
AtLeastOneOfGroup *([]string) `yaml:"-"`
ExactlyOneOfGroup *([]string) `yaml:"-"`
RequiredWithGroup *([]string) `yaml:"-"`
// Can only be overridden - we should never set this ourselves.
NewType string `yaml:"-"`
EnumValues []string `yaml:"enum_values,omitempty"`
ExcludeDocsValues bool `yaml:"exclude_docs_values,omitempty"`
// ====================
// Array Fields
// ====================
MinSize *int `yaml:"min_size,omitempty"`
MaxSize *int `yaml:"max_size,omitempty"`
// Adds a ValidateFunc to the item schema
ItemValidation resource.Validation `yaml:"item_validation,omitempty"`
ParentName string `yaml:"parent_name,omitempty"`
// ====================
// ResourceRef Fields
// ====================
Resource string `yaml:"resource,omitempty"`
Imports string `yaml:"imports,omitempty"`
// ====================
// Terraform Overrides
// ====================
// Adds a DiffSuppressFunc to the schema
DiffSuppressFunc string `yaml:"diff_suppress_func,omitempty"`
StateFunc string `yaml:"state_func,omitempty"` // Adds a StateFunc to the schema
Sensitive bool `yaml:"sensitive,omitempty"` // Adds `Sensitive: true` to the schema
// If true, write-only arguments will be automatically generated for this field.
// (`[field_name]_wo` and `[field_name]_wo_version`).
// For more information, see: https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/write-only-arguments
WriteOnly bool `yaml:"write_only,omitempty"`
// TODO: remove this field after all references are migrated
// see: https://github.com/GoogleCloudPlatform/magic-modules/pull/14933#pullrequestreview-3166578379
WriteOnlyLegacy bool `yaml:"write_only_legacy,omitempty"` // Adds `WriteOnlyLegacy: true` to the schema
// Does not set this value to the returned API value. Useful for fields
// like secrets where the returned API value is not helpful.
IgnoreRead bool `yaml:"ignore_read,omitempty"`
// Adds a ValidateFunc to the schema
Validation resource.Validation `yaml:"validation,omitempty"`
// Indicates that this is an Array that should have Set diff semantics.
UnorderedList bool `yaml:"unordered_list,omitempty"`
IsSet bool `yaml:"is_set,omitempty"` // Uses a Set instead of an Array
// Optional function to determine the unique ID of an item in the set
// If not specified, schema.HashString (when elements are string) or
// schema.HashSchema are used.
SetHashFunc string `yaml:"set_hash_func,omitempty"`
// if true, then we get the default value from the Google API if no value
// is set in the terraform configuration for this field.
// It translates to setting the field to Computed & Optional in the schema.
// For nested fields, this only applies at the current level. This means
// it should be explicitly added to each field that needs the defaulting
// behavior.
DefaultFromApi bool `yaml:"default_from_api,omitempty"`
// https://github.com/hashicorp/terraform/pull/20837
// Apply a ConfigMode of SchemaConfigModeAttr to the field.
// This should be avoided for new fields, and only used with old ones.
SchemaConfigModeAttr bool `yaml:"schema_config_mode_attr,omitempty"`
// Names of fields that should be included in the updateMask.
UpdateMaskFields []string `yaml:"update_mask_fields,omitempty"`
// For a TypeMap, the expander function to call on the key.
// Defaults to expandString.
KeyExpander string `yaml:"key_expander,omitempty"`
// For a TypeMap, the DSF to apply to the key.
KeyDiffSuppressFunc string `yaml:"key_diff_suppress_func,omitempty"`
// ====================
// Map Fields
// ====================
// The type definition of the contents of the map.
ValueType *Type `yaml:"value_type,omitempty"`
// While the API doesn't give keys an explicit name, we specify one
// because in Terraform the key has to be a property of the object.
//
// The name of the key. Used in the Terraform schema as a field name.
KeyName string `yaml:"key_name,omitempty"`
// ====================
// KeyValuePairs Fields
// ====================
// Ignore writing the "effective_labels" and "effective_annotations" fields to API.
IgnoreWrite bool `yaml:"ignore_write,omitempty"`
// ====================
// Schema Modifications
// ====================
// Schema modifications change the schema of a resource in some
// fundamental way. They're not very portable, and will be hard to
// generate so we should limit their use. Generally, if you're not
// converting existing Terraform resources, these shouldn't be used.
//
// With great power comes great responsibility.
// Flattens a NestedObject by removing that field from the Terraform
// schema but will preserve it in the JSON sent/retrieved from the API
//
// EX: a API schema where fields are nested (eg: `one.two.three`) and we
// desire the properties of the deepest nested object (eg: `three`) to
// become top level properties in the Terraform schema. By overriding
// the properties `one` and `one.two` and setting flatten_object then
// all the properties in `three` will be at the root of the TF schema.
//
// We need this for cases where a field inside a nested object has a
// default, if we can't spend a breaking change to fix a misshapen
// field, or if the UX is _much_ better otherwise.
//
// WARN: only fully flattened properties are currently supported. In the
// example above you could not flatten `one.two` without also flattening
// all of it's parents such as `one`
FlattenObject bool `yaml:"flatten_object,omitempty"`
// ===========
// Custom code
// ===========
// All custom code attributes are string-typed. The string should
// be the name of a template file which will be compiled in the
// specified / described place.
// A custom expander replaces the default expander for an attribute.
// It is called as part of Create, and as part of Update if
// object.input is false. It can return an object of any type,
// so the function header *is* part of the custom code template.
// As with flatten, `property` and `prefix` are available.
CustomExpand string `yaml:"custom_expand,omitempty"`
// A custom flattener replaces the default flattener for an attribute.
// It is called as part of Read. It can return an object of any
// type, and may sometimes need to return an object with non-interface{}
// type so that the d.Set() call will succeed, so the function
// header *is* a part of the custom code template. To help with
// creating the function header, `property` and `prefix` are available,
// just as they are in the standard flattener template.
CustomFlatten string `yaml:"custom_flatten,omitempty"`
ResourceMetadata *Resource `yaml:"-"`
ParentMetadata *Type `yaml:"-"`
// The prefix used as part of the property expand/flatten function name
// flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}
Prefix string `yaml:"prefix,omitempty"`
// The field is not present in CAI asset
IsMissingInCai bool `yaml:"is_missing_in_cai,omitempty"`
// A custom expander replaces the default expander for an attribute.
// It is called as part of tfplan2cai conversion if
// object.input is false. It can return an object of any type,
// so the function header *is* part of the custom code template.
// As with flatten, `property` and `prefix` are available.
CustomTgcExpand string `yaml:"custom_tgc_expand,omitempty"`
// A custom flattener replaces the default flattener for an attribute.
// It is called as part of cai2hcl conversion. It can return an object of any type,
// so the function header *is* a part of the custom code template. To help with
// creating the function header, `property` and `prefix` are available,
// just as they are in the standard flattener template.
CustomTgcFlatten string `yaml:"custom_tgc_flatten,omitempty"`
// If true, the empty value of this attribute in CAI asset is included.
IncludeEmptyValueInCai bool `yaml:"include_empty_value_in_cai,omitempty"`
// If the property is type of bool and has `defaul_from_api: true`,
// include empty value in CAI asset by default during tfplan2cai conversion.
// Use `exclude_false_in_cai` to override the default behavior
// when the default value on API side is true.
//
// If a property is missing in CAI asset, use `is_missing_in_cai: true`
// and `exclude_false_in_cai: true` is not needed
ExcludeFalseInCai bool `yaml:"exclude_false_in_cai,omitempty"`
// If true, the custom flatten function is not applied during cai2hcl
TGCIgnoreTerraformCustomFlatten bool `yaml:"tgc_ignore_terraform_custom_flatten,omitempty"`
TGCIgnoreRead bool `yaml:"tgc_ignore_read,omitempty"`
Properties []*Type `yaml:"properties,omitempty"`
ItemType *Type `yaml:"item_type,omitempty"`
}
const MAX_NAME = 20
func (t *Type) MarshalYAML() (interface{}, error) {
// Use a type alias to prevent the marshaller from recursively calling this method.
type typeAlias Type
resourceMetadata := t.ResourceMetadata
if resourceMetadata == nil {
resourceMetadata = &Resource{}
}
// Calculate the default values for a Type struct.
// setShallowDefaults is safe to call with a nil ResourceMetadata.
defaults := Type{}
// Pre-populate fields that the default calculation depends on.
defaults.Name = t.Name
defaults.Type = t.Type
defaults.Resource = t.Resource
defaults.ParentName = t.ParentName
defaults.setShallowDefaults(resourceMetadata)
defaults.Type = ""
defaults.Resource = ""
if defaults.ParentName != defaults.Name {
defaults.ParentName = ""
defaults.Name = ""
}
// OmitDefaultsForMarshaling creates a clone of the struct where any field
// matching its default value is set to its zero-value, allowing `omitempty` to work.
// It returns a pointer to the clone.
clone, err := utils.OmitDefaultsForMarshaling(*t, defaults)
if err != nil {
return nil, err
}
clonePtr := clone.(*Type)
// Explicitly break the parent cycle in the clone to prevent deep recursion.
clonePtr.ParentMetadata = nil
// Encode the cleaned-up struct into a yaml.Node.
var node yaml.Node
err = node.Encode((*typeAlias)(clonePtr)) // Use the alias to prevent recursion
if err != nil {
return nil, err
}
// Fix: Ensure float values (like 0.0) are marshaled as floats (0.0) with !!float tag.
// If we don't set the tag, it might be emitted as '0' (int) or '!!int 0.0' (invalid).
if _, ok := t.DefaultValue.(float64); ok {
for i := 0; i < len(node.Content); i += 2 {
if node.Content[i].Value == "default_value" {
valNode := node.Content[i+1]
if !strings.Contains(valNode.Value, ".") && !strings.Contains(strings.ToLower(valNode.Value), "e") {
valNode.Value = valNode.Value + ".0"
}
valNode.Tag = "!!float"
break
}
}
}
// Special handling for `properties` field.
// If the original `properties` slice was explicitly empty (`[]`), `omitempty`
// would have removed it during the node encoding. We need to add it back in.
if t.Properties != nil && len(t.Properties) == 0 {
// Check if the key was omitted.
found := false
for i := 0; i < len(node.Content); i += 2 { // Iterate over key nodes
if node.Content[i].Value == "properties" {
found = true
break
}
}
if !found {
// Add the key and an empty sequence node to the mapping.
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "properties"}
valueNode := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}
node.Content = append(node.Content, keyNode, valueNode)
}
}
return &node, nil
}
// SetShallowDefaults calculates and sets default values for the immediate fields
// of this Type, without recursing into its children (like ItemType or Properties).
// This is used by MarshalYAML to create a "defaults" object for comparison.
func (t *Type) setShallowDefaults(r *Resource) {
t.ResourceMetadata = r
if t.UpdateVerb == "" {
t.UpdateVerb = r.UpdateVerb
}
switch {
case t.IsA("Map"):
if t.KeyExpander == "" {
t.KeyExpander = "tpgresource.ExpandString"
}
case t.IsA("NestedObject"):
if t.Name == "" {
t.Name = t.ParentName
}
if t.Description == "" {
t.Description = "A nested object resource."
}
case t.IsA("ResourceRef"):
if t.Name == "" {
t.Name = t.Resource
}
if t.Description == "" {
t.Description = fmt.Sprintf("A reference to %s resource", t.Resource)
}
case t.IsA("Fingerprint"):
t.Output = true
}
if t.ApiName == "" {
t.ApiName = t.Name
}
}
// SetDefault recursively sets default values for this Type and all its children.
// This is used during the initial unmarshalling/compilation phase.
func (t *Type) SetDefault(r *Resource) {
t.setShallowDefaults(r) // First, set defaults for the current level.
switch {
case t.IsA("Array"):
if t.ItemType != nil {
t.ItemType.Name = t.Name
t.ItemType.ParentName = t.Name
t.ItemType.ParentMetadata = t
t.ItemType.SetDefault(r) // Recurse
}
case t.IsA("Map"):
if t.ValueType != nil {
t.ValueType.ParentName = t.Name
t.ValueType.ParentMetadata = t
oldName := t.ValueType.Name
t.ValueType.SetDefault(r) // Recurse
t.ValueType.Name = oldName // unset name if it was previously unset
}
case t.IsA("NestedObject"):
for _, p := range t.Properties {
p.ParentMetadata = t
p.SetDefault(r) // Recurse
}
}
}
func (t *Type) Validate(rName string) (es []error) {
// Use Lineage to get the full path (e.g. "parent.child.grandchild") for clearer error messages.
fullFieldPath := t.Name
if lineage := t.Lineage(); len(lineage) > 0 {
fullFieldPath = strings.Join(lineage, ".")
}
if t.Name == "" {
es = append(es, fmt.Errorf("missing `name` for property with type %s in resource %s", t.Type, rName))
}
// Check type is valid. Also allow empty as it's currently used in unit tests.
if !slices.Contains([]string{"Boolean", "Double", "Integer", "String", "Time", "Enum", "ResourceRef", "NestedObject", "Array", "KeyValuePairs", "KeyValueLabels", "KeyValueTerraformLabels", "KeyValueEffectiveLabels", "KeyValueAnnotations", "Map", "Fingerprint"}, t.Type) {
es = append(es, fmt.Errorf("property %s unknown type %q in resource %s", fullFieldPath, t.Type, rName))
}
if t.Output && t.Required {
es = append(es, fmt.Errorf("property %s cannot be output and required at the same time in resource %s.", fullFieldPath, rName))
}
if t.DefaultFromApi && t.DefaultValue != nil {
es = append(es, fmt.Errorf("property %s 'default_value' and 'default_from_api' cannot be both set in resource %s ", fullFieldPath, rName))
}
if (t.WriteOnlyLegacy || t.WriteOnly) && (t.DefaultFromApi || t.Output) {
es = append(es, fmt.Errorf("property %s cannot be write_only and default_from_api or output at the same time in resource %s", fullFieldPath, rName))
}
if (t.WriteOnlyLegacy || t.WriteOnly) && t.Sensitive {
es = append(es, fmt.Errorf("property %s cannot be write_only and sensitive at the same time in resource %s", fullFieldPath, rName))
}
t.validateLabelsField()
switch {
case t.IsA("Array"):
es = append(es, t.ItemType.Validate(rName)...)
case t.IsA("Map"):
// ValueType.Name should be empty (because it's unused) but we require types to have names in all other cases.
// This logic allows both to be validated.
oldName := t.ValueType.Name
t.ValueType.Name = "any_value"
es = append(es, t.ValueType.Validate(rName)...)
t.ValueType.Name = oldName
if t.ValueType.Name != "" {
es = append(es, fmt.Errorf("property %s value_type.name can't be set in resource %s", fullFieldPath, rName))
}
case t.IsA("NestedObject"):
for _, p := range t.Properties {
es = append(es, p.Validate(rName)...)
}
default:
}
return es
}
// TODO rewrite: add validations
// check :description, required: true
// check :update_verb, allowed: %i[POST PUT PATCH NONE],
// check_default_value_property
// check_conflicts
// check_at_least_one_of
// check_exactly_one_of
// check_required_with
// check the allowed fields for each type, for example, KeyName is only allowed for Map
// Returns a slice of Terraform field names representing where the field is nested within the parent resource.
// For example, []string{"parent_field", "meta", "label", "foo_bar"}.
func (t Type) Lineage() []string {
if t.ParentMetadata == nil || t.ParentMetadata.FlattenObject {
return []string{google.Underscore(t.Name)}
}
// Skip arrays & maps because otherwise the parent field name will be duplicated
if t.ParentMetadata.IsA("Array") || t.ParentMetadata.IsA("Map") {
return t.ParentMetadata.Lineage()
}
return append(t.ParentMetadata.Lineage(), google.Underscore(t.Name))
}
// Returns a slice of API field names representing where the field is nested within the parent resource.
// For example, []string{"parentField", "meta", "label", "fooBar"}. For fine-grained resources, this will
// include the field on the API resource that the fine-grained resource manages.
func (t Type) ApiLineage() []string {
if t.ParentMetadata == nil {
// The special value "." indicates that the resource's shouldn't be considered "nested"
// even if it has NestedQuery set.
if !t.UrlParamOnly && t.ResourceMetadata.ApiResourceField != "." {
if t.ResourceMetadata.ApiResourceField != "" {
return []string{t.ResourceMetadata.ApiResourceField, t.ApiName}
} else if t.ResourceMetadata.NestedQuery != nil {
// Handle `items` as a special case since that's a common container field name for a list endpoint,
// not a fine-grained field name within a resource.
keys := t.ResourceMetadata.NestedQuery.Keys
if len(keys) > 1 || keys[0] != "items" {
return append(t.ResourceMetadata.NestedQuery.Keys, t.ApiName)
}
}
}
return []string{t.ApiName}
}
// Skip arrays because otherwise the array will be included twice
if t.ParentMetadata.IsA("Array") {
return t.ParentMetadata.ApiLineage()
}
// Insert `value` for children of Map fields, and exclude this type because
// it will have the same Name as the parent field.
if t.ParentMetadata.IsA("Map") {
return append(t.ParentMetadata.ApiLineage(), "value")
}
return append(t.ParentMetadata.ApiLineage(), t.ApiName)
}
func (t Type) EnumValuesToString(quoteSeperator string, addEmpty bool) string {
var values []string
for _, val := range t.EnumValues {
values = append(values, fmt.Sprintf("%s%s%s", quoteSeperator, val, quoteSeperator))
}
if addEmpty && !slices.Contains(values, "\"\"") && !t.Required {
values = append(values, "\"\"")
}
return strings.Join(values, ", ")
}
func (t Type) TitlelizeProperty() string {
return google.Camelize(t.Name, "upper")
}
func (t Type) CamelizeProperty() string {
return google.Camelize(t.Name, "lower")
}
// If the Prefix field is already set, returns the value.
// Otherwise, set the Prefix field and returns the value.
func (t *Type) GetPrefix() string {
if t.Prefix == "" {
if t.ParentMetadata == nil {
nestedPrefix := ""
// TODO: Use the nestedPrefix for tgc provider to be consistent with terraform provider
if t.ResourceMetadata.NestedQuery != nil && !strings.Contains(t.ResourceMetadata.ProductMetadata.Compiler, "terraformgoogleconversion") {
nestedPrefix = "Nested"
}
t.Prefix = fmt.Sprintf("%s%s", nestedPrefix, t.ResourceMetadata.ResourceName())
} else {
if t.ParentMetadata != nil && (t.ParentMetadata.IsA("Array") || t.ParentMetadata.IsA("Map")) {
t.Prefix = t.ParentMetadata.GetPrefix()
} else {
if t.ParentMetadata != nil && t.ParentMetadata.ParentMetadata != nil && t.ParentMetadata.ParentMetadata.IsA("Map") {
t.Prefix = fmt.Sprintf("%s%s", t.ParentMetadata.GetPrefix(), t.ParentMetadata.ParentMetadata.TitlelizeProperty())
} else {
t.Prefix = fmt.Sprintf("%s%s", t.ParentMetadata.GetPrefix(), t.ParentMetadata.TitlelizeProperty())
}
}
}
}
return t.Prefix
}
func (t Type) ResourceType() string {
r := t.ResourceRef()
if r == nil {
return ""
}
path := strings.Split(r.BaseUrl, "/")
return path[len(path)-1]
}
func (t Type) FWResourceType() string {
r := t.ResourceRef()
if r == nil {
return ""
}
path := strings.Split(r.BaseUrl, "/")
return path[len(path)-1]
}
// TODO rewrite: validation
// func (t *Type) check_default_value_property() {
// return if @default_value.nil?
// case self
// when Api::Type::String
// clazz = ::String
// when Api::Type::Integer
// clazz = ::Integer
// when Api::Type::Double
// clazz = ::Float
// when Api::Type::Enum
// clazz = ::Symbol
// when Api::Type::Boolean
// clazz = :boolean
// when Api::Type::ResourceRef
// clazz = [::String, ::Hash]
// else
// raise "Update 'check_default_value_property' method to support " \
// "default value for type //{self.class}"
// end
// check :default_value, type: clazz
// }
// Checks that all conflicting properties actually exist.
// This currently just returns if empty, because we don't want to do the check, since
// this list will have a full path for nested attributes.
// func (t *Type) check_conflicts() {
// check :conflicts, type: ::Array, default: [], item_type: ::String
// return if @conflicts.empty?
// }
// Returns list of properties that are in conflict with this property.
// func (t *Type) conflicting() {
func (t Type) Conflicting() []string {
if t.ResourceMetadata == nil {
return []string{}
}
if t.ConflictsGroup != nil {
return *t.ConflictsGroup
}
return t.Conflicts
}
// TODO rewrite: validation
// Checks that all properties that needs at least one of their fields actually exist.
// This currently just returns if empty, because we don't want to do the check, since
// this list will have a full path for nested attributes.
// func (t *Type) check_at_least_one_of() {
// check :at_least_one_of, type: ::Array, default: [], item_type: ::String
// return if @at_least_one_of.empty?
// }
// Returns list of properties that needs at least one of their fields set.
// func (t *Type) at_least_one_of_list() {
func (t Type) AtLeastOneOfList() []string {
if t.ResourceMetadata == nil {
return []string{}
}
if t.AtLeastOneOfGroup != nil {
return *t.AtLeastOneOfGroup
}
return t.AtLeastOneOf
}
// TODO rewrite: validation
// Checks that all properties that needs exactly one of their fields actually exist.
// This currently just returns if empty, because we don't want to do the check, since
// this list will have a full path for nested attributes.
// func (t *Type) check_exactly_one_of() {
// check :exactly_one_of, type: ::Array, default: [], item_type: ::String
// return if @exactly_one_of.empty?
// }
// Returns list of properties that needs exactly one of their fields set.
// func (t *Type) exactly_one_of_list() {
func (t Type) ExactlyOneOfList() []string {
if t.ResourceMetadata == nil {
return []string{}
}
if t.ExactlyOneOfGroup != nil {
return *t.ExactlyOneOfGroup
}
return t.ExactlyOneOf
}
// TODO rewrite: validation
// Checks that all properties that needs required with their fields actually exist.
// This currently just returns if empty, because we don't want to do the check, since
// this list will have a full path for nested attributes.
// func (t *Type) check_required_with() {
// check :required_with, type: ::Array, default: [], item_type: ::String
// return if @required_with.empty?
// }
// Returns list of properties that needs required with their fields set.
func (t Type) RequiredWithList() []string {
if t.ResourceMetadata == nil {
return []string{}
}
if t.RequiredWithGroup != nil {
return *t.RequiredWithGroup
}
return t.RequiredWith
}
func (t Type) Parent() *Type {
return t.ParentMetadata
}
func (t Type) MinVersionObj() *product.Version {
if t.MinVersion != "" {
return t.ResourceMetadata.ProductMetadata.versionObj(t.MinVersion)
} else {
return t.ResourceMetadata.MinVersionObj()
}
}
func (t *Type) exactVersionObj() *product.Version {
if t.ExactVersion == "" {
return nil
}
return t.ResourceMetadata.ProductMetadata.versionObj(t.ExactVersion)
}
func (t *Type) ExcludeIfNotInVersion(version *product.Version) {
if !t.Exclude {
if versionObj := t.exactVersionObj(); versionObj != nil {
t.Exclude = versionObj.CompareTo(version) != 0
}
if !t.Exclude {
t.Exclude = version.CompareTo(t.MinVersionObj()) < 0
}
}
if t.IsA("NestedObject") {
for _, p := range t.Properties {
p.ExcludeIfNotInVersion(version)
}
} else if t.IsA("Array") && t.ItemType.IsA("NestedObject") {
t.ItemType.ExcludeIfNotInVersion(version)
}
}
func (t Type) IsA(clazz string) bool {
if clazz == "" {
log.Fatalf("class cannot be empty")
}
if t.NewType != "" {
return t.NewType == clazz
}
return t.Type == clazz
}
// Returns nested properties for this property.
func (t Type) NestedProperties() []*Type {
props := make([]*Type, 0)
switch {
case t.IsA("Array"):
if t.ItemType.IsA("NestedObject") {
props = google.Reject(t.ItemType.NestedProperties(), func(p *Type) bool {
return t.Exclude
})
}
case t.IsA("NestedObject"):
props = t.UserProperties()
case t.IsA("Map"):
props = google.Reject(t.ValueType.NestedProperties(), func(p *Type) bool {
return t.Exclude
})
default:
}
return props
}
// Returns write-only properties for this property.
func (t Type) WriteOnlyProperties() []*Type {
props := make([]*Type, 0)
switch {
case t.IsA("Array"):
if t.ItemType.IsA("NestedObject") {
props = google.Reject(t.ItemType.WriteOnlyProperties(), func(p *Type) bool {
return t.Exclude
})
}
case t.IsA("NestedObject"):
props = google.Select(t.UserProperties(), func(p *Type) bool {
return p.WriteOnlyLegacy || p.WriteOnly
})
case t.IsA("Map"):
props = google.Reject(t.ValueType.WriteOnlyProperties(), func(p *Type) bool {
return t.Exclude
})
default:
}
return props
}
// AllUniqueNestedProperties Returns all unique nested properties (regular and write-only), preserving order and sorted by name.
func (t Type) AllUniqueNestedProperties() []*Type {
seen := make(map[string]bool)
var result []*Type
for _, p := range t.NestedProperties() {
key := strings.Join(p.Lineage(), "|")
if !seen[key] {
result = append(result, p)
seen[key] = true
}
}
for _, p := range t.WriteOnlyProperties() {
key := strings.Join(p.Lineage(), "|")
if !seen[key] {
result = append(result, p)
seen[key] = true
}
}
return result
}
func (t Type) Removed() bool {
return t.RemovedMessage != ""
}
func (t Type) Deprecated() bool {
return t.DeprecationMessage != ""
}
func (t *Type) GetDescription() string {
return strings.TrimSpace(strings.TrimRight(t.Description, "\n"))
}
func (t *Type) FieldType() []string {
ret := []string{}
if t.Required {
ret = append(ret, "Required")
} else if !t.Output {
ret = append(ret, "Optional")
} else if t.Output && t.ParentMetadata != nil {
ret = append(ret, "Output")
}
if t.WriteOnlyLegacy || t.WriteOnly {
ret = append(ret, "Write-Only")
}
if t.MinVersion == "beta" && t.ResourceMetadata.MinVersion != "beta" {
ret = append(ret, "[Beta](../guides/provider_versions.html.markdown)")
}
if t.DeprecationMessage != "" {
ret = append(ret, "Deprecated")
}
return ret
}
// TODO rewrite: validation
// class Array < Composite
// check :item_type, type: [::String, NestedObject, ResourceRef, Enum], required: true
// unless @item_type.is_a?(NestedObject) || @item_type.is_a?(ResourceRef) \
// || @item_type.is_a?(Enum) || type?(@item_type)
// raise "Invalid type //{@item_type}"
// end
// This function is for array field
func (t Type) ItemTypeClass() string {
if !t.IsA("Array") {
return ""
}
return t.ItemType.Type
}
func (t Type) TFType(s string) string {
switch s {
case "Boolean":
return "schema.TypeBool"
case "Double":
return "schema.TypeFloat"
case "Integer":
return "schema.TypeInt"
case "String":
return "schema.TypeString"
case "Time":
return "schema.TypeString"
case "Enum":
return "schema.TypeString"
case "ResourceRef":
return "schema.TypeString"
case "NestedObject":
return "schema.TypeList"
case "Array":
return "schema.TypeList"
case "KeyValuePairs":
return "schema.TypeMap"
case "KeyValueLabels":
return "schema.TypeMap"
case "KeyValueTerraformLabels":
return "schema.TypeMap"
case "KeyValueEffectiveLabels":
return "schema.TypeMap"
case "KeyValueAnnotations":
return "schema.TypeMap"
case "Map":
return "schema.TypeSet"
case "Fingerprint":
return "schema.TypeString"