/
schema.go
1693 lines (1499 loc) 路 59.1 KB
/
schema.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
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 2016-2022, Pulumi Corporation.
//
// 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 schema
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"regexp"
"sort"
"strings"
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"gopkg.in/yaml.v3"
)
// TODO:
// - Providerless packages
// Type represents a datatype in the Pulumi Schema. Types created by this package are identical if they are
// equal values.
type Type interface {
String() string
isType()
}
type primitiveType int
const (
boolType primitiveType = 1
intType primitiveType = 2
numberType primitiveType = 3
stringType primitiveType = 4
archiveType primitiveType = 5
assetType primitiveType = 6
anyType primitiveType = 7
jsonType primitiveType = 8
)
// nolint: goconst
func (t primitiveType) String() string {
switch t {
case boolType:
return "boolean"
case intType:
return "integer"
case numberType:
return "number"
case stringType:
return "string"
case archiveType:
return "pulumi:pulumi:Archive"
case assetType:
return "pulumi:pulumi:Asset"
case jsonType:
fallthrough
case anyType:
return "pulumi:pulumi:Any"
default:
panic("unknown primitive type")
}
}
func (primitiveType) isType() {}
// IsPrimitiveType returns true if the given Type is a primitive type. The primitive types are bool, int, number,
// string, archive, asset, and any.
func IsPrimitiveType(t Type) bool {
_, ok := plainType(t).(primitiveType)
return ok
}
var (
// BoolType represents the set of boolean values.
BoolType Type = boolType
// IntType represents the set of 32-bit integer values.
IntType Type = intType
// NumberType represents the set of IEEE754 double-precision values.
NumberType Type = numberType
// StringType represents the set of UTF-8 string values.
StringType Type = stringType
// ArchiveType represents the set of Pulumi Archive values.
ArchiveType Type = archiveType
// AssetType represents the set of Pulumi Asset values.
AssetType Type = assetType
// JSONType represents the set of JSON-encoded values.
JSONType Type = jsonType
// AnyType represents the complete set of values.
AnyType Type = anyType
)
// An InvalidType represents an invalid type with associated diagnostics.
type InvalidType struct {
Diagnostics hcl.Diagnostics
}
func (t *InvalidType) String() string {
return "Invalid"
}
func (*InvalidType) isType() {}
func invalidType(diags ...*hcl.Diagnostic) (Type, hcl.Diagnostics) {
t := &InvalidType{Diagnostics: hcl.Diagnostics(diags)}
return t, hcl.Diagnostics(diags)
}
// MapType represents maps from strings to particular element types.
type MapType struct {
// ElementType is the element type of the map.
ElementType Type
}
func (t *MapType) String() string {
return fmt.Sprintf("Map<%v>", t.ElementType)
}
func (*MapType) isType() {}
// ArrayType represents arrays of particular element types.
type ArrayType struct {
// ElementType is the element type of the array.
ElementType Type
}
func (t *ArrayType) String() string {
return fmt.Sprintf("Array<%v>", t.ElementType)
}
func (*ArrayType) isType() {}
// EnumType represents an enum.
type EnumType struct {
// Package is the type's package. Package will not be accurate for types loaded by
// reference. In that case, use PackageReference instead.
Package *Package
// PackageReference is the PackageReference that defines the resource.
PackageReference PackageReference
// Token is the type's Pulumi type token.
Token string
// Comment is the description of the type, if any.
Comment string
// Elements are the predefined enum values.
Elements []*Enum
// ElementType is the underlying type for the enum.
ElementType Type
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
}
// Enum contains information about an enum.
type Enum struct {
// Value is the value of the enum.
Value interface{}
// Comment is the description for the enum value.
Comment string
// Name for the enum.
Name string
// DeprecationMessage indicates whether or not the value is deprecated.
DeprecationMessage string
}
func (t *EnumType) String() string {
return t.Token
}
func (*EnumType) isType() {}
// UnionType represents values that may be any one of a specified set of types.
type UnionType struct {
// ElementTypes are the allowable types for the union type.
ElementTypes []Type
// DefaultType is the default type, if any, for the union type. This can be used by targets that do not support
// unions, or in positions where unions are not appropriate.
DefaultType Type
// Discriminator informs the consumer of an alternative schema based on the value associated with it.
Discriminator string
// Mapping is an optional object to hold mappings between payload values and schema names or references.
Mapping map[string]string
}
func (t *UnionType) String() string {
elements := make([]string, len(t.ElementTypes))
for i, e := range t.ElementTypes {
elements[i] = e.String()
}
if t.DefaultType != nil {
elements = append(elements, "default="+t.DefaultType.String())
}
return fmt.Sprintf("Union<%v>", strings.Join(elements, ", "))
}
func (*UnionType) isType() {}
// ObjectType represents schematized maps from strings to particular types.
type ObjectType struct {
// Package is the package that defines the resource. Package will not be accurate for
// types loaded by reference. In that case, use PackageReference instead.
Package *Package
// PackageReference is the PackageReference that defines the resource.
PackageReference PackageReference
// Token is the type's Pulumi type token.
Token string
// Comment is the description of the type, if any.
Comment string
// Properties is the list of the type's properties.
Properties []*Property
// Language specifies additional language-specific data about the object type.
Language map[string]interface{}
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
// InputShape is the input shape for this object. Only valid if IsPlainShape returns true.
InputShape *ObjectType
// PlainShape is the plain shape for this object. Only valid if IsInputShape returns true.
PlainShape *ObjectType
properties map[string]*Property
}
// IsPlainShape returns true if this object type is the plain shape of a (plain, input)
// pair. The plain shape of an object does not contain *InputType values and only
// references other plain shapes.
func (t *ObjectType) IsPlainShape() bool {
return t.PlainShape == nil
}
// IsInputShape returns true if this object type is the input shape of a (plain, input)
// pair. The input shape of an object may contain *InputType values and may
// reference other input shapes.
func (t *ObjectType) IsInputShape() bool {
return t.PlainShape != nil
}
func (t *ObjectType) Property(name string) (*Property, bool) {
if t.properties == nil && len(t.Properties) > 0 {
t.properties = make(map[string]*Property)
for _, p := range t.Properties {
t.properties[p.Name] = p
}
}
p, ok := t.properties[name]
return p, ok
}
func (t *ObjectType) String() string {
if t.PlainShape != nil {
return t.Token + "鈥nput"
}
return t.Token
}
func (*ObjectType) isType() {}
type ResourceType struct {
// Token is the type's Pulumi type token.
Token string
// Resource is the type's underlying resource.
Resource *Resource
}
func (t *ResourceType) String() string {
return t.Token
}
func (t *ResourceType) isType() {}
// TokenType represents an opaque type that is referred to only by its token. A TokenType may have an underlying type
// that can be used in place of the token.
type TokenType struct {
// Token is the type's Pulumi type token.
Token string
// Underlying type is the type's underlying type, if any.
UnderlyingType Type
}
func (t *TokenType) String() string {
return t.Token
}
func (*TokenType) isType() {}
// InputType represents a type that accepts either a prompt value or an output value.
type InputType struct {
// ElementType is the element type of the input.
ElementType Type
}
func (t *InputType) String() string {
return fmt.Sprintf("Input<%v>", t.ElementType)
}
func (*InputType) isType() {}
// OptionalType represents a type that accepts an optional value.
type OptionalType struct {
// ElementType is the element type of the input.
ElementType Type
}
func (t *OptionalType) String() string {
return fmt.Sprintf("Optional<%v>", t.ElementType)
}
func (*OptionalType) isType() {}
// DefaultValue describes a default value for a property.
type DefaultValue struct {
// Value specifies a static default value, if any. This value must be representable in the Pulumi schema type
// system, and its type must be assignable to that of the property to which the default applies.
Value interface{}
// Environment specifies a set of environment variables to probe for a default value.
Environment []string
// Language specifies additional language-specific data about the default value.
Language map[string]interface{}
}
// Property describes an object or resource property.
type Property struct {
// Name is the name of the property.
Name string
// Comment is the description of the property, if any.
Comment string
// Type is the type of the property.
Type Type
// ConstValue is the constant value for the property, if any.
ConstValue interface{}
// DefaultValue is the default value for the property, if any.
DefaultValue *DefaultValue
// DeprecationMessage indicates whether or not the property is deprecated.
DeprecationMessage string
// Language specifies additional language-specific data about the property.
Language map[string]interface{}
// Secret is true if the property is secret (default false).
Secret bool
// ReplaceOnChanges specifies if the property is to be replaced instead of updated (default false).
ReplaceOnChanges bool
// WillReplaceOnChanges indicates that the provider will replace the resource when
// this property is changed. This property is used exclusively for docs.
WillReplaceOnChanges bool
Plain bool
}
// IsRequired returns true if this property is required (i.e. its type is not Optional).
func (p *Property) IsRequired() bool {
_, optional := p.Type.(*OptionalType)
return !optional
}
// Alias describes an alias for a Pulumi resource.
type Alias struct {
// Name is the "name" portion of the alias, if any.
Name *string
// Project is the "project" portion of the alias, if any.
Project *string
// Type is the "type" portion of the alias, if any.
Type *string
}
// Resource describes a Pulumi resource.
type Resource struct {
// Package is the package that defines the resource. Package will not be accurate for
// types loaded by reference. In that case, use PackageReference instead.
Package *Package
// PackageReference is the PackageReference that defines the resource.
PackageReference PackageReference
// Token is the resource's Pulumi type token.
Token string
// Comment is the description of the resource, if any.
Comment string
// IsProvider is true if the resource is a provider resource.
IsProvider bool
// InputProperties is the list of the resource's input properties.
InputProperties []*Property
// Properties is the list of the resource's output properties. This should be a superset of the input properties.
Properties []*Property
// StateInputs is the set of inputs used to get an existing resource, if any.
StateInputs *ObjectType
// Aliases is the list of aliases for the resource.
Aliases []*Alias
// DeprecationMessage indicates whether or not the resource is deprecated.
DeprecationMessage string
// Language specifies additional language-specific data about the resource.
Language map[string]interface{}
// IsComponent indicates whether the resource is a ComponentResource.
IsComponent bool
// Methods is the list of methods for the resource.
Methods []*Method
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
}
// The set of resource paths where ReplaceOnChanges is true.
//
// For example, if you have the following resource struct:
//
// Resource A {
//
// Properties: {
// Object B {
// Object D: {
// ReplaceOnChanges: true
// }
// Object F: {}
// }
// Object C {
// ReplaceOnChanges: true
// }
// }
// }
//
// A.ReplaceOnChanges() == [[B, D], [C]]
func (r *Resource) ReplaceOnChanges() (changes [][]*Property, err []error) {
for _, p := range r.Properties {
if p.ReplaceOnChanges {
changes = append(changes, []*Property{p})
} else {
stack := map[string]struct{}{p.Type.String(): {}}
childChanges, errList := replaceOnChangesType(p.Type, &stack)
err = append(err, errList...)
for _, c := range childChanges {
changes = append(changes, append([]*Property{p}, c...))
}
}
}
for i, e := range err {
err[i] = fmt.Errorf("Failed to genereate full `ReplaceOnChanges`: %w", e)
}
return changes, err
}
func replaceOnChangesType(t Type, stack *map[string]struct{}) ([][]*Property, []error) {
var errTmp []error
if o, ok := t.(*OptionalType); ok {
return replaceOnChangesType(o.ElementType, stack)
} else if o, ok := t.(*ObjectType); ok {
changes := [][]*Property{}
err := []error{}
for _, p := range o.Properties {
if p.ReplaceOnChanges {
changes = append(changes, []*Property{p})
} else if _, ok := (*stack)[p.Type.String()]; !ok {
// We handle recursive objects
(*stack)[p.Type.String()] = struct{}{}
var object [][]*Property
object, errTmp = replaceOnChangesType(p.Type, stack)
err = append(err, errTmp...)
for _, path := range object {
changes = append(changes, append([]*Property{p}, path...))
}
delete(*stack, p.Type.String())
} else {
err = append(err, fmt.Errorf("Found recursive object %q", p.Name))
}
}
// We don't want to emit errors where replaceOnChanges is not used.
if len(changes) == 0 {
return nil, nil
}
return changes, err
} else if a, ok := t.(*ArrayType); ok {
// This looks for types internal to the array, not a property of the array.
return replaceOnChangesType(a.ElementType, stack)
} else if m, ok := t.(*MapType); ok {
// This looks for types internal to the map, not a property of the array.
return replaceOnChangesType(m.ElementType, stack)
}
return nil, nil
}
// Joins the output of `ReplaceOnChanges` into property path names.
//
// For example, given an input [[B, D], [C]] where each property has a name
// equivalent to it's variable, this function should yield: ["B.D", "C"]
func PropertyListJoinToString(propertyList [][]*Property, nameConverter func(string) string) []string {
var nonOptional func(Type) Type
nonOptional = func(t Type) Type {
if o, ok := t.(*OptionalType); ok {
return nonOptional(o.ElementType)
}
return t
}
out := make([]string, len(propertyList))
for i, p := range propertyList {
names := make([]string, len(p))
for j, n := range p {
if _, ok := nonOptional(n.Type).(*ArrayType); ok {
names[j] = nameConverter(n.Name) + "[*]"
} else if _, ok := nonOptional(n.Type).(*MapType); ok {
names[j] = nameConverter(n.Name) + ".*"
} else {
names[j] = nameConverter(n.Name)
}
}
out[i] = strings.Join(names, ".")
}
return out
}
type Method struct {
// Name is the name of the method.
Name string
// Function is the function definition for the method.
Function *Function
}
// Function describes a Pulumi function.
type Function struct {
// Package is the package that defines the function. Package will not be accurate for
// types loaded by reference. In that case, use PackageReference instead.
Package *Package
// PackageReference is the PackageReference that defines the function.
PackageReference PackageReference
// Token is the function's Pulumi type token.
Token string
// Comment is the description of the function, if any.
Comment string
// Inputs is the bag of input values for the function, if any.
Inputs *ObjectType
// Outputs is the bag of output values for the function, if any.
Outputs *ObjectType
// DeprecationMessage indicates whether or not the function is deprecated.
DeprecationMessage string
// Language specifies additional language-specific data about the function.
Language map[string]interface{}
// IsMethod indicates whether the function is a method of a resource.
IsMethod bool
// IsOverlay indicates whether the function is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
}
// Determines if codegen should emit a ${fn}Output version that
// automatically accepts Inputs and returns Outputs.
func (fun *Function) NeedsOutputVersion() bool {
// Skip functions that return no value. Arguably we could
// support them and return `Task`, but there are no such
// functions in `pulumi-azure-native` or `pulumi-aws` so we
// omit to simplify.
if fun.Outputs == nil || len(fun.Outputs.Properties) == 0 {
return false
}
// Skip functions that have no inputs. The user can simply
// lift the `Task` to `Output` manually.
if fun.Inputs == nil {
return false
}
// No properties is kind of like no inputs.
if len(fun.Inputs.Properties) == 0 {
return false
}
return true
}
// Package describes a Pulumi package.
type Package struct {
moduleFormat *regexp.Regexp
// Name is the unqualified name of the package (e.g. "aws", "azure", "gcp", "kubernetes". "random")
Name string
// DisplayName is the human-friendly name of the package.
DisplayName string
// Version is the version of the package.
Version *semver.Version
// Description is the description of the package.
Description string
// Keywords is the list of keywords that are associated with the package, if any.
// Some reserved keywords can be specified as well that help with categorizing the
// package in the Pulumi registry. `category/<name>` and `kind/<type>` are the only
// reserved keywords at this time, where `<name>` can be one of:
// `cloud`, `database`, `infrastructure`, `monitoring`, `network`, `utility`, `vcs`
// and `<type>` is either `native` or `component`. If the package is a bridged Terraform
// provider, then don't include the `kind/` label.
Keywords []string
// Homepage is the package's homepage.
Homepage string
// License indicates which license is used for the package's contents.
License string
// Attribution allows freeform text attribution of derived work, if needed.
Attribution string
// Repository is the URL at which the source for the package can be found.
Repository string
// LogoURL is the URL for the package's logo, if any.
LogoURL string
// PluginDownloadURL is the URL to use to acquire the provider plugin binary, if any.
PluginDownloadURL string
// Publisher is the name of the person or organization that authored and published the package.
Publisher string
// A list of allowed package name in addition to the Name property.
AllowedPackageNames []string
// Types is the list of non-resource types defined by the package.
Types []Type
// Config is the set of configuration properties defined by the package.
Config []*Property
// Provider is the resource provider for the package, if any.
Provider *Resource
// Resources is the list of resource types defined by the package.
Resources []*Resource
// Functions is the list of functions defined by the package.
Functions []*Function
// Language specifies additional language-specific data about the package.
Language map[string]interface{}
resourceTable map[string]*Resource
resourceTypeTable map[string]*ResourceType
functionTable map[string]*Function
typeTable map[string]Type
importedLanguages map[string]struct{}
}
// Language provides hooks for importing language-specific metadata in a package.
type Language interface {
// ImportDefaultSpec decodes language-specific metadata associated with a DefaultValue.
ImportDefaultSpec(def *DefaultValue, bytes json.RawMessage) (interface{}, error)
// ImportPropertySpec decodes language-specific metadata associated with a Property.
ImportPropertySpec(property *Property, bytes json.RawMessage) (interface{}, error)
// ImportObjectTypeSpec decodes language-specific metadata associated with a ObjectType.
ImportObjectTypeSpec(object *ObjectType, bytes json.RawMessage) (interface{}, error)
// ImportResourceSpec decodes language-specific metadata associated with a Resource.
ImportResourceSpec(resource *Resource, bytes json.RawMessage) (interface{}, error)
// ImportFunctionSpec decodes language-specific metadata associated with a Function.
ImportFunctionSpec(function *Function, bytes json.RawMessage) (interface{}, error)
// ImportPackageSpec decodes language-specific metadata associated with a Package.
ImportPackageSpec(pkg *Package, bytes json.RawMessage) (interface{}, error)
}
func sortedLanguageNames(metadata map[string]interface{}) []string {
names := make([]string, 0, len(metadata))
for lang := range metadata {
names = append(names, lang)
}
sort.Strings(names)
return names
}
func importDefaultLanguages(def *DefaultValue, languages map[string]Language) error {
for _, name := range sortedLanguageNames(def.Language) {
val := def.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportDefaultSpec(def, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
def.Language[name] = val
}
}
}
return nil
}
func importPropertyLanguages(property *Property, languages map[string]Language) error {
if property.DefaultValue != nil {
if err := importDefaultLanguages(property.DefaultValue, languages); err != nil {
return fmt.Errorf("importing default value: %w", err)
}
}
for _, name := range sortedLanguageNames(property.Language) {
val := property.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportPropertySpec(property, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
property.Language[name] = val
}
}
}
return nil
}
func importObjectTypeLanguages(object *ObjectType, languages map[string]Language) error {
for _, property := range object.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return fmt.Errorf("importing property %v: %w", property.Name, err)
}
}
for _, name := range sortedLanguageNames(object.Language) {
val := object.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportObjectTypeSpec(object, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
object.Language[name] = val
}
}
}
return nil
}
func importResourceLanguages(resource *Resource, languages map[string]Language) error {
for _, property := range resource.InputProperties {
if err := importPropertyLanguages(property, languages); err != nil {
return fmt.Errorf("importing input property %v: %w", property.Name, err)
}
}
for _, property := range resource.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return fmt.Errorf("importing property %v: %w", property.Name, err)
}
}
if resource.StateInputs != nil {
for _, property := range resource.StateInputs.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return fmt.Errorf("importing state input property %v: %w", property.Name, err)
}
}
}
for _, name := range sortedLanguageNames(resource.Language) {
val := resource.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportResourceSpec(resource, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
resource.Language[name] = val
}
}
}
return nil
}
func importFunctionLanguages(function *Function, languages map[string]Language) error {
if function.Inputs != nil {
if err := importObjectTypeLanguages(function.Inputs, languages); err != nil {
return fmt.Errorf("importing inputs: %w", err)
}
}
if function.Outputs != nil {
if err := importObjectTypeLanguages(function.Outputs, languages); err != nil {
return fmt.Errorf("importing outputs: %w", err)
}
}
for _, name := range sortedLanguageNames(function.Language) {
val := function.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportFunctionSpec(function, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
function.Language[name] = val
}
}
}
return nil
}
func (pkg *Package) ImportLanguages(languages map[string]Language) error {
if pkg.importedLanguages == nil {
pkg.importedLanguages = map[string]struct{}{}
}
any := false
for lang := range languages {
if _, ok := pkg.importedLanguages[lang]; !ok {
any = true
break
}
}
if !any {
return nil
}
for _, t := range pkg.Types {
if object, ok := t.(*ObjectType); ok {
if err := importObjectTypeLanguages(object, languages); err != nil {
return fmt.Errorf("importing object type %v: %w", object.Token, err)
}
}
}
for _, config := range pkg.Config {
if err := importPropertyLanguages(config, languages); err != nil {
return fmt.Errorf("importing configuration property %v: %w", config.Name, err)
}
}
if pkg.Provider != nil {
if err := importResourceLanguages(pkg.Provider, languages); err != nil {
return fmt.Errorf("importing provider: %w", err)
}
}
for _, resource := range pkg.Resources {
if err := importResourceLanguages(resource, languages); err != nil {
return fmt.Errorf("importing resource %v: %w", resource.Token, err)
}
}
for _, function := range pkg.Functions {
if err := importFunctionLanguages(function, languages); err != nil {
return fmt.Errorf("importing function %v: %w", function.Token, err)
}
}
for _, name := range sortedLanguageNames(pkg.Language) {
val := pkg.Language[name]
if raw, ok := val.(json.RawMessage); ok {
if lang, ok := languages[name]; ok {
val, err := lang.ImportPackageSpec(pkg, raw)
if err != nil {
return fmt.Errorf("importing %v metadata: %w", name, err)
}
pkg.Language[name] = val
}
}
}
for lang := range languages {
pkg.importedLanguages[lang] = struct{}{}
}
return nil
}
func packageIdentity(name string, version *semver.Version) string {
// The package's identity is its name and version (if any) separated buy a ':'. The ':' character is not allowed
// in package names and so is safe to use as a separator.
id := name + ":"
if version != nil {
return id + version.String()
}
return id
}
func (pkg *Package) Identity() string {
return packageIdentity(pkg.Name, pkg.Version)
}
func (pkg *Package) Equals(other *Package) bool {
return pkg == other || pkg.Identity() == other.Identity()
}
var defaultModuleFormat = regexp.MustCompile("(.*)")
func (pkg *Package) TokenToModule(tok string) string {
// token := pkg ":" module ":" member
components := strings.Split(tok, ":")
if len(components) != 3 {
return ""
}
switch components[1] {
case "providers":
return ""
default:
if pkg.moduleFormat == nil {
pkg.moduleFormat = defaultModuleFormat
}
matches := pkg.moduleFormat.FindStringSubmatch(components[1])
if len(matches) < 2 || strings.HasPrefix(matches[1], "index") {
return ""
}
return matches[1]
}
}
func TokenToRuntimeModule(tok string) string {
// token := pkg ":" module ":" member
components := strings.Split(tok, ":")
if len(components) != 3 {
return ""
}
return components[1]
}
func (pkg *Package) TokenToRuntimeModule(tok string) string {
return TokenToRuntimeModule(tok)
}
func (pkg *Package) GetResource(token string) (*Resource, bool) {
r, ok := pkg.resourceTable[token]
return r, ok
}
func (pkg *Package) GetFunction(token string) (*Function, bool) {
f, ok := pkg.functionTable[token]
return f, ok
}
func (pkg *Package) GetResourceType(token string) (*ResourceType, bool) {
t, ok := pkg.resourceTypeTable[token]
return t, ok
}
func (pkg *Package) GetType(token string) (Type, bool) {
t, ok := pkg.typeTable[token]
return t, ok
}
func (pkg *Package) Reference() PackageReference {
return packageDefRef{pkg: pkg}
}
func (pkg *Package) MarshalSpec() (spec *PackageSpec, err error) {
version := ""
if pkg.Version != nil {
version = pkg.Version.String()
}
var metadata *MetadataSpec
if pkg.moduleFormat != nil {
metadata = &MetadataSpec{ModuleFormat: pkg.moduleFormat.String()}
}
spec = &PackageSpec{
Name: pkg.Name,
Version: version,
DisplayName: pkg.DisplayName,
Publisher: pkg.Publisher,
Description: pkg.Description,
Keywords: pkg.Keywords,
Homepage: pkg.Homepage,
License: pkg.License,
Attribution: pkg.Attribution,
Repository: pkg.Repository,
LogoURL: pkg.LogoURL,
PluginDownloadURL: pkg.PluginDownloadURL,
Meta: metadata,
Types: map[string]ComplexTypeSpec{},
Resources: map[string]ResourceSpec{},
Functions: map[string]FunctionSpec{},
AllowedPackageNames: pkg.AllowedPackageNames,
}
lang, err := marshalLanguage(pkg.Language)
if err != nil {
return nil, fmt.Errorf("marshaling package language: %w", err)
}
spec.Language = lang
spec.Config.Required, spec.Config.Variables, err = pkg.marshalProperties(pkg.Config, true)
if err != nil {
return nil, fmt.Errorf("marshaling package config: %w", err)
}
spec.Provider, err = pkg.marshalResource(pkg.Provider)
if err != nil {
return nil, fmt.Errorf("marshaling provider: %w", err)
}
for _, t := range pkg.Types {
switch t := t.(type) {
case *ObjectType:
if t.IsInputShape() {
continue
}
// Use the input shape when marshaling in order to get the plain annotations right.
o, err := pkg.marshalObject(t.InputShape, false)
if err != nil {
return nil, fmt.Errorf("marshaling type '%v': %w", t.Token, err)
}
spec.Types[t.Token] = o
case *EnumType:
spec.Types[t.Token] = pkg.marshalEnum(t)
}