-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gen.go
3921 lines (3422 loc) 路 120 KB
/
gen.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-2021, 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.
// Pulling out some of the repeated strings tokens into constants would harm readability, so we just ignore the
// goconst linter's warning.
//
// nolint: lll, goconst
package gen
import (
"bytes"
"fmt"
"go/format"
"io"
"os"
"path"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/cgstrings"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// A signifier that the module is external, and will never match.
//
// This token is always an invalid module since ':' is not allowed within modules.
const ExternalModuleSig = ":always-external:"
type typeDetails struct {
// Note: if any of {ptr,array,map}Input are set, input and the corresponding output field must also be set. The
// mark* functions ensure that these invariants hold.
input bool
ptrInput bool
arrayInput bool
mapInput bool
// Note: if any of {ptr,array,map}Output are set, output must also be set. The mark* functions ensure that these
// invariants hold.
output bool
ptrOutput bool
arrayOutput bool
mapOutput bool
}
func (d *typeDetails) hasOutputs() bool {
return d.output || d.ptrOutput || d.arrayOutput || d.mapOutput
}
func (d *typeDetails) mark(input, output bool) {
d.input = d.input || input
d.output = d.output || input || output
}
func (d *typeDetails) markPtr(input, output bool) {
d.mark(input, output)
d.ptrInput = d.ptrInput || input
d.ptrOutput = d.ptrOutput || input || output
}
func (d *typeDetails) markArray(input, output bool) {
d.mark(input, output)
d.arrayInput = d.arrayInput || input
d.arrayOutput = d.arrayOutput || input || output
}
func (d *typeDetails) markMap(input, output bool) {
d.mark(input, output)
d.mapInput = d.mapInput || input
d.mapOutput = d.mapOutput || input || output
}
// Title converts the input string to a title case
// where only the initial letter is upper-cased.
// It also removes $-prefix if any.
func Title(s string) string {
if s == "" {
return ""
}
if s[0] == '$' {
return Title(s[1:])
}
s = cgstrings.UppercaseFirst(s)
s = cgstrings.Unhyphenate(s)
return s
}
func tokenToPackage(pkg *schema.Package, overrides map[string]string, tok string) string {
mod := pkg.TokenToModule(tok)
if override, ok := overrides[mod]; ok {
mod = override
}
return strings.ToLower(mod)
}
// A threadsafe cache for sharing between invocations of GenerateProgram.
type Cache struct {
externalPackages map[*schema.Package]map[string]*pkgContext
m *sync.Mutex
}
var globalCache = NewCache()
func NewCache() *Cache {
return &Cache{
externalPackages: map[*schema.Package]map[string]*pkgContext{},
m: new(sync.Mutex),
}
}
func (c *Cache) lookupContextMap(pkg *schema.Package) (map[string]*pkgContext, bool) {
c.m.Lock()
defer c.m.Unlock()
m, ok := c.externalPackages[pkg]
return m, ok
}
func (c *Cache) setContextMap(pkg *schema.Package, m map[string]*pkgContext) {
c.m.Lock()
defer c.m.Unlock()
c.externalPackages[pkg] = m
}
type pkgContext struct {
pkg *schema.Package
mod string
importBasePath string
rootPackageName string
typeDetails map[schema.Type]*typeDetails
enums []*schema.EnumType
types []*schema.ObjectType
resources []*schema.Resource
functions []*schema.Function
// schemaNames tracks the names of types/resources as specified in the schema
schemaNames codegen.StringSet
names codegen.StringSet
renamed map[string]string
// A mapping between external packages and their bound contents.
externalPackages *Cache
// duplicateTokens tracks tokens that exist for both types and resources
duplicateTokens map[string]bool
functionNames map[*schema.Function]string
needsUtils bool
tool string
packages map[string]*pkgContext
// Name overrides set in GoPackageInfo
modToPkg map[string]string // Module name -> package name
pkgImportAliases map[string]string // Package name -> import alias
// Determines whether to make single-return-value methods return an output struct or the value
liftSingleValueMethodReturns bool
// Determines if we should emit type registration code
disableInputTypeRegistrations bool
// Determines if we should emit object defaults code
disableObjectDefaults bool
}
func (pkg *pkgContext) detailsForType(t schema.Type) *typeDetails {
if obj, ok := t.(*schema.ObjectType); ok && obj.IsInputShape() {
t = obj.PlainShape
}
details, ok := pkg.typeDetails[t]
if !ok {
details = &typeDetails{}
pkg.typeDetails[t] = details
}
return details
}
func (pkg *pkgContext) tokenToPackage(tok string) string {
return tokenToPackage(pkg.pkg, pkg.modToPkg, tok)
}
func (pkg *pkgContext) tokenToType(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "tok: %s", tok)
if pkg == nil {
panic(fmt.Errorf("pkg is nil. token %s", tok))
}
if pkg.pkg == nil {
panic(fmt.Errorf("pkg.pkg is nil. token %s", tok))
}
mod, name := pkg.tokenToPackage(tok), components[2]
name = Title(name)
if modPkg, ok := pkg.packages[mod]; ok {
newName, renamed := modPkg.renamed[name]
if renamed {
name = newName
} else if modPkg.duplicateTokens[strings.ToLower(tok)] {
// maintain support for duplicate tokens for types and resources in Kubernetes
name += "Type"
}
}
if mod == pkg.mod {
return name
}
if mod == "" {
mod = packageRoot(pkg.pkg)
}
var importPath string
if alias, hasAlias := pkg.pkgImportAliases[path.Join(pkg.importBasePath, mod)]; hasAlias {
importPath = alias
} else {
importPath = strings.ReplaceAll(mod, "/", "")
importPath = strings.ReplaceAll(importPath, "-", "")
}
return strings.ReplaceAll(importPath+"."+name, "-provider", "")
}
// Resolve a enum type to its name.
func (pkg *pkgContext) resolveEnumType(t *schema.EnumType) string {
if !pkg.isExternalReference(t) {
return pkg.tokenToEnum(t.Token)
}
extPkgCtx, _ := pkg.contextForExternalReference(t)
enumType := extPkgCtx.typeString(t)
return enumType
}
func (pkg *pkgContext) tokenToEnum(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assert(len(components) == 3)
if pkg == nil {
panic(fmt.Errorf("pkg is nil. token %s", tok))
}
if pkg.pkg == nil {
panic(fmt.Errorf("pkg.pkg is nil. token %s", tok))
}
mod, name := pkg.tokenToPackage(tok), components[2]
name = Title(name)
if modPkg, ok := pkg.packages[mod]; ok {
newName, renamed := modPkg.renamed[name]
if renamed {
name = newName
} else if modPkg.duplicateTokens[tok] {
// If the package containing the enum's token already has a resource or type with the
// same name, add an `Enum` suffix.
name += "Enum"
}
}
if mod == pkg.mod {
return name
}
if mod == "" {
mod = components[0]
}
var importPath string
if alias, hasAlias := pkg.pkgImportAliases[path.Join(pkg.importBasePath, mod)]; hasAlias {
importPath = alias
} else {
importPath = strings.ReplaceAll(mod, "/", "")
}
return importPath + "." + name
}
func (pkg *pkgContext) tokenToResource(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assert(len(components) == 3)
if pkg == nil {
panic(fmt.Errorf("pkg is nil. token %s", tok))
}
if pkg.pkg == nil {
panic(fmt.Errorf("pkg.pkg is nil. token %s", tok))
}
// Is it a provider resource?
if components[0] == "pulumi" && components[1] == "providers" {
return fmt.Sprintf("%s.Provider", components[2])
}
mod, name := pkg.tokenToPackage(tok), components[2]
name = Title(name)
if mod == pkg.mod {
return name
}
if mod == "" {
mod = components[0]
}
var importPath string
if alias, hasAlias := pkg.pkgImportAliases[path.Join(pkg.importBasePath, mod)]; hasAlias {
importPath = alias
} else {
importPath = strings.ReplaceAll(mod, "/", "")
}
return importPath + "." + name
}
func tokenToModule(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assert(len(components) == 3)
return components[1]
}
func tokenToName(tok string) string {
components := strings.Split(tok, ":")
contract.Assert(len(components) == 3)
return Title(components[2])
}
// disambiguatedResourceName gets the name of a resource as it should appear in source, resolving conflicts in the process.
func disambiguatedResourceName(r *schema.Resource, pkg *pkgContext) string {
name := rawResourceName(r)
if renamed, ok := pkg.renamed[name]; ok {
name = renamed
}
return name
}
// rawResourceName produces raw resource name translated from schema type token without resolving conflicts or dupes.
func rawResourceName(r *schema.Resource) string {
if r.IsProvider {
return "Provider"
}
return tokenToName(r.Token)
}
// If `nil` is a valid value of type `t`.
func isNilType(t schema.Type) bool {
switch t := t.(type) {
case *schema.OptionalType, *schema.ArrayType, *schema.MapType, *schema.ResourceType, *schema.InputType:
return true
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return isNilType(t.UnderlyingType)
}
case *schema.UnionType:
// If the union is actually a relaxed enum type, use the underlying
// type for the enum instead
for _, e := range t.ElementTypes {
if typ, ok := e.(*schema.EnumType); ok {
return isNilType(typ.ElementType)
}
}
default:
switch t {
case schema.ArchiveType, schema.AssetType, schema.JSONType, schema.AnyType:
return true
}
}
return false
}
func (pkg *pkgContext) inputType(t schema.Type) (result string) {
switch t := codegen.SimplifyInputUnion(t).(type) {
case *schema.OptionalType:
return pkg.typeString(t)
case *schema.InputType:
return pkg.inputType(t.ElementType)
case *schema.EnumType:
// Since enum type is itself an input
return pkg.resolveEnumType(t) + "Input"
case *schema.ArrayType:
en := pkg.inputType(t.ElementType)
return strings.TrimSuffix(en, "Input") + "ArrayInput"
case *schema.MapType:
en := pkg.inputType(t.ElementType)
return strings.TrimSuffix(en, "Input") + "MapInput"
case *schema.ObjectType:
if t.IsInputShape() {
t = t.PlainShape
}
return pkg.resolveObjectType(t) + "Input"
case *schema.ResourceType:
return pkg.resolveResourceType(t) + "Input"
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return pkg.inputType(t.UnderlyingType)
}
return pkg.tokenToType(t.Token) + "Input"
case *schema.UnionType:
// If the union is actually a relaxed enum type, use the underlying
// type for the input instead
for _, e := range t.ElementTypes {
if typ, ok := e.(*schema.EnumType); ok {
return pkg.inputType(typ.ElementType)
}
}
// TODO(pdg): union types
return "pulumi.Input"
default:
switch t {
case schema.BoolType:
return "pulumi.BoolInput"
case schema.IntType:
return "pulumi.IntInput"
case schema.NumberType:
return "pulumi.Float64Input"
case schema.StringType:
return "pulumi.StringInput"
case schema.ArchiveType:
return "pulumi.ArchiveInput"
case schema.AssetType:
return "pulumi.AssetOrArchiveInput"
case schema.JSONType:
fallthrough
case schema.AnyType:
return "pulumi.Input"
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
func (pkg *pkgContext) argsTypeImpl(t schema.Type) (result string) {
switch t := codegen.SimplifyInputUnion(t).(type) {
case *schema.OptionalType:
return pkg.typeStringImpl(t, true)
case *schema.InputType:
return pkg.argsTypeImpl(t.ElementType)
case *schema.EnumType:
// Since enum type is itself an input
return pkg.resolveEnumType(t)
case *schema.ArrayType:
en := pkg.argsTypeImpl(t.ElementType)
return strings.TrimSuffix(en, "Args") + "Array"
case *schema.MapType:
en := pkg.argsTypeImpl(t.ElementType)
return strings.TrimSuffix(en, "Args") + "Map"
case *schema.ObjectType:
return pkg.resolveObjectType(t)
case *schema.ResourceType:
return pkg.resolveResourceType(t)
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return pkg.argsTypeImpl(t.UnderlyingType)
}
return pkg.tokenToType(t.Token)
case *schema.UnionType:
// If the union is actually a relaxed enum type, use the underlying
// type for the input instead
for _, e := range t.ElementTypes {
if typ, ok := e.(*schema.EnumType); ok {
return pkg.argsTypeImpl(typ.ElementType)
}
}
return "pulumi.Any"
default:
switch t {
case schema.BoolType:
return "pulumi.Bool"
case schema.IntType:
return "pulumi.Int"
case schema.NumberType:
return "pulumi.Float64"
case schema.StringType:
return "pulumi.String"
case schema.ArchiveType:
return "pulumi.Archive"
case schema.AssetType:
return "pulumi.AssetOrArchive"
case schema.JSONType:
fallthrough
case schema.AnyType:
return "pulumi.Any"
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
func (pkg *pkgContext) argsType(t schema.Type) string {
return pkg.typeStringImpl(t, true)
}
func (pkg *pkgContext) typeStringImpl(t schema.Type, argsType bool) string {
switch t := t.(type) {
case *schema.OptionalType:
if input, isInputType := t.ElementType.(*schema.InputType); isInputType {
elem := pkg.inputType(input.ElementType)
if isNilType(input.ElementType) || elem == "pulumi.Input" {
return elem
}
if pkg.isExternalReference(input.ElementType) {
_, details := pkg.contextForExternalReference(input.ElementType)
switch input.ElementType.(type) {
case *schema.ObjectType:
if !details.ptrInput {
return "*" + elem
}
case *schema.EnumType:
if !(details.ptrInput || details.input) {
return "*" + elem
}
}
}
if argsType {
return elem + "Ptr"
}
return strings.TrimSuffix(elem, "Input") + "PtrInput"
}
elementType := pkg.typeStringImpl(t.ElementType, argsType)
if isNilType(t.ElementType) || elementType == "interface{}" {
return elementType
}
return "*" + elementType
case *schema.InputType:
if argsType {
return pkg.argsTypeImpl(t.ElementType)
}
return pkg.inputType(t.ElementType)
case *schema.EnumType:
return pkg.resolveEnumType(t)
case *schema.ArrayType:
typ := "[]"
return typ + pkg.typeStringImpl(t.ElementType, argsType)
case *schema.MapType:
typ := "map[string]"
return typ + pkg.typeStringImpl(t.ElementType, argsType)
case *schema.ObjectType:
return pkg.resolveObjectType(t)
case *schema.ResourceType:
return "*" + pkg.resolveResourceType(t)
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return pkg.typeStringImpl(t.UnderlyingType, argsType)
}
return pkg.tokenToType(t.Token)
case *schema.UnionType:
// If the union is actually a relaxed enum type, use the underlying
// type for the enum instead
for _, e := range t.ElementTypes {
if typ, ok := e.(*schema.EnumType); ok {
return pkg.typeStringImpl(typ.ElementType, argsType)
}
}
// TODO(pdg): union types
return "interface{}"
default:
switch t {
case schema.BoolType:
return "bool"
case schema.IntType:
return "int"
case schema.NumberType:
return "float64"
case schema.StringType:
return "string"
case schema.ArchiveType:
return "pulumi.Archive"
case schema.AssetType:
return "pulumi.AssetOrArchive"
case schema.JSONType:
fallthrough
case schema.AnyType:
return "interface{}"
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
func (pkg *pkgContext) typeString(t schema.Type) string {
s := pkg.typeStringImpl(t, false)
if s == "pulumi." {
return "pulumi.Any"
}
return s
}
func (pkg *pkgContext) isExternalReference(t schema.Type) bool {
isExternal, _, _ := pkg.isExternalReferenceWithPackage(t)
return isExternal
}
// Return if `t` is external to `pkg`. If so, the associated foreign schema.Package is returned.
func (pkg *pkgContext) isExternalReferenceWithPackage(t schema.Type) (
isExternal bool, extPkg *schema.Package, token string) {
var err error
switch typ := t.(type) {
case *schema.ObjectType:
isExternal = typ.Package != nil && pkg.pkg != nil && typ.Package != pkg.pkg
if isExternal {
extPkg, err = typ.PackageReference.Definition()
contract.AssertNoError(err)
token = typ.Token
}
return
case *schema.ResourceType:
isExternal = typ.Resource != nil && pkg.pkg != nil && typ.Resource.Package != pkg.pkg
if isExternal {
extPkg, err = typ.Resource.PackageReference.Definition()
contract.AssertNoError(err)
token = typ.Token
}
return
case *schema.EnumType:
isExternal = pkg.pkg != nil && typ.Package != pkg.pkg
if isExternal {
extPkg, err = typ.PackageReference.Definition()
contract.AssertNoError(err)
token = typ.Token
}
return
}
return
}
// resolveResourceType resolves resource references in properties while
// taking into account potential external resources. Returned type is
// always marked as required. Caller should check if the property is
// optional and convert the type to a pointer if necessary.
func (pkg *pkgContext) resolveResourceType(t *schema.ResourceType) string {
if !pkg.isExternalReference(t) {
return pkg.tokenToResource(t.Token)
}
extPkgCtx, _ := pkg.contextForExternalReference(t)
resType := extPkgCtx.tokenToResource(t.Token)
if !strings.Contains(resType, ".") {
resType = fmt.Sprintf("%s.%s", extPkgCtx.pkg.Name, resType)
}
return resType
}
// resolveObjectType resolves resource references in properties while
// taking into account potential external resources. Returned type is
// always marked as required. Caller should check if the property is
// optional and convert the type to a pointer if necessary.
func (pkg *pkgContext) resolveObjectType(t *schema.ObjectType) string {
isExternal, _, _ := pkg.isExternalReferenceWithPackage(t)
if !isExternal {
name := pkg.tokenToType(t.Token)
if t.IsInputShape() {
return name + "Args"
}
return name
}
extPkg, _ := pkg.contextForExternalReference(t)
return extPkg.typeString(t)
}
func (pkg *pkgContext) contextForExternalReference(t schema.Type) (*pkgContext, typeDetails) {
isExternal, extPkg, token := pkg.isExternalReferenceWithPackage(t)
contract.Assert(isExternal)
var goInfo GoPackageInfo
contract.AssertNoError(extPkg.ImportLanguages(map[string]schema.Language{"go": Importer}))
if info, ok := extPkg.Language["go"].(GoPackageInfo); ok {
goInfo = info
} else {
goInfo.ImportBasePath = extractImportBasePath(extPkg)
}
pkgImportAliases := goInfo.PackageImportAliases
// Ensure that any package import aliases we have specified locally take precedence over those
// specified in the remote package.
if ourPkgGoInfoI, has := pkg.pkg.Language["go"]; has {
ourPkgGoInfo := ourPkgGoInfoI.(GoPackageInfo)
if len(ourPkgGoInfo.PackageImportAliases) > 0 {
pkgImportAliases = make(map[string]string)
// Copy the external import aliases.
for k, v := range goInfo.PackageImportAliases {
pkgImportAliases[k] = v
}
// Copy the local import aliases, overwriting any external aliases.
for k, v := range ourPkgGoInfo.PackageImportAliases {
pkgImportAliases[k] = v
}
}
}
var maps map[string]*pkgContext
if extMap, ok := pkg.externalPackages.lookupContextMap(extPkg); ok {
maps = extMap
} else {
maps = generatePackageContextMap(pkg.tool, extPkg, goInfo, pkg.externalPackages)
pkg.externalPackages.setContextMap(extPkg, maps)
}
extPkgCtx := maps[""]
extPkgCtx.pkgImportAliases = pkgImportAliases
extPkgCtx.externalPackages = pkg.externalPackages
mod := tokenToPackage(extPkg, goInfo.ModuleToPackage, token)
extPkgCtx.mod = ExternalModuleSig
return extPkgCtx, *maps[mod].detailsForType(t)
}
// outputTypeImpl does the meat of the generation of output type names from schema types. This function should only be
// called with a fully-resolved type (e.g. the result of codegen.ResolvedType). Instead of calling this function, you
// probably want to call pkgContext.outputType, which ensures that its argument is resolved.
func (pkg *pkgContext) outputTypeImpl(t schema.Type) string {
switch t := t.(type) {
case *schema.OptionalType:
elem := pkg.outputTypeImpl(t.ElementType)
if isNilType(t.ElementType) || elem == "pulumi.AnyOutput" {
return elem
}
if pkg.isExternalReference(t.ElementType) {
_, details := pkg.contextForExternalReference(t.ElementType)
switch t.ElementType.(type) {
case *schema.ObjectType:
if !details.ptrOutput {
return "*" + elem
}
case *schema.EnumType:
if !(details.ptrOutput || details.output) {
return "*" + elem
}
}
}
return strings.TrimSuffix(elem, "Output") + "PtrOutput"
case *schema.EnumType:
return pkg.resolveEnumType(t) + "Output"
case *schema.ArrayType:
en := strings.TrimSuffix(pkg.outputTypeImpl(t.ElementType), "Output")
if en == "pulumi.Any" {
return "pulumi.ArrayOutput"
}
return en + "ArrayOutput"
case *schema.MapType:
en := strings.TrimSuffix(pkg.outputTypeImpl(t.ElementType), "Output")
if en == "pulumi.Any" {
return "pulumi.MapOutput"
}
return en + "MapOutput"
case *schema.ObjectType:
return pkg.resolveObjectType(t) + "Output"
case *schema.ResourceType:
return pkg.resolveResourceType(t) + "Output"
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return pkg.outputTypeImpl(t.UnderlyingType)
}
return pkg.tokenToType(t.Token) + "Output"
case *schema.UnionType:
// If the union is actually a relaxed enum type, use the underlying
// type for the output instead
for _, e := range t.ElementTypes {
if typ, ok := e.(*schema.EnumType); ok {
return pkg.outputTypeImpl(typ.ElementType)
}
}
// TODO(pdg): union types
return "pulumi.AnyOutput"
case *schema.InputType:
// We can't make output types for input types. We instead strip the input and try again.
return pkg.outputTypeImpl(t.ElementType)
default:
switch t {
case schema.BoolType:
return "pulumi.BoolOutput"
case schema.IntType:
return "pulumi.IntOutput"
case schema.NumberType:
return "pulumi.Float64Output"
case schema.StringType:
return "pulumi.StringOutput"
case schema.ArchiveType:
return "pulumi.ArchiveOutput"
case schema.AssetType:
return "pulumi.AssetOrArchiveOutput"
case schema.JSONType:
fallthrough
case schema.AnyType:
return "pulumi.AnyOutput"
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
// outputType returns a reference to the Go output type that corresponds to the given schema type. For example, given
// a schema.String, outputType returns "pulumi.String", and given a *schema.ObjectType with the token pkg:mod:Name,
// outputType returns "mod.NameOutput" or "NameOutput", depending on whether or not the object type lives in a
// different module than the one associated with the receiver.
func (pkg *pkgContext) outputType(t schema.Type) string {
return pkg.outputTypeImpl(codegen.ResolvedType(t))
}
// toOutputMethod returns the name of the "ToXXXOutput" method for the given schema type. For example, given a
// schema.String, toOutputMethod returns "ToStringOutput", and given a *schema.ObjectType with the token pkg:mod:Name,
// outputType returns "ToNameOutput".
func (pkg *pkgContext) toOutputMethod(t schema.Type) string {
outputTypeName := pkg.outputType(t)
if i := strings.LastIndexByte(outputTypeName, '.'); i != -1 {
outputTypeName = outputTypeName[i+1:]
}
return "To" + outputTypeName
}
func printComment(w io.Writer, comment string, indent bool) int {
comment = codegen.FilterExamples(comment, "go")
lines := strings.Split(comment, "\n")
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
for _, l := range lines {
if indent {
fmt.Fprintf(w, "\t")
}
if l == "" {
fmt.Fprintf(w, "//\n")
} else {
fmt.Fprintf(w, "// %s\n", l)
}
}
return len(lines)
}
func printCommentWithDeprecationMessage(w io.Writer, comment, deprecationMessage string, indent bool) {
lines := printComment(w, comment, indent)
if deprecationMessage != "" {
if lines > 0 {
fmt.Fprintf(w, "//\n")
}
printComment(w, fmt.Sprintf("Deprecated: %s", deprecationMessage), indent)
}
}
func (pkg *pkgContext) genInputInterface(w io.Writer, name string) {
printComment(w, pkg.getInputUsage(name), false)
fmt.Fprintf(w, "type %sInput interface {\n", name)
fmt.Fprintf(w, "\tpulumi.Input\n\n")
fmt.Fprintf(w, "\tTo%sOutput() %sOutput\n", Title(name), name)
fmt.Fprintf(w, "\tTo%sOutputWithContext(context.Context) %sOutput\n", Title(name), name)
fmt.Fprintf(w, "}\n\n")
}
func (pkg *pkgContext) getUsageForNestedType(name, baseTypeName string) string {
const defaultExampleFormat = "%sArgs{...}"
example := fmt.Sprintf(defaultExampleFormat, baseTypeName)
trimmer := func(typeName string) string {
if strings.HasSuffix(typeName, "Array") {
return typeName[:strings.LastIndex(typeName, "Array")]
}
if strings.HasSuffix(typeName, "Map") {
return typeName[:strings.LastIndex(typeName, "Map")]
}
return typeName
}
// If not a nested collection type, use the default example format
if trimmer(name) == name {
return example
}
if strings.HasSuffix(name, "Map") {
if pkg.schemaNames.Has(baseTypeName) {
return fmt.Sprintf("%s{ \"key\": %s }", name, example)
}
return fmt.Sprintf("%s{ \"key\": %s }", name, pkg.getUsageForNestedType(baseTypeName, trimmer(baseTypeName)))
}
if strings.HasSuffix(name, "Array") {
if pkg.schemaNames.Has(baseTypeName) {
return fmt.Sprintf("%s{ %s }", name, example)
}
return fmt.Sprintf("%s{ %s }", name, pkg.getUsageForNestedType(baseTypeName, trimmer(baseTypeName)))
}
return example
}
func (pkg *pkgContext) getInputUsage(name string) string {
if strings.HasSuffix(name, "Array") {
baseTypeName := name[:strings.LastIndex(name, "Array")]
return strings.Join([]string{
fmt.Sprintf("%sInput is an input type that accepts %s and %sOutput values.", name, name, name),
fmt.Sprintf("You can construct a concrete instance of `%sInput` via:", name),
"",
"\t\t " + pkg.getUsageForNestedType(name, baseTypeName),
" ",
}, "\n")
}
if strings.HasSuffix(name, "Map") {
baseTypeName := name[:strings.LastIndex(name, "Map")]
return strings.Join([]string{
fmt.Sprintf("%sInput is an input type that accepts %s and %sOutput values.", name, name, name),
fmt.Sprintf("You can construct a concrete instance of `%sInput` via:", name),
"",
"\t\t " + pkg.getUsageForNestedType(name, baseTypeName),
" ",
}, "\n")
}
if strings.HasSuffix(name, "Ptr") {
baseTypeName := name[:strings.LastIndex(name, "Ptr")]
return strings.Join([]string{
fmt.Sprintf("%sInput is an input type that accepts %sArgs, %s and %sOutput values.", name, baseTypeName, name, name),
fmt.Sprintf("You can construct a concrete instance of `%sInput` via:", name),
"",
fmt.Sprintf("\t\t %sArgs{...}", baseTypeName),
"",
" or:",
"",
"\t\t nil",
" ",
}, "\n")
}
return strings.Join([]string{
fmt.Sprintf("%sInput is an input type that accepts %sArgs and %sOutput values.", name, name, name),
fmt.Sprintf("You can construct a concrete instance of `%sInput` via:", name),
"",
fmt.Sprintf("\t\t %sArgs{...}", name),
" ",
}, "\n")
}
type genInputImplementationArgs struct {
name string
receiverType string
elementType string
ptrMethods bool
toOutputMethods bool
}
func genInputImplementation(w io.Writer, name, receiverType, elementType string, ptrMethods bool) {
genInputImplementationWithArgs(w, genInputImplementationArgs{
name: name,
receiverType: receiverType,
elementType: elementType,
ptrMethods: ptrMethods,
toOutputMethods: true,
})
}
func genInputImplementationWithArgs(w io.Writer, genArgs genInputImplementationArgs) {
name := genArgs.name
receiverType := genArgs.receiverType
elementType := genArgs.elementType
fmt.Fprintf(w, "func (%s) ElementType() reflect.Type {\n", receiverType)
fmt.Fprintf(w, "\treturn reflect.TypeOf((*%s)(nil)).Elem()\n", elementType)
fmt.Fprintf(w, "}\n\n")
if genArgs.toOutputMethods {
fmt.Fprintf(w, "func (i %s) To%sOutput() %sOutput {\n", receiverType, Title(name), name)
fmt.Fprintf(w, "\treturn i.To%sOutputWithContext(context.Background())\n", Title(name))
fmt.Fprintf(w, "}\n\n")
fmt.Fprintf(w, "func (i %s) To%sOutputWithContext(ctx context.Context) %sOutput {\n", receiverType, Title(name), name)
fmt.Fprintf(w, "\treturn pulumi.ToOutputWithContext(ctx, i).(%sOutput)\n", name)
fmt.Fprintf(w, "}\n\n")
}