-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gen.go
1878 lines (1661 loc) 路 52.4 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
//go:generate go run bundler.go
// Copyright 2016-2020, 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 docs
import (
"bytes"
"fmt"
"html"
"html/template"
"path"
"sort"
"strings"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/dotnet"
go_gen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
"github.com/pulumi/pulumi/pkg/v3/codegen/nodejs"
"github.com/pulumi/pulumi/pkg/v3/codegen/python"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
var (
supportedLanguages = []string{"csharp", "go", "nodejs", "python"}
snippetLanguages = []string{"csharp", "go", "python", "typescript"}
templates *template.Template
packagedTemplates map[string][]byte
docHelpers map[string]codegen.DocLanguageHelper
// The following property case maps are for rendering property
// names of nested properties in Python language with the correct
// casing.
snakeCaseToCamelCase map[string]string
camelCaseToSnakeCase map[string]string
seenCasingTypes codegen.Set
// The language-specific info objects for a certain package (provider).
goPkgInfo go_gen.GoPackageInfo
csharpPkgInfo dotnet.CSharpPackageInfo
nodePkgInfo nodejs.NodePackageInfo
pythonPkgInfo python.PackageInfo
// langModuleNameLookup is a map of module name to its language-specific
// name.
langModuleNameLookup map[string]string
// titleLookup is a map to map module package name to the desired display name
// for display in the TOC menu under API Reference.
titleLookup = map[string]string{
"aiven": "Aiven",
"akamai": "Akamai",
"alicloud": "AliCloud",
"auth0": "Auth0",
"aws": "AWS",
"azure": "Azure Classic",
"azure-native": "Azure Native",
"azuread": "Azure AD",
"azuredevops": "Azure DevOps",
"azuresel": "Azure",
"civo": "Civo",
"cloudamqp": "CloudAMQP",
"cloudflare": "Cloudflare",
"cloudinit": "cloud-init",
"consul": "Consul",
"datadog": "Datadog",
"digitalocean": "DigitalOcean",
"dnsimple": "DNSimple",
"docker": "Docker",
"eks": "EKS",
"f5bigip": "f5 BIG-IP",
"fastly": "Fastly",
"gcp": "GCP",
"google-native": "Google Native (preview)",
"github": "GitHub",
"gitlab": "GitLab",
"hcloud": "Hetzner Cloud",
"kafka": "Kafka",
"keycloak": "Keycloak",
"kong": "Kong",
"kubernetes": "Kubernetes",
"linode": "Linode",
"mailgun": "Mailgun",
"mongodbatlas": "MongoDB Atlas",
"mysql": "MySQL",
"newrelic": "New Relic",
"ns1": "NS1",
"okta": "Okta",
"openstack": "Open Stack",
"opsgenie": "Opsgenie",
"packet": "Packet",
"pagerduty": "PagerDuty",
"postgresql": "PostgreSQL",
"rabbitmq": "RabbitMQ",
"rancher2": "Rancher 2",
"random": "Random",
"signalfx": "SignalFx",
"spotinst": "Spotinst",
"tls": "TLS",
"vault": "Vault",
"venafi": "Venafi",
"vsphere": "vSphere",
"wavefront": "Wavefront",
"equinix-metal": "Equinix Metal",
"splunk": "Splunk",
"yandex": "Yandex",
"rke": "Rancher RKE",
"sumologic": "SumoLogic",
}
// Property anchor tag separator, used in a property anchor tag id to separate the
// property and language (e.g. property~lang).
propertyLangSeparator = "_"
)
func init() {
docHelpers = make(map[string]codegen.DocLanguageHelper)
for _, lang := range supportedLanguages {
switch lang {
case "csharp":
docHelpers[lang] = &dotnet.DocLanguageHelper{}
case "go":
docHelpers[lang] = &go_gen.DocLanguageHelper{}
case "nodejs":
docHelpers[lang] = &nodejs.DocLanguageHelper{}
case "python":
docHelpers[lang] = &python.DocLanguageHelper{}
}
}
snakeCaseToCamelCase = map[string]string{}
camelCaseToSnakeCase = map[string]string{}
seenCasingTypes = codegen.Set{}
langModuleNameLookup = map[string]string{}
}
type typeDetails struct {
inputType bool
}
// header represents the header of each resource markdown file.
type header struct {
Title string
TitleTag string
MetaDesc string
}
// property represents an input or an output property.
type property struct {
// ID is the `id` attribute that will be attached to the DOM element containing the property.
ID string
// DisplayName is the property name with word-breaks.
DisplayName string
Name string
Comment string
Types []propertyType
DeprecationMessage string
Link string
IsRequired bool
IsInput bool
}
// enum represents an enum.
type enum struct {
ID string // ID is the `id` attribute attached to the DOM element containing the enum.
DisplayName string // DisplayName is the enum name with word-breaks.
Name string // Name is the language-specific enum name.
Value string
Comment string
DeprecationMessage string
}
// docNestedType represents a complex type.
type docNestedType struct {
Name string
AnchorID string
Properties map[string][]property
EnumValues map[string][]enum
}
// propertyType represents the type of a property.
type propertyType struct {
DisplayName string
DescriptionName string // Name used in description list.
Name string
// Link can be a link to an anchor tag on the same
// page, or to another page/site.
Link string
}
// paramSeparator is for data passed to the separator template.
type paramSeparator struct {
Indent string
}
// formalParam represents the formal parameters of a constructor
// or a lookup function.
type formalParam struct {
Name string
Type propertyType
// This is the language specific optional type indicator.
// For example, in nodejs this is the character "?" and in Go
// it's "*".
OptionalFlag string
DefaultValue string
// Comment is an optional description of the parameter.
Comment string
}
type packageDetails struct {
Repository string
License string
Notes string
Version string
}
type resourceDocArgs struct {
Header header
Tool string
// LangChooserLanguages is a comma-separated list of languages to pass to the
// language chooser shortcode. Use this to customize the languages shown for a
// resource. By default, the language chooser will show all languages supported
// by Pulumi for all resources.
LangChooserLanguages string
// Comment represents the introductory resource comment.
Comment string
ExamplesSection []exampleSection
DeprecationMessage string
// Import
ImportDocs string
// ConstructorParams is a map from language to the rendered HTML for the constructor's
// arguments.
ConstructorParams map[string]string
// ConstructorParamsTyped is the typed set of parameters for the constructor, in order.
ConstructorParamsTyped map[string][]formalParam
// ConstructorResource is the resource that is being constructed or
// is the result of a constructor-like function.
ConstructorResource map[string]propertyType
// ArgsRequired is a flag indicating if the args param is required
// when creating a new resource.
ArgsRequired bool
// InputProperties is a map per language and a corresponding slice of
// input properties accepted as args while creating a new resource.
InputProperties map[string][]property
// OutputProperties is a map per language and a corresponding slice of
// output properties returned when a new instance of the resource is
// created.
OutputProperties map[string][]property
// LookupParams is a map of the param string to be rendered per language
// for looking-up a resource.
LookupParams map[string]string
// StateInputs is a map per language and the corresponding slice of
// state input properties required while looking-up an existing resource.
StateInputs map[string][]property
// StateParam is the type name of the state param, if any.
StateParam string
// NestedTypes is a slice of the nested types used in the input and
// output properties.
NestedTypes []docNestedType
PackageDetails packageDetails
}
// typeUsage represents a nested type's usage.
type typeUsage struct {
Input bool
Output bool
}
// nestedTypeUsageInfo is a type-alias for a map of Pulumi type-tokens
// and whether or not the type is used as an input and/or output
// properties.
type nestedTypeUsageInfo map[string]typeUsage
func (ss nestedTypeUsageInfo) add(s string, input bool) {
if v, ok := ss[s]; ok {
if input {
v.Input = true
} else {
v.Output = true
}
ss[s] = v
return
}
ss[s] = typeUsage{
Input: input,
Output: !input,
}
}
// contains returns true if the token already exists and matches the
// input or output flag of the token.
func (ss nestedTypeUsageInfo) contains(token string, input bool) bool {
a, ok := ss[token]
if !ok {
return false
}
if input && a.Input {
return true
} else if !input && a.Output {
return true
}
return false
}
type modContext struct {
pkg *schema.Package
mod string
inputTypes []*schema.ObjectType
resources []*schema.Resource
functions []*schema.Function
typeDetails map[*schema.ObjectType]*typeDetails
children []*modContext
tool string
}
func resourceName(r *schema.Resource) string {
if r.IsProvider {
return "Provider"
}
return strings.Title(tokenToName(r.Token))
}
func getLanguageDocHelper(lang string) codegen.DocLanguageHelper {
if h, ok := docHelpers[lang]; ok {
return h
}
panic(errors.Errorf("could not find a doc lang helper for %s", lang))
}
type propertyCharacteristics struct {
// input is a flag indicating if the property is an input type.
input bool
}
func (mod *modContext) details(t *schema.ObjectType) *typeDetails {
details, ok := mod.typeDetails[t]
if !ok {
details = &typeDetails{}
if mod.typeDetails == nil {
mod.typeDetails = map[*schema.ObjectType]*typeDetails{}
}
mod.typeDetails[t] = details
}
return details
}
// getLanguageModuleName transforms the current module's name to a
// language-specific name using the language info, if any, for the
// current package.
func (mod *modContext) getLanguageModuleName(lang string) string {
modName := mod.mod
lookupKey := lang + "_" + modName
if v, ok := langModuleNameLookup[lookupKey]; ok {
return v
}
switch lang {
case "go":
// Go module names use lowercase.
modName = strings.ToLower(modName)
if override, ok := goPkgInfo.ModuleToPackage[modName]; ok {
modName = override
}
case "csharp":
if override, ok := csharpPkgInfo.Namespaces[modName]; ok {
modName = override
}
case "nodejs":
if override, ok := nodePkgInfo.ModuleToPackage[modName]; ok {
modName = override
}
case "python":
if override, ok := pythonPkgInfo.ModuleNameOverrides[modName]; ok {
modName = override
}
}
langModuleNameLookup[lookupKey] = modName
return modName
}
// cleanTypeString removes any namespaces from the generated type string for all languages.
// The result of this function should be used display purposes only.
func (mod *modContext) cleanTypeString(t schema.Type, langTypeString, lang, modName string, isInput bool) string {
switch lang {
case "go", "python":
langTypeString = cleanOptionalIdentifier(langTypeString, lang)
parts := strings.Split(langTypeString, ".")
return parts[len(parts)-1]
}
cleanCSharpName := func(pkgName, objModName string) string {
// C# types can be wrapped in enumerable types such as List<> or Dictionary<>, so we have to
// only replace the namespace between the < and the > characters.
qualifier := "Inputs"
if !isInput {
qualifier = "Outputs"
}
var csharpNS string
// This type could be at the package-level, so it won't have a module name.
if objModName != "" {
csharpNS = fmt.Sprintf("Pulumi.%s.%s.%s.", title(pkgName, lang), title(objModName, lang), qualifier)
} else {
csharpNS = fmt.Sprintf("Pulumi.%s.%s.", title(pkgName, lang), qualifier)
}
return strings.ReplaceAll(langTypeString, csharpNS, "")
}
cleanNodeJSName := func(objModName string) string {
// The nodejs codegen currently doesn't use the ModuleToPackage override available
// in the k8s package's schema. So we'll manually strip some known module names for k8s.
// TODO[pulumi/pulumi#4325]: Remove this block once the nodejs code gen is able to use the
// package name overrides for modules.
if isKubernetesPackage(mod.pkg) {
langTypeString = strings.ReplaceAll(langTypeString, "k8s.io.", "")
langTypeString = strings.ReplaceAll(langTypeString, "apiserver.", "")
langTypeString = strings.ReplaceAll(langTypeString, "rbac.authorization.v1.", "")
langTypeString = strings.ReplaceAll(langTypeString, "rbac.authorization.v1alpha1.", "")
langTypeString = strings.ReplaceAll(langTypeString, "rbac.authorization.v1beta1.", "")
}
objModName = strings.ReplaceAll(objModName, "/", ".") + "."
return strings.ReplaceAll(langTypeString, objModName, "")
}
switch t := t.(type) {
case *schema.ArrayType:
if schema.IsPrimitiveType(t.ElementType) {
break
}
return mod.cleanTypeString(t.ElementType, langTypeString, lang, modName, isInput)
case *schema.UnionType:
for _, e := range t.ElementTypes {
if schema.IsPrimitiveType(e) {
continue
}
return mod.cleanTypeString(e, langTypeString, lang, modName, isInput)
}
case *schema.ObjectType:
objTypeModName := mod.pkg.TokenToModule(t.Token)
if objTypeModName != mod.mod {
modName = mod.getLanguageModuleName(lang)
}
}
if lang == "nodejs" {
return cleanNodeJSName(modName)
} else if lang == "csharp" {
return cleanCSharpName(mod.pkg.Name, modName)
}
return strings.ReplaceAll(langTypeString, modName, "")
}
// typeString returns a property type suitable for docs with its display name and the anchor link to
// a type if the type of the property is an array or an object.
func (mod *modContext) typeString(t schema.Type, lang string, characteristics propertyCharacteristics, insertWordBreaks bool) propertyType {
t = codegen.PlainType(t)
docLanguageHelper := getLanguageDocHelper(lang)
modName := mod.getLanguageModuleName(lang)
langTypeString := docLanguageHelper.GetLanguageTypeString(mod.pkg, modName, t, characteristics.input)
if optional, ok := t.(*schema.OptionalType); ok {
t = optional.ElementType
}
// If the type is an object type, let's also wrap it with a link to the supporting type
// on the same page using an anchor tag.
var href string
switch t := t.(type) {
case *schema.ArrayType:
elementLangType := mod.typeString(t.ElementType, lang, characteristics, false)
href = elementLangType.Link
case *schema.ObjectType:
tokenName := tokenToName(t.Token)
// Links to anchor tags on the same page must be lower-cased.
href = "#" + strings.ToLower(tokenName)
case *schema.EnumType:
tokenName := tokenToName(t.Token)
// Links to anchor tags on the same page must be lower-cased.
href = "#" + strings.ToLower(tokenName)
case *schema.UnionType:
var elements []string
for _, e := range t.ElementTypes {
elementLangType := mod.typeString(e, lang, characteristics, false)
elements = append(elements, elementLangType.DisplayName)
}
langTypeString = strings.Join(elements, " | ")
}
// Strip the namespace/module prefix for the type's display name.
displayName := langTypeString
if !schema.IsPrimitiveType(t) {
displayName = mod.cleanTypeString(t, langTypeString, lang, modName, characteristics.input)
}
// If word-breaks need to be inserted, then the type string
// should be html-encoded first if the language is C# in order
// to avoid confusing the Hugo rendering where the word-break
// tags are inserted.
if insertWordBreaks {
if lang == "csharp" {
displayName = html.EscapeString(displayName)
}
displayName = wbr(displayName)
}
displayName = cleanOptionalIdentifier(displayName, lang)
langTypeString = cleanOptionalIdentifier(langTypeString, lang)
return propertyType{
Name: langTypeString,
DisplayName: displayName,
Link: href,
}
}
// cleanOptionalIdentifier removes the type identifier (i.e. "?" in "string?").
func cleanOptionalIdentifier(s, lang string) string {
switch lang {
case "nodejs":
return strings.TrimSuffix(s, "?")
case "go":
return strings.TrimPrefix(s, "*")
case "csharp":
return strings.TrimSuffix(s, "?")
case "python":
if strings.HasPrefix(s, "Optional[") && strings.HasSuffix(s, "]") {
s = strings.TrimPrefix(s, "Optional[")
s = strings.TrimSuffix(s, "]")
return s
}
}
return s
}
// Resources typically take the same set of parameters to their constructors, and these
// are the default comments/descriptions for them.
const (
ctorNameArgComment = "The unique name of the resource."
ctorArgsArgComment = "The arguments to resource properties."
ctorOptsArgComment = "Bag of options to control resource's behavior."
)
func (mod *modContext) genConstructorTS(r *schema.Resource, argsOptional bool) []formalParam {
name := resourceName(r)
docLangHelper := getLanguageDocHelper("nodejs")
var argsType string
optsType := "CustomResourceOptions"
// The args type for k8s package differs from the rest depending on whether we are dealing with
// overlay resources or regular k8s resources.
if isKubernetesPackage(mod.pkg) {
if mod.isKubernetesOverlayModule() {
if name == "CustomResource" {
argsType = name + "Args"
} else {
argsType = name + "Opts"
}
} else {
// The non-schema-based k8s codegen does not apply a suffix to the input types.
argsType = name
}
if mod.isComponentResource() {
optsType = "ComponentResourceOptions"
}
} else {
argsType = name + "Args"
}
argsFlag := ""
if argsOptional {
argsFlag = "?"
}
return []formalParam{
{
Name: "name",
Type: propertyType{
Name: "string",
},
Comment: ctorNameArgComment,
},
{
Name: "args",
OptionalFlag: argsFlag,
Type: propertyType{
Name: argsType,
Link: "#inputs",
},
Comment: ctorArgsArgComment,
},
{
Name: "opts",
OptionalFlag: "?",
Type: propertyType{
Name: optsType,
Link: docLangHelper.GetDocLinkForPulumiType(mod.pkg, optsType),
},
Comment: ctorOptsArgComment,
},
}
}
func (mod *modContext) genConstructorGo(r *schema.Resource, argsOptional bool) []formalParam {
name := resourceName(r)
argsType := name + "Args"
argsFlag := ""
if argsOptional {
argsFlag = "*"
}
docLangHelper := getLanguageDocHelper("go")
return []formalParam{
{
Name: "ctx",
OptionalFlag: "*",
Type: propertyType{
Name: "Context",
Link: docLangHelper.GetDocLinkForPulumiType(mod.pkg, "Context"),
},
Comment: "Context object for the current deployment.",
},
{
Name: "name",
Type: propertyType{
Name: "string",
},
Comment: ctorNameArgComment,
},
{
Name: "args",
OptionalFlag: argsFlag,
Type: propertyType{
Name: argsType,
Link: "#inputs",
},
Comment: ctorArgsArgComment,
},
{
Name: "opts",
OptionalFlag: "...",
Type: propertyType{
Name: "ResourceOption",
Link: docLangHelper.GetDocLinkForPulumiType(mod.pkg, "ResourceOption"),
},
Comment: ctorOptsArgComment,
},
}
}
func (mod *modContext) genConstructorCS(r *schema.Resource, argsOptional bool) []formalParam {
name := resourceName(r)
optsType := "CustomResourceOptions"
if isKubernetesPackage(mod.pkg) && mod.isComponentResource() {
optsType = "ComponentResourceOptions"
}
var argsFlag string
var argsDefault string
if argsOptional {
// If the number of required input properties was zero, we can make the args object optional.
argsDefault = " = null"
argsFlag = "?"
}
docLangHelper := getLanguageDocHelper("csharp")
return []formalParam{
{
Name: "name",
Type: propertyType{
Name: "string",
},
Comment: ctorNameArgComment,
},
{
Name: "args",
OptionalFlag: argsFlag,
DefaultValue: argsDefault,
Type: propertyType{
Name: name + "Args",
Link: "#inputs",
},
Comment: ctorArgsArgComment,
},
{
Name: "opts",
OptionalFlag: "?",
DefaultValue: " = null",
Type: propertyType{
Name: optsType,
Link: docLangHelper.GetDocLinkForPulumiType(mod.pkg, fmt.Sprintf("Pulumi.%s", optsType)),
},
Comment: ctorOptsArgComment,
},
}
}
func (mod *modContext) genConstructorPython(r *schema.Resource, argsOptional, argsOverload bool) []formalParam {
docLanguageHelper := getLanguageDocHelper("python")
isK8sOverlayMod := mod.isKubernetesOverlayModule()
isDockerImageResource := mod.pkg.Name == "docker" && resourceName(r) == "Image"
// Kubernetes overlay resources use a different ordering of formal params in Python.
if isK8sOverlayMod {
return getKubernetesOverlayPythonFormalParams(mod.mod)
} else if isDockerImageResource {
return getDockerImagePythonFormalParams()
}
var params []formalParam
params = append(params, formalParam{
Name: "resource_name",
Type: propertyType{
Name: "str",
},
Comment: ctorNameArgComment,
})
if argsOverload {
// Determine whether we need to use the alternate args class name (e.g. `<Resource>InitArgs` instead of
// `<Resource>Args`) due to an input type with the same name as the resource in the same module.
resName := resourceName(r)
resArgsName := fmt.Sprintf("%sArgs", resName)
for _, inputType := range mod.inputTypes {
inputTypeName := strings.Title(tokenToName(inputType.Token))
if resName == inputTypeName {
resArgsName = fmt.Sprintf("%sInitArgs", resName)
}
}
optionalFlag, defaultVal, descriptionName := "", "", resArgsName
typeName := descriptionName
if argsOptional {
optionalFlag, defaultVal, typeName = "optional", " = None", fmt.Sprintf("Optional[%s]", typeName)
}
params = append(params, formalParam{
Name: "args",
OptionalFlag: optionalFlag,
DefaultValue: defaultVal,
Type: propertyType{
Name: typeName,
DescriptionName: descriptionName,
Link: "#inputs",
},
Comment: ctorArgsArgComment,
})
}
params = append(params, formalParam{
Name: "opts",
OptionalFlag: "optional",
DefaultValue: " = None",
Type: propertyType{
Name: "Optional[ResourceOptions]",
DescriptionName: "ResourceOptions",
Link: "/docs/reference/pkg/python/pulumi/#pulumi.ResourceOptions",
},
Comment: ctorOptsArgComment,
})
if argsOverload {
return params
}
for _, p := range r.InputProperties {
// If the property defines a const value, then skip it.
// For example, in k8s, `apiVersion` and `kind` are often hard-coded
// in the SDK and are not really user-provided input properties.
if p.ConstValue != nil {
continue
}
typ := docLanguageHelper.GetLanguageTypeString(mod.pkg, mod.mod, codegen.PlainType(codegen.OptionalType(p)), true /*input*/)
params = append(params, formalParam{
Name: python.InitParamName(p.Name),
DefaultValue: " = None",
Type: propertyType{
Name: fmt.Sprintf("%s", typ),
},
})
}
return params
}
func (mod *modContext) genNestedTypes(member interface{}, resourceType bool) []docNestedType {
tokens := nestedTypeUsageInfo{}
// Collect all of the types for this "member" as a map of resource names
// and if it appears in an input object and/or output object.
mod.getTypes(member, tokens)
var typs []docNestedType
for token := range tokens {
for _, t := range mod.pkg.Types {
switch typ := t.(type) {
case *schema.ObjectType:
if typ.Token != token || len(typ.Properties) == 0 || typ.IsInputShape() {
continue
}
// Create a map to hold the per-language properties of this object.
props := make(map[string][]property)
for _, lang := range supportedLanguages {
props[lang] = mod.getProperties(typ.Properties, lang, true, true, false)
}
name := strings.Title(tokenToName(typ.Token))
typs = append(typs, docNestedType{
Name: wbr(name),
AnchorID: strings.ToLower(name),
Properties: props,
})
case *schema.EnumType:
if typ.Token != token || len(typ.Elements) == 0 {
continue
}
name := strings.Title(tokenToName(typ.Token))
enums := make(map[string][]enum)
for _, lang := range supportedLanguages {
docLangHelper := getLanguageDocHelper(lang)
var langEnumValues []enum
for _, e := range typ.Elements {
enumName, err := docLangHelper.GetEnumName(e, name)
if err != nil {
panic(err)
}
enumID := strings.ToLower(name + propertyLangSeparator + lang)
langEnumValues = append(langEnumValues, enum{
ID: enumID,
DisplayName: wbr(enumName),
Name: enumName,
Value: fmt.Sprintf("%v", e.Value),
Comment: e.Comment,
DeprecationMessage: e.DeprecationMessage,
})
}
enums[lang] = langEnumValues
}
typs = append(typs, docNestedType{
Name: wbr(name),
AnchorID: strings.ToLower(name),
EnumValues: enums,
})
}
}
}
sort.Slice(typs, func(i, j int) bool {
return typs[i].Name < typs[j].Name
})
return typs
}
// getProperties returns a slice of properties that can be rendered for docs for
// the provided slice of properties in the schema.
func (mod *modContext) getProperties(properties []*schema.Property, lang string, input, nested, isProvider bool,
) []property {
if len(properties) == 0 {
return nil
}
docProperties := make([]property, 0, len(properties))
for _, prop := range properties {
if prop == nil {
continue
}
// If the property has a const value, then don't show it as an input property.
// Even though it is a valid property, it is used by the language code gen to
// generate the appropriate defaults for it. These cannot be overridden by users.
if prop.ConstValue != nil {
continue
}
characteristics := propertyCharacteristics{input: input}
langDocHelper := getLanguageDocHelper(lang)
name, err := langDocHelper.GetPropertyName(prop)
if err != nil {
panic(err)
}
propLangName := name
propID := strings.ToLower(propLangName + propertyLangSeparator + lang)
propTypes := make([]propertyType, 0)
if typ, isUnion := codegen.UnwrapType(prop.Type).(*schema.UnionType); isUnion {
for _, elementType := range typ.ElementTypes {
propTypes = append(propTypes, mod.typeString(elementType, lang, characteristics, true))
}
} else {
propTypes = append(propTypes, mod.typeString(prop.Type, lang, characteristics, true))
}
comment := prop.Comment
// Default values for Provider inputs correspond to environment variables, so add that info to the docs.
if isProvider && input && prop.DefaultValue != nil && len(prop.DefaultValue.Environment) > 0 {
var suffix string
if len(prop.DefaultValue.Environment) > 1 {
suffix = "s"
}
comment += fmt.Sprintf(" It can also be sourced from the following environment variable%s: ", suffix)
for i, v := range prop.DefaultValue.Environment {
comment += fmt.Sprintf("`%s`", v)
if i != len(prop.DefaultValue.Environment)-1 {
comment += ", "
}
}
}
docProperties = append(docProperties, property{
ID: propID,
DisplayName: wbr(propLangName),
Name: propLangName,
Comment: comment,
DeprecationMessage: prop.DeprecationMessage,
IsRequired: prop.IsRequired(),
IsInput: input,
Link: "#" + propID,
Types: propTypes,
})
}
// Sort required props to move them to the top of the properties list, then by name.
sort.SliceStable(docProperties, func(i, j int) bool {
pi, pj := docProperties[i], docProperties[j]
switch {
case pi.IsRequired != pj.IsRequired:
return pi.IsRequired && !pj.IsRequired
default:
return pi.Name < pj.Name
}
})
return docProperties
}
func getDockerImagePythonFormalParams() []formalParam {
return []formalParam{
{
Name: "image_name",
},
{
Name: "build",
},
{
Name: "local_image_name",
DefaultValue: "=None",
},
{
Name: "registry",
DefaultValue: "=None",
},
{
Name: "skip_push",
DefaultValue: "=None",
},
{
Name: "opts",
DefaultValue: "=None",
},