/
gen.go
2499 lines (2189 loc) 路 74.7 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 dotnet
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"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"
)
type typeDetails struct {
outputType bool
inputType bool
stateType bool
plainType bool
usedInFunctionOutputVersionInputs bool
}
// Title converts the input string to a title case
// where only the initial letter is upper-cased.
func Title(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
return string(append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...))
}
func csharpIdentifier(s string) string {
// Some schema field names may look like $ref or $schema. Remove the leading $ to make a valid identifier.
// This could lead to a clash if both `$foo` and `foo` are defined, but we don't try to de-duplicate now.
if strings.HasPrefix(s, "$") {
s = s[1:]
}
switch s {
case "abstract", "as", "base", "bool",
"break", "byte", "case", "catch",
"char", "checked", "class", "const",
"continue", "decimal", "default", "delegate",
"do", "double", "else", "enum",
"event", "explicit", "extern", "false",
"finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit",
"in", "int", "interface", "internal",
"is", "lock", "long", "namespace",
"new", "null", "object", "operator",
"out", "override", "params", "private",
"protected", "public", "readonly", "ref",
"return", "sbyte", "sealed", "short",
"sizeof", "stackalloc", "static", "string",
"struct", "switch", "this", "throw",
"true", "try", "typeof", "uint",
"ulong", "unchecked", "unsafe", "ushort",
"using", "virtual", "void", "volatile", "while":
return "@" + s
default:
return s
}
}
func isImmutableArrayType(t schema.Type, wrapInput bool) bool {
_, isArray := t.(*schema.ArrayType)
return isArray && !wrapInput
}
func isValueType(t schema.Type) bool {
switch t := t.(type) {
case *schema.OptionalType:
return isValueType(t.ElementType)
case *schema.EnumType:
return true
default:
switch t {
case schema.BoolType, schema.IntType, schema.NumberType:
return true
default:
return false
}
}
}
func namespaceName(namespaces map[string]string, name string) string {
if ns, ok := namespaces[name]; ok {
return ns
}
names := strings.Split(name, "-")
for i, name := range names {
names[i] = Title(name)
}
return strings.Join(names, "")
}
type modContext struct {
pkg *schema.Package
mod string
propertyNames map[*schema.Property]string
types []*schema.ObjectType
enums []*schema.EnumType
resources []*schema.Resource
functions []*schema.Function
typeDetails map[*schema.ObjectType]*typeDetails
children []*modContext
tool string
namespaceName string
namespaces map[string]string
compatibility string
dictionaryConstructors bool
// If types in the Input namespace are used.
fullyQualifiedInputs bool
// Determine whether to lift single-value method return values
liftSingleValueMethodReturns bool
// The root namespace to use, if any.
rootNamespace string
}
func (mod *modContext) RootNamespace() string {
if mod.rootNamespace != "" {
return mod.rootNamespace
}
return "Pulumi"
}
func (mod *modContext) propertyName(p *schema.Property) string {
if n, ok := mod.propertyNames[p]; ok {
return n
}
return Title(p.Name)
}
func (mod *modContext) details(t *schema.ObjectType) *typeDetails {
details, ok := mod.typeDetails[t]
if !ok {
details = &typeDetails{}
mod.typeDetails[t] = details
}
return details
}
func tokenToName(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "malformed token %v", tok)
return Title(components[2])
}
func resourceName(r *schema.Resource) string {
if r.IsProvider {
return "Provider"
}
return tokenToName(r.Token)
}
func tokenToFunctionName(tok string) string {
return tokenToName(tok)
}
func (mod *modContext) isK8sCompatMode() bool {
return mod.compatibility == "kubernetes20"
}
func (mod *modContext) isTFCompatMode() bool {
return mod.compatibility == "tfbridge20"
}
func (mod *modContext) tokenToNamespace(tok string, qualifier string) string {
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "malformed token %v", tok)
pkg, nsName := mod.RootNamespace()+"."+namespaceName(mod.namespaces, components[0]), mod.pkg.TokenToModule(tok)
if mod.isK8sCompatMode() {
if qualifier != "" {
return pkg + ".Types." + qualifier + "." + namespaceName(mod.namespaces, nsName)
}
}
typ := pkg
if nsName != "" {
typ += "." + namespaceName(mod.namespaces, nsName)
}
if qualifier != "" {
typ += "." + qualifier
}
return typ
}
func (mod *modContext) typeName(t *schema.ObjectType, state, input, args bool) string {
name := tokenToName(t.Token)
if state {
return name + "GetArgs"
}
if !mod.isTFCompatMode() && !mod.isK8sCompatMode() {
if args {
return name + "Args"
}
return name
}
switch {
case input && args && mod.details(t).usedInFunctionOutputVersionInputs:
return name + "InputArgs"
case input:
return name + "Args"
case mod.details(t).plainType:
return name + "Result"
}
return name
}
func isInputType(t schema.Type) bool {
if optional, ok := t.(*schema.OptionalType); ok {
t = optional.ElementType
}
_, isInputType := t.(*schema.InputType)
return isInputType
}
func ignoreOptional(t *schema.OptionalType, requireInitializers bool) bool {
switch t := t.ElementType.(type) {
case *schema.InputType:
switch t.ElementType.(type) {
case *schema.ArrayType, *schema.MapType:
return true
}
case *schema.ArrayType:
return !requireInitializers
}
return false
}
func simplifyInputUnion(union *schema.UnionType) *schema.UnionType {
elements := make([]schema.Type, len(union.ElementTypes))
for i, et := range union.ElementTypes {
if input, ok := et.(*schema.InputType); ok {
switch input.ElementType.(type) {
case *schema.ArrayType, *schema.MapType:
// Instead of just replacing Input<{Array,Map}<T>> with {Array,Map}<T>, replace it with
// {Array,Map}<Plain(T)>. This matches the behavior of typeString when presented with an
// Input<{Array,Map}<T>>.
elements[i] = codegen.PlainType(input.ElementType)
default:
elements[i] = input.ElementType
}
} else {
elements[i] = et
}
}
return &schema.UnionType{
ElementTypes: elements,
DefaultType: union.DefaultType,
Discriminator: union.Discriminator,
Mapping: union.Mapping,
}
}
func (mod *modContext) unionTypeString(t *schema.UnionType, qualifier string, input, wrapInput, state, requireInitializers bool) string {
elementTypeSet := codegen.StringSet{}
var elementTypes []string
for _, e := range t.ElementTypes {
// If this is an output and a "relaxed" enum, emit the type as the underlying primitive type rather than the union.
// Eg. Output<string> rather than Output<Union<EnumType, string>>
if typ, ok := e.(*schema.EnumType); ok && !input {
return mod.typeString(typ.ElementType, qualifier, input, state, requireInitializers)
}
et := mod.typeString(e, qualifier, input, state, false)
if !elementTypeSet.Has(et) {
elementTypeSet.Add(et)
elementTypes = append(elementTypes, et)
}
}
switch len(elementTypes) {
case 1:
if wrapInput {
return fmt.Sprintf("Input<%s>", elementTypes[0])
}
return elementTypes[0]
case 2:
unionT := "Union"
if wrapInput {
unionT = "InputUnion"
}
return fmt.Sprintf("%s<%s>", unionT, strings.Join(elementTypes, ", "))
default:
return "object"
}
}
func (mod *modContext) typeString(t schema.Type, qualifier string, input, state, requireInitializers bool) string {
switch t := t.(type) {
case *schema.OptionalType:
elem := mod.typeString(t.ElementType, qualifier, input, state, requireInitializers)
if ignoreOptional(t, requireInitializers) {
return elem
}
return elem + "?"
case *schema.InputType:
inputType := "Input"
elem := t.ElementType
switch e := t.ElementType.(type) {
case *schema.ArrayType:
inputType, elem = "InputList", codegen.PlainType(e.ElementType)
case *schema.MapType:
inputType, elem = "InputMap", codegen.PlainType(e.ElementType)
default:
if e == schema.JSONType {
return "InputJson"
}
}
if union, ok := elem.(*schema.UnionType); ok {
union = simplifyInputUnion(union)
if inputType == "Input" {
return mod.unionTypeString(union, qualifier, input, true, state, requireInitializers)
}
elem = union
}
return fmt.Sprintf("%s<%s>", inputType, mod.typeString(elem, qualifier, input, state, requireInitializers))
case *schema.EnumType:
return fmt.Sprintf("%s.%s", mod.tokenToNamespace(t.Token, ""), tokenToName(t.Token))
case *schema.ArrayType:
listType := "ImmutableArray"
if requireInitializers {
listType = "List"
}
return fmt.Sprintf("%v<%v>", listType, mod.typeString(t.ElementType, qualifier, input, state, false))
case *schema.MapType:
mapType := "ImmutableDictionary"
if requireInitializers {
mapType = "Dictionary"
}
return fmt.Sprintf("%v<string, %v>", mapType, mod.typeString(t.ElementType, qualifier, input, state, false))
case *schema.ObjectType:
namingCtx := mod
if t.Package != mod.pkg {
// If object type belongs to another package, we apply naming conventions from that package,
// including namespace naming and compatibility mode.
extPkg := t.Package
var info CSharpPackageInfo
contract.AssertNoError(extPkg.ImportLanguages(map[string]schema.Language{"csharp": Importer}))
if v, ok := t.Package.Language["csharp"].(CSharpPackageInfo); ok {
info = v
}
namingCtx = &modContext{
pkg: extPkg,
namespaces: info.Namespaces,
rootNamespace: info.GetRootNamespace(),
compatibility: info.Compatibility,
}
}
typ := namingCtx.tokenToNamespace(t.Token, qualifier)
if (typ == namingCtx.namespaceName && qualifier == "") || typ == namingCtx.namespaceName+"."+qualifier {
typ = qualifier
}
if typ == "Inputs" && mod.fullyQualifiedInputs {
typ = fmt.Sprintf("%s.Inputs", mod.namespaceName)
}
if typ != "" {
typ += "."
}
return typ + mod.typeName(t, state, input, t.IsInputShape())
case *schema.ResourceType:
if strings.HasPrefix(t.Token, "pulumi:providers:") {
pkgName := strings.TrimPrefix(t.Token, "pulumi:providers:")
return fmt.Sprintf("%s.%s.Provider", mod.RootNamespace(), namespaceName(mod.namespaces, pkgName))
}
namingCtx := mod
if t.Resource != nil && t.Resource.Package != mod.pkg {
// If resource type belongs to another package, we apply naming conventions from that package,
// including namespace naming and compatibility mode.
extPkg := t.Resource.Package
var info CSharpPackageInfo
contract.AssertNoError(extPkg.ImportLanguages(map[string]schema.Language{"csharp": Importer}))
if v, ok := t.Resource.Package.Language["csharp"].(CSharpPackageInfo); ok {
info = v
}
namingCtx = &modContext{
pkg: extPkg,
namespaces: info.Namespaces,
rootNamespace: info.GetRootNamespace(),
compatibility: info.Compatibility,
}
}
typ := namingCtx.tokenToNamespace(t.Token, "")
if typ != "" {
typ += "."
}
return typ + tokenToName(t.Token)
case *schema.TokenType:
// Use the underlying type for now.
if t.UnderlyingType != nil {
return mod.typeString(t.UnderlyingType, qualifier, input, state, requireInitializers)
}
typ := tokenToName(t.Token)
if ns := mod.tokenToNamespace(t.Token, qualifier); ns != mod.namespaceName {
typ = ns + "." + typ
}
return typ
case *schema.UnionType:
return mod.unionTypeString(t, qualifier, input, false, state, requireInitializers)
default:
switch t {
case schema.BoolType:
return "bool"
case schema.IntType:
return "int"
case schema.NumberType:
return "double"
case schema.StringType:
return "string"
case schema.ArchiveType:
return "Archive"
case schema.AssetType:
return "AssetOrArchive"
case schema.JSONType:
return "System.Text.Json.JsonElement"
case schema.AnyType:
return "object"
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
var docCommentEscaper = strings.NewReplacer(
`&`, "&",
`<`, "<",
`>`, ">",
)
func printComment(w io.Writer, comment, indent string) {
printCommentWithOptions(w, comment, indent, true /*escape*/)
}
func printCommentWithOptions(w io.Writer, comment, indent string, escape bool) {
if escape {
comment = docCommentEscaper.Replace(comment)
}
lines := strings.Split(comment, "\n")
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
if len(lines) > 0 {
fmt.Fprintf(w, "%s/// <summary>\n", indent)
for _, l := range lines {
fmt.Fprintf(w, "%s/// %s\n", indent, l)
}
fmt.Fprintf(w, "%s/// </summary>\n", indent)
}
}
type plainType struct {
mod *modContext
res *schema.Resource
name string
comment string
unescapeComment bool
baseClass string
propertyTypeQualifier string
properties []*schema.Property
args bool
state bool
internal bool
}
func (pt *plainType) genInputPropertyAttribute(w io.Writer, indent string, prop *schema.Property) {
wireName := prop.Name
attributeArgs := ""
if prop.IsRequired() {
attributeArgs = ", required: true"
}
if pt.res != nil && pt.res.IsProvider {
json := true
typ := codegen.UnwrapType(prop.Type)
if typ == schema.StringType {
json = false
} else if t, ok := typ.(*schema.TokenType); ok && t.UnderlyingType == schema.StringType {
json = false
}
if json {
attributeArgs += ", json: true"
}
}
fmt.Fprintf(w, "%s[Input(\"%s\"%s)]\n", indent, wireName, attributeArgs)
}
func (pt *plainType) genInputProperty(w io.Writer, prop *schema.Property, indent string, generateInputAttribute bool) {
propertyName := pt.mod.propertyName(prop)
propertyType := pt.mod.typeString(prop.Type, pt.propertyTypeQualifier, true, pt.state, false)
indent = strings.Repeat(indent, 2)
// Next generate the input property itself. The way this is generated depends on the type of the property:
// complex types like lists and maps need a backing field.
needsBackingField := false
switch codegen.UnwrapType(prop.Type).(type) {
case *schema.ArrayType, *schema.MapType:
needsBackingField = true
}
if prop.Secret {
needsBackingField = true
}
// Next generate the input property itself. The way this is generated depends on the type of the property:
// complex types like lists and maps need a backing field. Secret properties also require a backing field.
if needsBackingField {
backingFieldName := "_" + prop.Name
requireInitializers := !pt.args || !isInputType(prop.Type)
backingFieldType := pt.mod.typeString(codegen.RequiredType(prop), pt.propertyTypeQualifier, true, pt.state, requireInitializers)
if generateInputAttribute {
pt.genInputPropertyAttribute(w, indent, prop)
}
fmt.Fprintf(w, "%sprivate %s? %s;\n", indent, backingFieldType, backingFieldName)
if prop.Comment != "" {
fmt.Fprintf(w, "\n")
printComment(w, prop.Comment, indent)
}
printObsoleteAttribute(w, prop.DeprecationMessage, indent)
switch codegen.UnwrapType(prop.Type).(type) {
case *schema.ArrayType, *schema.MapType:
// Note that we use the backing field type--which is just the property type without any nullable annotation--to
// ensure that the user does not see warnings when initializing these properties using object or collection
// initializers.
fmt.Fprintf(w, "%spublic %s %s\n", indent, backingFieldType, propertyName)
fmt.Fprintf(w, "%s{\n", indent)
fmt.Fprintf(w, "%s get => %[2]s ?? (%[2]s = new %[3]s());\n", indent, backingFieldName, backingFieldType)
default:
fmt.Fprintf(w, "%spublic %s? %s\n", indent, backingFieldType, propertyName)
fmt.Fprintf(w, "%s{\n", indent)
fmt.Fprintf(w, "%s get => %s;\n", indent, backingFieldName)
}
if prop.Secret && isInputType(prop.Type) {
fmt.Fprintf(w, "%s set\n", indent)
fmt.Fprintf(w, "%s {\n", indent)
// Since we can't directly assign the Output from CreateSecret to the property, use an Output.All or
// Output.Tuple to enable the secret flag on the data. (If any input to the All/Tuple is secret, then the
// Output will also be secret.)
switch t := codegen.UnwrapType(prop.Type).(type) {
case *schema.ArrayType:
elemType := pt.mod.typeString(codegen.PlainType(t.ElementType), pt.propertyTypeQualifier, true, pt.state, false)
fmt.Fprintf(w, "%s var emptySecret = Output.CreateSecret(ImmutableArray.Create<%s>());\n", indent, elemType)
fmt.Fprintf(w, "%s %s = Output.All(value, emptySecret).Apply(v => v[0]);\n", indent, backingFieldName)
case *schema.MapType:
elemType := pt.mod.typeString(codegen.PlainType(t.ElementType), pt.propertyTypeQualifier, true, pt.state, false)
fmt.Fprintf(w, "%s var emptySecret = Output.CreateSecret(ImmutableDictionary.Create<string, %s>());\n", indent, elemType)
fmt.Fprintf(w, "%s %s = Output.All(value, emptySecret).Apply(v => v[0]);\n", indent, backingFieldName)
default:
fmt.Fprintf(w, "%s var emptySecret = Output.CreateSecret(0);\n", indent)
fmt.Fprintf(w, "%s %s = Output.Tuple<%s?, int>(value, emptySecret).Apply(t => t.Item1);\n", indent, backingFieldName, backingFieldType)
}
fmt.Fprintf(w, "%s }\n", indent)
} else {
fmt.Fprintf(w, "%s set => %s = value;\n", indent, backingFieldName)
}
fmt.Fprintf(w, "%s}\n", indent)
} else {
initializer := ""
if prop.IsRequired() && !isValueType(prop.Type) {
initializer = " = null!;"
}
printComment(w, prop.Comment, indent)
if generateInputAttribute {
pt.genInputPropertyAttribute(w, indent, prop)
}
fmt.Fprintf(w, "%spublic %s %s { get; set; }%s\n", indent, propertyType, propertyName, initializer)
}
}
// Set to avoid generating a class with the same name twice.
var generatedTypes = codegen.Set{}
func (pt *plainType) genInputType(w io.Writer, level int) error {
return pt.genInputTypeWithFlags(w, level, true /* generateInputAttributes */)
}
func (pt *plainType) genInputTypeWithFlags(w io.Writer, level int, generateInputAttributes bool) error {
// The way the legacy codegen for kubernetes is structured, inputs for a resource args type and resource args
// subtype could become a single class because of the name + namespace clash. We use a set of generated types
// to prevent generating classes with equal full names in multiple files. The check should be removed if we
// ever change the namespacing in the k8s SDK to the standard one.
if pt.mod.isK8sCompatMode() {
key := pt.mod.namespaceName + pt.name
if generatedTypes.Has(key) {
return nil
}
generatedTypes.Add(key)
}
indent := strings.Repeat(" ", level)
fmt.Fprintf(w, "\n")
sealed := "sealed "
if pt.mod.isK8sCompatMode() && (pt.res == nil || !pt.res.IsProvider) {
sealed = ""
}
// Open the class.
printCommentWithOptions(w, pt.comment, indent, !pt.unescapeComment)
var suffix string
if pt.baseClass != "" {
suffix = fmt.Sprintf(" : global::Pulumi.%s", pt.baseClass)
}
fmt.Fprintf(w, "%spublic %sclass %s%s\n", indent, sealed, pt.name, suffix)
fmt.Fprintf(w, "%s{\n", indent)
// Declare each input property.
for _, p := range pt.properties {
pt.genInputProperty(w, p, indent, generateInputAttributes)
fmt.Fprintf(w, "\n")
}
// Generate a constructor that will set default values.
fmt.Fprintf(w, "%s public %s()\n", indent, pt.name)
fmt.Fprintf(w, "%s {\n", indent)
for _, prop := range pt.properties {
if prop.DefaultValue != nil {
dv, err := pt.mod.getDefaultValue(prop.DefaultValue, prop.Type)
if err != nil {
return err
}
propertyName := pt.mod.propertyName(prop)
fmt.Fprintf(w, "%s %s = %s;\n", indent, propertyName, dv)
}
}
fmt.Fprintf(w, "%s }\n", indent)
// override Empty static property from inherited ResourceArgs
// and make it return a concrete args type instead of inherited ResourceArgs
fmt.Fprintf(w, "%s public static new %s Empty => new %s();\n", indent, pt.name, pt.name)
// Close the class.
fmt.Fprintf(w, "%s}\n", indent)
return nil
}
func (pt *plainType) genOutputType(w io.Writer, level int) {
indent := strings.Repeat(" ", level)
fmt.Fprintf(w, "\n")
// Open the class and attribute it appropriately.
printCommentWithOptions(w, pt.comment, indent, !pt.unescapeComment)
fmt.Fprintf(w, "%s[OutputType]\n", indent)
visibility := "public"
if pt.internal {
visibility = "internal"
}
fmt.Fprintf(w, "%s%s sealed class %s\n", indent, visibility, pt.name)
fmt.Fprintf(w, "%s{\n", indent)
// Generate each output field.
for _, prop := range pt.properties {
fieldName := pt.mod.propertyName(prop)
typ := prop.Type
if !prop.IsRequired() && pt.mod.isK8sCompatMode() {
typ = codegen.RequiredType(prop)
}
fieldType := pt.mod.typeString(typ, pt.propertyTypeQualifier, false, false, false)
printComment(w, prop.Comment, indent+" ")
fmt.Fprintf(w, "%s public readonly %s %s;\n", indent, fieldType, fieldName)
}
if len(pt.properties) > 0 {
fmt.Fprintf(w, "\n")
}
// Generate an appropriately-attributed constructor that will set this types' fields.
fmt.Fprintf(w, "%s [OutputConstructor]\n", indent)
fmt.Fprintf(w, "%s private %s(", indent, pt.name)
// Generate the constructor parameters.
for i, prop := range pt.properties {
paramName := csharpIdentifier(prop.Name)
typ := prop.Type
if !prop.IsRequired() && pt.mod.isK8sCompatMode() {
typ = codegen.RequiredType(prop)
}
paramType := pt.mod.typeString(typ, pt.propertyTypeQualifier, false, false, false)
terminator := ""
if i != len(pt.properties)-1 {
terminator = ",\n"
}
paramDef := fmt.Sprintf("%s %s%s", paramType, paramName, terminator)
if len(pt.properties) > 1 {
paramDef = fmt.Sprintf("\n%s %s", indent, paramDef)
}
fmt.Fprint(w, paramDef)
}
fmt.Fprintf(w, ")\n")
// Generate the constructor body.
fmt.Fprintf(w, "%s {\n", indent)
for _, prop := range pt.properties {
paramName := csharpIdentifier(prop.Name)
fieldName := pt.mod.propertyName(prop)
if fieldName == paramName {
// Avoid a no-op in case of field and property name collision.
fieldName = "this." + fieldName
}
fmt.Fprintf(w, "%s %s = %s;\n", indent, fieldName, paramName)
}
fmt.Fprintf(w, "%s }\n", indent)
// Close the class.
fmt.Fprintf(w, "%s}\n", indent)
}
func primitiveValue(value interface{}) (string, error) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.Interface {
v = v.Elem()
}
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
return "true", nil
}
return "false", nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return strconv.FormatInt(v.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return strconv.FormatUint(v.Uint(), 10), nil
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(v.Float(), 'f', -1, 64), nil
case reflect.String:
return fmt.Sprintf("%q", v.String()), nil
default:
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
func (mod *modContext) getDefaultValue(dv *schema.DefaultValue, t schema.Type) (string, error) {
t = codegen.UnwrapType(t)
var val string
if dv.Value != nil {
switch enum := t.(type) {
case *schema.EnumType:
enumName := tokenToName(enum.Token)
for _, e := range enum.Elements {
if e.Value != dv.Value {
continue
}
elName := e.Name
if elName == "" {
elName = fmt.Sprintf("%v", e.Value)
}
safeName, err := makeSafeEnumName(elName, enumName)
if err != nil {
return "", err
}
val = fmt.Sprintf("%s.%s.%s", mod.namespaceName, enumName, safeName)
break
}
if val == "" {
return "", fmt.Errorf("default value '%v' not found in enum '%s'", dv.Value, enumName)
}
default:
v, err := primitiveValue(dv.Value)
if err != nil {
return "", err
}
val = v
}
}
if len(dv.Environment) != 0 {
getType := ""
switch t {
case schema.BoolType:
getType = "Boolean"
case schema.IntType:
getType = "Int32"
case schema.NumberType:
getType = "Double"
}
envVars := fmt.Sprintf("%q", dv.Environment[0])
for _, e := range dv.Environment[1:] {
envVars += fmt.Sprintf(", %q", e)
}
getEnv := fmt.Sprintf("Utilities.GetEnv%s(%s)", getType, envVars)
if val != "" {
val = fmt.Sprintf("%s ?? %s", getEnv, val)
} else {
val = getEnv
}
}
return val, nil
}
func genAlias(w io.Writer, alias *schema.Alias) {
fmt.Fprintf(w, "new global::Pulumi.Alias { ")
parts := []string{}
if alias.Name != nil {
parts = append(parts, fmt.Sprintf("Name = \"%v\"", *alias.Name))
}
if alias.Project != nil {
parts = append(parts, fmt.Sprintf("Project = \"%v\"", *alias.Project))
}
if alias.Type != nil {
parts = append(parts, fmt.Sprintf("Type = \"%v\"", *alias.Type))
}
for i, part := range parts {
if i > 0 {
fmt.Fprintf(w, ", ")
}
fmt.Fprintf(w, "%s", part)
}
fmt.Fprintf(w, "}")
}
func (mod *modContext) genResource(w io.Writer, r *schema.Resource) error {
// Create a resource module file into which all of this resource's types will go.
name := resourceName(r)
// Open the namespace.
fmt.Fprintf(w, "namespace %s\n", mod.namespaceName)
fmt.Fprintf(w, "{\n")
// Write the documentation comment for the resource class
printComment(w, codegen.FilterExamples(r.Comment, "csharp"), " ")
// Open the class.
className := name
var baseType string
optionsType := "CustomResourceOptions"
switch {
case r.IsProvider:
baseType = "global::Pulumi.ProviderResource"
case mod.isK8sCompatMode():
baseType = "KubernetesResource"
case r.IsComponent:
baseType = "global::Pulumi.ComponentResource"
optionsType = "ComponentResourceOptions"
default:
baseType = "global::Pulumi.CustomResource"
}
if r.DeprecationMessage != "" {
fmt.Fprintf(w, " [Obsolete(@\"%s\")]\n", strings.Replace(r.DeprecationMessage, `"`, `""`, -1))
}
fmt.Fprintf(w, " [%sResourceType(\"%s\")]\n", namespaceName(mod.namespaces, mod.pkg.Name), r.Token)
fmt.Fprintf(w, " public partial class %s : %s\n", className, baseType)
fmt.Fprintf(w, " {\n")
var secretProps []string
// Emit all output properties.
for _, prop := range r.Properties {
// Write the property attribute
wireName := prop.Name
propertyName := mod.propertyName(prop)
typ := prop.Type
if !prop.IsRequired() && mod.isK8sCompatMode() {
typ = codegen.RequiredType(prop)
}
propertyType := mod.typeString(typ, "Outputs", false, false, false)
// Workaround the fact that provider inputs come back as strings.
if r.IsProvider && !schema.IsPrimitiveType(prop.Type) {
propertyType = "string"
if !prop.IsRequired() {
propertyType += "?"
}
}
if prop.Secret {
secretProps = append(secretProps, prop.Name)
}
printComment(w, prop.Comment, " ")
fmt.Fprintf(w, " [Output(\"%s\")]\n", wireName)
fmt.Fprintf(w, " public Output<%s> %s { get; private set; } = null!;\n", propertyType, propertyName)
fmt.Fprintf(w, "\n")
}
if len(r.Properties) > 0 {
fmt.Fprintf(w, "\n")
}
// Emit the class constructor.
argsClassName := className + "Args"
if mod.isK8sCompatMode() && !r.IsProvider {
argsClassName = fmt.Sprintf("%s.%sArgs", mod.tokenToNamespace(r.Token, "Inputs"), className)
}
argsType := argsClassName
var argsDefault string
allOptionalInputs := true
hasConstInputs := false
for _, prop := range r.InputProperties {
allOptionalInputs = allOptionalInputs && !prop.IsRequired()
hasConstInputs = hasConstInputs || prop.ConstValue != nil
}
if allOptionalInputs || mod.isK8sCompatMode() {
// If the number of required input properties was zero, we can make the args object optional.
argsDefault = " = null"
argsType += "?"
}
tok := r.Token
if r.IsProvider {
tok = mod.pkg.Name
}
argsOverride := fmt.Sprintf("args ?? new %sArgs()", className)
if hasConstInputs {
argsOverride = "MakeArgs(args)"
}
// Write a comment prior to the constructor.
fmt.Fprintf(w, " /// <summary>\n")
fmt.Fprintf(w, " /// Create a %s resource with the given unique name, arguments, and options.\n", className)
fmt.Fprintf(w, " /// </summary>\n")
fmt.Fprintf(w, " ///\n")
fmt.Fprintf(w, " /// <param name=\"name\">The unique name of the resource</param>\n")
fmt.Fprintf(w, " /// <param name=\"args\">The arguments used to populate this resource's properties</param>\n")
fmt.Fprintf(w, " /// <param name=\"options\">A bag of options that control this resource's behavior</param>\n")
fmt.Fprintf(w, " public %s(string name, %s args%s, %s? options = null)\n", className, argsType, argsDefault, optionsType)
if r.IsComponent {
fmt.Fprintf(w, " : base(\"%s\", name, %s, MakeResourceOptions(options, \"\"), remote: true)\n", tok, argsOverride)
} else {
fmt.Fprintf(w, " : base(\"%s\", name, %s, MakeResourceOptions(options, \"\"))\n", tok, argsOverride)
}
fmt.Fprintf(w, " {\n")
fmt.Fprintf(w, " }\n")
// Write a dictionary constructor.
if mod.dictionaryConstructors && !r.IsComponent {
fmt.Fprintf(w, " internal %s(string name, ImmutableDictionary<string, object?> dictionary, %s? options = null)\n",
className, optionsType)
if r.IsComponent {