/
gen.go
3191 lines (2752 loc) 路 98.5 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 python
import (
"bytes"
"fmt"
"io"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
"github.com/blang/semver"
"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
resourceOutputType bool
plainType bool
}
type imports codegen.StringSet
func (imports imports) addType(mod *modContext, t *schema.ObjectType, input bool) {
imports.addTypeIf(mod, t, input, nil /*predicate*/)
}
func (imports imports) addTypeIf(mod *modContext, t *schema.ObjectType, input bool, predicate func(imp string) bool) {
if imp := mod.importObjectType(t, input); imp != "" && (predicate == nil || predicate(imp)) {
codegen.StringSet(imports).Add(imp)
}
}
func (imports imports) addEnum(mod *modContext, enum *schema.EnumType) {
if imp := mod.importEnumType(enum); imp != "" {
codegen.StringSet(imports).Add(imp)
}
}
func (imports imports) addResource(mod *modContext, r *schema.ResourceType) {
if imp := mod.importResourceType(r); imp != "" {
codegen.StringSet(imports).Add(imp)
}
}
func (imports imports) strings() []string {
result := make([]string, 0, len(imports))
for imp := range imports {
result = append(result, imp)
}
sort.Strings(result)
return result
}
func title(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
return string(append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...))
}
type modLocator struct {
// Returns defining modlue for a given ObjectType. Returns nil
// for types that are not being generated in the current
// GeneratePacakge call.
objectTypeMod func(*schema.ObjectType) *modContext
}
type modContext struct {
pkg schema.PackageReference
modLocator *modLocator
mod string
pyPkgName string
types []*schema.ObjectType
enums []*schema.EnumType
resources []*schema.Resource
functions []*schema.Function
typeDetails map[*schema.ObjectType]*typeDetails
children []*modContext
parent *modContext
tool string
extraSourceFiles []string
isConfig bool
// Name overrides set in PackageInfo
modNameOverrides map[string]string // Optional overrides for Pulumi module names
compatibility string // Toggle compatibility mode for a specified target.
// Determine whether to lift single-value method return values
liftSingleValueMethodReturns bool
}
func (mod *modContext) isTopLevel() bool {
return mod.parent == nil
}
func (mod *modContext) walkSelfWithDescendants() []*modContext {
var found []*modContext
found = append(found, mod)
for _, childMod := range mod.children {
found = append(found, childMod.walkSelfWithDescendants()...)
}
return found
}
func (mod *modContext) addChild(child *modContext) {
mod.children = append(mod.children, child)
child.parent = mod
}
func (mod *modContext) details(t *schema.ObjectType) *typeDetails {
m := mod
if mod.modLocator != nil {
if actualMod := mod.modLocator.objectTypeMod(t); actualMod != nil {
m = actualMod
}
}
details, ok := m.typeDetails[t]
if !ok {
details = &typeDetails{}
if m.typeDetails == nil {
m.typeDetails = map[*schema.ObjectType]*typeDetails{}
}
m.typeDetails[t] = details
}
return details
}
func (mod *modContext) modNameAndName(pkg schema.PackageReference, t schema.Type, input bool) (modName string, name string) {
var info PackageInfo
p, err := pkg.Definition()
contract.AssertNoError(err)
contract.AssertNoError(p.ImportLanguages(map[string]schema.Language{"python": Importer}))
if v, ok := p.Language["python"].(PackageInfo); ok {
info = v
}
var token string
switch t := t.(type) {
case *schema.EnumType:
token, name = t.Token, tokenToName(t.Token)
case *schema.ObjectType:
namingCtx := &modContext{
pkg: pkg,
modNameOverrides: info.ModuleNameOverrides,
compatibility: info.Compatibility,
}
token, name = t.Token, namingCtx.unqualifiedObjectTypeName(t, input)
case *schema.ResourceType:
token, name = t.Token, tokenToName(t.Token)
}
modName = tokenToModule(token, pkg, info.ModuleNameOverrides)
if modName != "" {
modName = strings.ReplaceAll(modName, "/", ".") + "."
}
return
}
func (mod *modContext) unqualifiedObjectTypeName(t *schema.ObjectType, input bool) string {
name := tokenToName(t.Token)
if mod.compatibility != tfbridge20 && mod.compatibility != kubernetes20 {
if t.IsInputShape() {
return name + "Args"
}
return name
}
switch {
case input:
return name + "Args"
case mod.details(t).plainType:
return name + "Result"
}
return name
}
func (mod *modContext) objectType(t *schema.ObjectType, input bool) string {
var prefix string
if !input {
prefix = "outputs."
}
// If it's an external type, reference it via fully qualified name.
if !codegen.PkgEquals(t.PackageReference, mod.pkg) {
modName, name := mod.modNameAndName(t.PackageReference, t, input)
return fmt.Sprintf("'%s.%s%s%s'", pyPack(t.PackageReference.Name()), modName, prefix, name)
}
modName, name := mod.tokenToModule(t.Token), mod.unqualifiedObjectTypeName(t, input)
if modName == "" && modName != mod.mod {
rootModName := "_root_outputs."
if input {
rootModName = "_root_inputs."
}
return fmt.Sprintf("'%s%s'", rootModName, name)
}
if modName == mod.mod {
modName = ""
}
if modName != "" {
modName = "_" + strings.ReplaceAll(modName, "/", ".") + "."
}
return fmt.Sprintf("'%s%s%s'", modName, prefix, name)
}
func (mod *modContext) tokenToEnum(tok string) string {
modName, name := mod.tokenToModule(tok), tokenToName(tok)
if modName == "" && modName != mod.mod {
return fmt.Sprintf("'_root_enums.%s'", name)
}
if modName == mod.mod {
modName = ""
}
if modName != "" {
modName = "_" + strings.ReplaceAll(modName, "/", ".") + "."
}
return fmt.Sprintf("'%s%s'", modName, name)
}
func (mod *modContext) resourceType(r *schema.ResourceType) string {
if r.Resource == nil || codegen.PkgEquals(r.Resource.PackageReference, mod.pkg) {
return mod.tokenToResource(r.Token)
}
// Is it a provider resource?
if strings.HasPrefix(r.Token, "pulumi:providers:") {
pkgName := strings.TrimPrefix(r.Token, "pulumi:providers:")
return fmt.Sprintf("pulumi_%s.Provider", pkgName)
}
pkg := r.Resource.PackageReference
modName, name := mod.modNameAndName(pkg, r, false)
return fmt.Sprintf("%s.%s%s", pyPack(pkg.Name()), modName, name)
}
func (mod *modContext) tokenToResource(tok string) string {
// token := pkg : module : member
// module := path/to/module
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "malformed token %v", tok)
// Is it a provider resource?
if components[0] == "pulumi" && components[1] == "providers" {
return fmt.Sprintf("pulumi_%s.Provider", components[2])
}
modName, name := mod.tokenToModule(tok), tokenToName(tok)
if modName == mod.mod {
modName = ""
}
if modName != "" {
modName = "_" + strings.ReplaceAll(modName, "/", ".") + "."
}
return fmt.Sprintf("%s%s", modName, name)
}
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 tokenToModule(tok string, pkg schema.PackageReference, moduleNameOverrides map[string]string) string {
// See if there's a manually-overridden module name.
if pkg == nil {
// If pkg is nil, we use the default `TokenToModule` scheme.
pkg = (&schema.Package{}).Reference()
}
canonicalModName := pkg.TokenToModule(tok)
if override, ok := moduleNameOverrides[canonicalModName]; ok {
return override
}
// A module can include fileparts, which we want to preserve.
var modName string
for i, part := range strings.Split(strings.ToLower(canonicalModName), "/") {
if i > 0 {
modName += "/"
}
modName += PyName(part)
}
return modName
}
func (mod *modContext) tokenToModule(tok string) string {
return tokenToModule(tok, mod.pkg, mod.modNameOverrides)
}
func printComment(w io.Writer, comment string, indent string) {
lines := strings.Split(comment, "\n")
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
if len(lines) == 0 {
return
}
// Known special characters that need escaping.
replacer := strings.NewReplacer(`\`, `\\`, `"""`, `\"\"\"`)
fmt.Fprintf(w, "%s\"\"\"\n", indent)
for _, l := range lines {
if l == "" {
fmt.Fprintf(w, "\n")
} else {
escaped := replacer.Replace(l)
fmt.Fprintf(w, "%s%s\n", indent, escaped)
}
}
fmt.Fprintf(w, "%s\"\"\"\n", indent)
}
func genStandardHeader(w io.Writer, tool string) {
// Set the encoding to UTF-8, in case the comments contain non-ASCII characters.
fmt.Fprintf(w, "# coding=utf-8\n")
// Emit a standard warning header ("do not edit", etc).
fmt.Fprintf(w, "# *** WARNING: this file was generated by %v. ***\n", tool)
fmt.Fprintf(w, "# *** Do not edit by hand unless you're certain you know what you are doing! ***\n\n")
}
func typingImports() []string {
return []string{
"Any",
"Mapping",
"Optional",
"Sequence",
"Union",
"overload",
}
}
func (mod *modContext) generateCommonImports(w io.Writer, imports imports, typingImports []string) {
rel, err := filepath.Rel(mod.mod, "")
contract.Assert(err == nil)
relRoot := path.Dir(rel)
relImport := relPathToRelImport(relRoot)
fmt.Fprintf(w, "import copy\n")
fmt.Fprintf(w, "import warnings\n")
fmt.Fprintf(w, "import pulumi\n")
fmt.Fprintf(w, "import pulumi.runtime\n")
fmt.Fprintf(w, "from typing import %s\n", strings.Join(typingImports, ", "))
fmt.Fprintf(w, "from %s import _utilities\n", relImport)
for _, imp := range imports.strings() {
fmt.Fprintf(w, "%s\n", imp)
}
fmt.Fprintf(w, "\n")
}
func (mod *modContext) genHeader(w io.Writer, needsSDK bool, imports imports) {
genStandardHeader(w, mod.tool)
// If needed, emit the standard Pulumi SDK import statement.
if needsSDK {
typings := typingImports()
mod.generateCommonImports(w, imports, typings)
}
}
func (mod *modContext) genFunctionHeader(w io.Writer, function *schema.Function, imports imports) {
genStandardHeader(w, mod.tool)
typings := typingImports()
if function.Outputs == nil || len(function.Outputs.Properties) == 0 {
typings = append(typings, "Awaitable")
}
mod.generateCommonImports(w, imports, typings)
}
func relPathToRelImport(relPath string) string {
// Convert relative path to relative import e.g. "../.." -> "..."
// https://realpython.com/absolute-vs-relative-python-imports/#relative-imports
relImport := "."
if relPath == "." {
return relImport
}
for _, component := range strings.Split(relPath, "/") {
if component == ".." {
relImport += "."
} else {
relImport += component
}
}
return relImport
}
func (mod *modContext) genUtilitiesFile() ([]byte, error) {
buffer := &bytes.Buffer{}
genStandardHeader(buffer, mod.tool)
fmt.Fprintf(buffer, utilitiesFile)
optionalURL := "None"
pkg, err := mod.pkg.Definition()
if err != nil {
return nil, err
}
if url := pkg.PluginDownloadURL; url != "" {
optionalURL = fmt.Sprintf("%q", url)
}
_, err = fmt.Fprintf(buffer, `
def get_plugin_download_url():
return %s
`, optionalURL)
return buffer.Bytes(), err
}
func (mod *modContext) gen(fs codegen.Fs) error {
dir := path.Join(mod.pyPkgName, mod.mod)
var exports []string
for p := range fs {
d := path.Dir(p)
if d == "." {
d = ""
}
if d == dir {
exports = append(exports, strings.TrimSuffix(path.Base(p), ".py"))
}
}
addFile := func(name, contents string) {
p := path.Join(dir, name)
if !strings.HasSuffix(name, ".pyi") {
exports = append(exports, name[:len(name)-len(".py")])
}
fs.Add(p, []byte(contents))
}
// Utilities, config, readme
switch mod.mod {
case "":
utils, err := mod.genUtilitiesFile()
if err != nil {
return err
}
fs.Add(filepath.Join(dir, "_utilities.py"), utils)
fs.Add(filepath.Join(dir, "py.typed"), []byte{})
// Ensure that the top-level (provider) module directory contains a README.md file.
pkg, err := mod.pkg.Definition()
if err != nil {
return err
}
var readme string
if pythonInfo, ok := pkg.Language["python"]; ok {
if typedInfo, ok := pythonInfo.(PackageInfo); ok {
readme = typedInfo.Readme
}
}
if readme == "" {
readme = mod.pkg.Description()
if readme != "" && readme[len(readme)-1] != '\n' {
readme += "\n"
}
if pkg.Attribution != "" {
if len(readme) != 0 {
readme += "\n"
}
readme += pkg.Attribution
}
if readme != "" && readme[len(readme)-1] != '\n' {
readme += "\n"
}
}
fs.Add(filepath.Join(dir, "README.md"), []byte(readme))
case "config":
config, err := mod.pkg.Config()
if err != nil {
return err
}
if len(config) > 0 {
vars, err := mod.genConfig(config)
if err != nil {
return err
}
addFile("vars.py", vars)
typeStubs, err := mod.genConfigStubs(config)
if err != nil {
return err
}
addFile("__init__.pyi", typeStubs)
}
}
// Resources
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
res, err := mod.genResource(r)
if err != nil {
return err
}
name := PyName(tokenToName(r.Token))
if mod.compatibility == kubernetes20 {
// To maintain backward compatibility for kubernetes, the file names
// need to be CamelCase instead of the standard snake_case.
name = tokenToName(r.Token)
}
if r.IsProvider {
name = "provider"
}
addFile(name+".py", res)
}
// Functions
for _, f := range mod.functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
fun, err := mod.genFunction(f)
if err != nil {
return err
}
addFile(PyName(tokenToName(f.Token))+".py", fun)
}
// Nested types
if len(mod.types) > 0 {
if err := mod.genTypes(dir, fs); err != nil {
return err
}
}
// Enums
if len(mod.enums) > 0 {
buffer := &bytes.Buffer{}
if err := mod.genEnums(buffer, mod.enums); err != nil {
return err
}
addFile("_enums.py", buffer.String())
}
// Index
if !mod.isEmpty() {
fs.Add(path.Join(dir, "__init__.py"), []byte(mod.genInit(exports)))
}
return nil
}
func (mod *modContext) hasTypes(input bool) bool {
if allTypesAreOverlays(mod.types) {
return false
}
for _, t := range mod.types {
if input && mod.details(t).inputType {
return true
}
if !input && mod.details(t).outputType {
return true
}
}
return false
}
func (mod *modContext) isEmpty() bool {
if len(mod.extraSourceFiles) > 0 || len(mod.functions) > 0 || len(mod.resources) > 0 || len(mod.types) > 0 ||
mod.isConfig {
return false
}
for _, child := range mod.children {
if !child.isEmpty() {
return false
}
}
return true
}
func (mod *modContext) submodulesExist() bool {
for _, submod := range mod.children {
if !submod.isEmpty() {
return true
}
}
return false
}
func (mod *modContext) unqualifiedImportName() string {
name := mod.mod
// Extract version suffix from child modules. Nested versions will have their own __init__.py file.
// Example: apps/v1beta1 -> v1beta1
parts := strings.Split(name, "/")
if len(parts) > 1 {
name = parts[len(parts)-1]
}
return PyName(name)
}
func (mod *modContext) fullyQualifiedImportName() string {
name := mod.unqualifiedImportName()
if mod.parent == nil && name == "" {
return mod.pyPkgName
}
if mod.parent == nil {
return fmt.Sprintf("%s.%s", pyPack(mod.pkg.Name()), name)
}
return fmt.Sprintf("%s.%s", mod.parent.fullyQualifiedImportName(), name)
}
// genInit emits an __init__.py module, optionally re-exporting other members or submodules.
func (mod *modContext) genInit(exports []string) string {
w := &bytes.Buffer{}
mod.genHeader(w, false /*needsSDK*/, nil)
if mod.isConfig {
fmt.Fprintf(w, "import sys\n")
fmt.Fprintf(w, "from .vars import _ExportableConfig\n")
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "sys.modules[__name__].__class__ = _ExportableConfig\n")
return w.String()
}
fmt.Fprintf(w, "%s\n", mod.genUtilitiesImport())
fmt.Fprintf(w, "import typing\n")
// Import anything to export flatly that is a direct export rather than sub-module.
if len(exports) > 0 {
sort.Slice(exports, func(i, j int) bool {
return PyName(exports[i]) < PyName(exports[j])
})
fmt.Fprintf(w, "# Export this package's modules as members:\n")
for _, exp := range exports {
name := PyName(exp)
if mod.compatibility == kubernetes20 {
// To maintain backward compatibility for kubernetes, the file names
// need to be CamelCase instead of the standard snake_case.
name = exp
}
fmt.Fprintf(w, "from .%s import *\n", name)
}
}
if mod.hasTypes(true /*input*/) {
fmt.Fprintf(w, "from ._inputs import *\n")
}
if mod.hasTypes(false /*input*/) {
fmt.Fprintf(w, "from . import outputs\n")
}
// If there are subpackages, import them with importlib.
if mod.submodulesExist() {
children := make([]*modContext, len(mod.children))
copy(children, mod.children)
sort.Slice(children, func(i, j int) bool {
return PyName(children[i].mod) < PyName(children[j].mod)
})
fmt.Fprintf(w, "\n# Make subpackages available:\n")
fmt.Fprintf(w, "if typing.TYPE_CHECKING:\n")
for _, submod := range children {
if !submod.isEmpty() {
unq := submod.unqualifiedImportName()
// The `__iam = iam` hack enables
// PyCharm and VSCode completion to do
// better.
//
// See https://github.com/pulumi/pulumi/issues/7367
fmt.Fprintf(w, " import %s as __%s\n %s = __%s\n",
submod.fullyQualifiedImportName(),
unq,
unq,
unq)
}
}
fmt.Fprintf(w, "else:\n")
for _, submod := range children {
if !submod.isEmpty() {
fmt.Fprintf(w, " %s = _utilities.lazy_import('%s')\n",
submod.unqualifiedImportName(),
submod.fullyQualifiedImportName())
}
}
fmt.Fprintf(w, "\n")
}
// If there are resources in this module, register the module with the runtime.
if len(mod.resources) != 0 {
err := genResourceMappings(mod, w)
contract.Assert(err == nil)
}
return w.String()
}
func (mod *modContext) getRelImportFromRoot() string {
rel, err := filepath.Rel(mod.mod, "")
contract.Assert(err == nil)
relRoot := path.Dir(rel)
return relPathToRelImport(relRoot)
}
func (mod *modContext) genUtilitiesImport() string {
rel, err := filepath.Rel(mod.mod, "")
contract.Assert(err == nil)
relRoot := path.Dir(rel)
relImport := relPathToRelImport(relRoot)
return fmt.Sprintf("from %s import _utilities", relImport)
}
func (mod *modContext) importObjectType(t *schema.ObjectType, input bool) string {
if !codegen.PkgEquals(t.PackageReference, mod.pkg) {
return fmt.Sprintf("import %s", pyPack(t.PackageReference.Name()))
}
tok := t.Token
parts := strings.Split(tok, ":")
contract.Assert(len(parts) == 3)
refPkgName := parts[0]
modName := mod.tokenToModule(tok)
if modName == mod.mod {
if input {
return "from ._inputs import *"
}
return "from . import outputs"
}
importPath := mod.getRelImportFromRoot()
if mod.pkg.Name() != parts[0] {
importPath = fmt.Sprintf("pulumi_%s", refPkgName)
}
if modName == "" {
imp, as := "outputs", "_root_outputs"
if input {
imp, as = "_inputs", "_root_inputs"
}
return fmt.Sprintf("from %s import %s as %s", importPath, imp, as)
}
components := strings.Split(modName, "/")
return fmt.Sprintf("from %s import %[2]s as _%[2]s", importPath, components[0])
}
func (mod *modContext) importEnumType(e *schema.EnumType) string {
if !codegen.PkgEquals(e.PackageReference, mod.pkg) {
return fmt.Sprintf("import %s", pyPack(e.PackageReference.Name()))
}
modName := mod.tokenToModule(e.Token)
if modName == mod.mod {
return "from ._enums import *"
}
importPath := mod.getRelImportFromRoot()
if modName == "" {
return fmt.Sprintf("from %s import _enums as _root_enums", importPath)
}
components := strings.Split(modName, "/")
return fmt.Sprintf("from %s import %s", importPath, components[0])
}
func (mod *modContext) importResourceType(r *schema.ResourceType) string {
if r.Resource != nil && !codegen.PkgEquals(r.Resource.PackageReference, mod.pkg) {
return fmt.Sprintf("import %s", pyPack(r.Resource.PackageReference.Name()))
}
tok := r.Token
parts := strings.Split(tok, ":")
contract.Assert(len(parts) == 3)
// If it's a provider resource, import the top-level package.
if parts[0] == "pulumi" && parts[1] == "providers" {
return fmt.Sprintf("import pulumi_%s", parts[2])
}
refPkgName := parts[0]
modName := mod.tokenToResource(tok)
importPath := mod.getRelImportFromRoot()
if mod.pkg.Name() != parts[0] {
importPath = fmt.Sprintf("pulumi_%s", refPkgName)
}
name := PyName(tokenToName(r.Token))
if mod.compatibility == kubernetes20 {
// To maintain backward compatibility for kubernetes, the file names
// need to be CamelCase instead of the standard snake_case.
name = tokenToName(r.Token)
}
if r.Resource != nil && r.Resource.IsProvider {
name = "provider"
}
components := strings.Split(modName, "/")
return fmt.Sprintf("from %s%s import %s", importPath, name, components[0])
}
// genConfig emits all config variables in the given module, returning the resulting file.
func (mod *modContext) genConfig(variables []*schema.Property) (string, error) {
w := &bytes.Buffer{}
imports := imports{}
mod.collectImports(variables, imports, false /*input*/)
mod.genHeader(w, true /*needsSDK*/, imports)
fmt.Fprintf(w, "import types\n")
fmt.Fprintf(w, "\n")
// Create a config bag for the variables to pull from.
fmt.Fprintf(w, "__config__ = pulumi.Config('%s')\n", mod.pkg.Name())
fmt.Fprintf(w, "\n\n")
// To avoid a breaking change to the existing config getters, we define a class that extends
// the `ModuleType` type and implements property getters for each config key. We then overwrite
// the `__class__` attribute of the current module as described in the proposal for PEP-549. This allows
// us to maintain the existing interface for users but implement dynamic getters behind the scenes.
fmt.Fprintf(w, "class _ExportableConfig(types.ModuleType):\n")
indent := " "
// Emit an entry for all config variables.
for _, p := range variables {
configFetch, err := genConfigFetch(p)
if err != nil {
return "", err
}
typeString := genConfigVarType(p)
fmt.Fprintf(w, "%s@property\n", indent)
fmt.Fprintf(w, "%sdef %s(self) -> %s:\n", indent, PyName(p.Name), typeString)
dblIndent := strings.Repeat(indent, 2)
printComment(w, p.Comment, dblIndent)
fmt.Fprintf(w, "%sreturn %s\n", dblIndent, configFetch)
fmt.Fprintf(w, "\n")
}
return w.String(), nil
}
func genConfigFetch(configVar *schema.Property) (string, error) {
getFunc := "get"
unwrappedType := codegen.UnwrapType(configVar.Type)
switch unwrappedType {
case schema.BoolType:
getFunc = "get_bool"
case schema.IntType:
getFunc = "get_int"
case schema.NumberType:
getFunc = "get_float"
}
configFetch := fmt.Sprintf("__config__.%s('%s')", getFunc, configVar.Name)
if configVar.DefaultValue != nil {
v, err := getDefaultValue(configVar.DefaultValue, unwrappedType)
if err != nil {
return "", err
}
configFetch += " or " + v
}
return configFetch, nil
}
func genConfigVarType(configVar *schema.Property) string {
// For historical reasons and to maintain backwards compatibility, the config variables for python
// are typed as `Optional[str`] or `str` for complex objects since the getters only use config.get().
// To return the rich objects would be a breaking change, tracked in https://github.com/pulumi/pulumi/issues/7493
typeString := "str"
switch codegen.UnwrapType(configVar.Type) {
case schema.BoolType:
typeString = "bool"
case schema.IntType:
typeString = "int"
case schema.NumberType:
typeString = "float"
}
if configVar.DefaultValue == nil || configVar.DefaultValue.Value == nil {
typeString = "Optional[" + typeString + "]"
}
return typeString
}
// genConfigStubs emits all type information for the config variables in the given module, returning the resulting file.
// We do this because we lose IDE autocomplete by implementing the dynamic config getters described in genConfig.
// Emitting these stubs allows us to maintain type hints and autocomplete for users.
func (mod *modContext) genConfigStubs(variables []*schema.Property) (string, error) {
w := &bytes.Buffer{}
imports := imports{}
mod.collectImports(variables, imports, false /*input*/)
mod.genHeader(w, true /*needsSDK*/, imports)
// Emit an entry for all config variables.
for _, p := range variables {
typeString := genConfigVarType(p)
fmt.Fprintf(w, "%s: %s\n", p.Name, typeString)
printComment(w, p.Comment, "")
fmt.Fprintf(w, "\n")
}
return w.String(), nil
}
func allTypesAreOverlays(types []*schema.ObjectType) bool {
for _, t := range types {
if !t.IsOverlay {
return false
}
}
return true
}
func (mod *modContext) genTypes(dir string, fs codegen.Fs) error {
genTypes := func(file string, input bool) error {
w := &bytes.Buffer{}
if allTypesAreOverlays(mod.types) {
// If all resources in this module are overlays, skip further code generation.
return nil
}
imports := imports{}
for _, t := range mod.types {
if t.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
if input && mod.details(t).inputType {
visitObjectTypes(t.Properties, func(t schema.Type) {
switch t := t.(type) {
case *schema.ObjectType:
imports.addTypeIf(mod, t, true /*input*/, func(imp string) bool {
// No need to import `._inputs` inside _inputs.py.
return imp != "from ._inputs import *"
})
case *schema.EnumType:
imports.addEnum(mod, t)
case *schema.ResourceType:
imports.addResource(mod, t)
}