-
Notifications
You must be signed in to change notification settings - Fork 41
/
generate.go
1680 lines (1459 loc) · 51.5 KB
/
generate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tfgen
import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
dotnetgen "github.com/pulumi/pulumi/pkg/v3/codegen/dotnet"
gogen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
nodejsgen "github.com/pulumi/pulumi/pkg/v3/codegen/nodejs"
"github.com/pulumi/pulumi/pkg/v3/codegen/pcl"
pygen "github.com/pulumi/pulumi/pkg/v3/codegen/python"
pschema "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/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/spf13/afero"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tf2pulumi/il"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfgen/internal/paths"
shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/schema"
schemaTools "github.com/pulumi/schema-tools/pkg"
)
const (
tfgen = "the Pulumi Terraform Bridge (tfgen) Tool"
defaultOutDir = "sdk/"
maxWidth = 120 // the ideal maximum width of the generated file.
)
type Generator struct {
pkg tokens.Package // the Pulum package name (e.g. `gcp`)
version string // the package version.
language Language // the language runtime to generate.
info tfbridge.ProviderInfo // the provider info for customizing code generation
root afero.Fs // the output virtual filesystem.
providerShim *inmemoryProvider // a provider shim to hold the provider schema during example conversion.
pluginHost plugin.Host // the plugin host for tf2pulumi.
packageCache *pcl.PackageCache // the package cache for tf2pulumi.
infoSource il.ProviderInfoSource // the provider info source for tf2pulumi.
terraformVersion string // the Terraform version to target for example codegen, if any
sink diag.Sink
skipDocs bool
skipExamples bool
coverageTracker *CoverageTracker
convertedCode map[string][]byte
}
type Language string
const (
Golang Language = "go"
NodeJS Language = "nodejs"
Python Language = "python"
CSharp Language = "dotnet"
Schema Language = "schema"
PCL Language = "pulumi"
)
func (l Language) shouldConvertExamples() bool {
switch l {
case Golang, NodeJS, Python, CSharp, Schema, PCL:
return true
}
return false
}
func (l Language) emitSDK(pkg *pschema.Package, info tfbridge.ProviderInfo, root afero.Fs) (map[string][]byte, error) {
var extraFiles map[string][]byte
var err error
switch l {
case Golang:
return gogen.GeneratePackage(tfgen, pkg)
case NodeJS:
if psi := info.JavaScript; psi != nil && psi.Overlay != nil {
extraFiles, err = getOverlayFiles(psi.Overlay, ".ts", root)
if err != nil {
return nil, err
}
}
// We exclude the "tests" directory because some nodejs package dirs (e.g. pulumi-docker)
// store tests here. We don't want to include them in the overlays because we don't want it
// exported with the module, but we don't want them deleted in a cleanup of the directory.
exclusions := codegen.NewStringSet("tests")
// We don't need to add overlays to the exclusion list because they have already been read
// into memory so deleting the files is not a problem.
err = cleanDir(root, "", exclusions)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
return nodejsgen.GeneratePackage(tfgen, pkg, extraFiles)
case Python:
if psi := info.Python; psi != nil && psi.Overlay != nil {
extraFiles, err = getOverlayFiles(psi.Overlay, ".py", root)
if err != nil {
return nil, err
}
}
// python's outdir path follows the pattern [provider]/sdk/python/pulumi_[pkg name]
pyOutDir := fmt.Sprintf("pulumi_%s", pkg.Name)
err = cleanDir(root, pyOutDir, nil)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
return pygen.GeneratePackage(tfgen, pkg, extraFiles)
case CSharp:
if psi := info.CSharp; psi != nil && psi.Overlay != nil {
extraFiles, err = getOverlayFiles(psi.Overlay, ".cs", root)
if err != nil {
return nil, err
}
}
err = cleanDir(root, "", nil)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
return dotnetgen.GeneratePackage(tfgen, pkg, extraFiles)
default:
return nil, errors.Errorf("%v does not support SDK generation", l)
}
}
var AllLanguages = []Language{Golang, NodeJS, Python, CSharp}
// pkg is a directory containing one or more modules.
type pkg struct {
name tokens.Package // the package name.
version string // the package version.
language Language // the package's language.
root afero.Fs // the root of the package.
modules moduleMap // the modules inside of this package.
provider *resourceType // the provider type for this package.
}
func newPkg(name tokens.Package, version string, language Language, fs afero.Fs) *pkg {
return &pkg{
name: name,
version: version,
language: language,
root: fs,
modules: make(moduleMap),
}
}
// addModule registers a new module in the given package. If one already exists under the name, we will merge
// the entry with the existing module (where merging simply appends the members).
func (p *pkg) addModule(m *module) {
p.modules[m.name] = p.modules[m.name].merge(m)
}
// addModuleMap registers an array of modules, using the same logic that addModule uses.
func (p *pkg) addModuleMap(m moduleMap) {
for _, k := range m.keys() {
p.addModule(m[k])
}
}
type moduleMap map[tokens.Module]*module
func (m moduleMap) keys() []tokens.Module {
var ks []tokens.Module
for k := range m {
ks = append(ks, k)
}
sort.SliceStable(ks, func(i, j int) bool {
return ks[i].String() < ks[j].String()
})
return ks
}
func (m moduleMap) values() []*module {
var vs []*module
for _, k := range m.keys() {
vs = append(vs, m[k])
}
return vs
}
func (m moduleMap) ensureModule(name tokens.Module) *module {
if _, ok := m[name]; !ok {
m[name] = newModule(name)
}
return m[name]
}
// module is a single module that was generated by this tool, containing members (types and functions).
type module struct {
name tokens.Module // the friendly module name.
members []moduleMember // a list of exported members from this module (ordered in case of dependencies).
}
func newModule(name tokens.Module) *module {
return &module{name: name}
}
// configMod is the special name used for configuration modules.
var configMod tokens.ModuleName = tokens.ModuleName("config")
// indexMod is the special name used for the root default module.
var indexMod tokens.ModuleName = tokens.ModuleName("index")
// config returns true if this is a configuration module.
func (m *module) config() bool {
return m.name.Name() == configMod
}
// addMember appends a new member. This maintains ordering in case the code is sensitive to declaration order.
func (m *module) addMember(member moduleMember) {
name := member.Name()
for _, existing := range m.members {
contract.Assertf(existing.Name() != name, "unexpected duplicate module member %s", name)
}
m.members = append(m.members, member)
}
// merge merges two separate modules into one and returns the result.
func (m *module) merge(other *module) *module {
if m == nil {
return other
} else if other == nil {
return m
}
contract.Assertf(m.name == other.name,
"expected module names %s and %s to match", m.name, other.name)
contract.Assertf(m.config() == other.config(),
"cannot combine config and non-config modules (%s %t; %s %t)",
m.name, m.config(), other.name, other.config())
return &module{
name: m.name,
members: append(m.members, other.members...),
}
}
// moduleMember is an exportable type.
type moduleMember interface {
Name() string
Doc() string
}
type typeKind int
const (
kindInvalid = iota
kindBool
kindInt
kindFloat
kindString
kindList
kindMap
kindSet
kindObject
)
// Avoid an unused warning from varcheck.
var _ = kindInvalid
// propertyType represents a non-resource, non-datasource type. Property types may be simple
type propertyType struct {
name string
doc string
kind typeKind
element *propertyType
properties []*variable
typ tokens.Type
nestedType tokens.Type
altTypes []tokens.Type
asset *tfbridge.AssetTranslation
}
func (g *Generator) makePropertyType(typePath paths.TypePath,
objectName string, sch shim.Schema, info *tfbridge.SchemaInfo, out bool,
entityDocs entityDocs) *propertyType {
t := &propertyType{}
var elemInfo *tfbridge.SchemaInfo
if info != nil {
t.typ = info.Type
t.nestedType = info.NestedType
t.altTypes = info.AltTypes
t.asset = info.Asset
elemInfo = info.Elem
}
if sch == nil {
contract.Assert(info != nil)
return t
}
switch sch.Type() {
case shim.TypeBool:
t.kind = kindBool
case shim.TypeInt:
t.kind = kindInt
case shim.TypeFloat:
t.kind = kindFloat
case shim.TypeString:
t.kind = kindString
case shim.TypeList:
t.kind = kindList
case shim.TypeMap:
t.kind = kindMap
case shim.TypeSet:
t.kind = kindSet
}
// We should carry across any of the deprecation messages, to Pulumi, as per Terraform schema
if sch.Deprecated() != "" && elemInfo != nil {
elemInfo.DeprecationMessage = sch.Deprecated()
}
switch elem := sch.Elem().(type) {
case shim.Schema:
t.element = g.makePropertyType(paths.NewElementPath(typePath),
objectName, elem, elemInfo, out, entityDocs)
case shim.Resource:
t.element = g.makeObjectPropertyType(paths.NewElementPath(typePath),
objectName, elem, elemInfo, out, entityDocs)
}
switch t.kind {
case kindList, kindSet:
if tfbridge.IsMaxItemsOne(sch, info) {
t = t.element
}
case kindMap:
// If this map has a "resource" element type, just use the generated element type. This works around a bug in
// TF that effectively forces this behavior.
if t.element != nil && t.element.kind == kindObject {
t = t.element
}
}
return t
}
func (g *Generator) makeObjectPropertyType(typePath paths.TypePath,
objectName string, res shim.Resource, info *tfbridge.SchemaInfo,
out bool, entityDocs entityDocs) *propertyType {
t := &propertyType{
kind: kindObject,
}
if info != nil {
t.typ = info.Type
t.nestedType = info.NestedType
t.altTypes = info.AltTypes
t.asset = info.Asset
}
var propertyInfos map[string]*tfbridge.SchemaInfo
if info != nil {
propertyInfos = info.Fields
}
for _, key := range stableSchemas(res.Schema()) {
propertySchema := res.Schema().Get(key)
var propertyInfo *tfbridge.SchemaInfo
if propertyInfos != nil {
propertyInfo = propertyInfos[key]
}
// TODO: Figure out why counting whether this description came from the attributes seems wrong.
// With AWS, counting this takes the takes number of arg descriptions from attribs from about 170 to about 1400.
// This seems wrong, so we ignore the second return value here for now.
doc, _ := getNestedDescriptionFromParsedDocs(entityDocs, objectName, key)
if v := g.propertyVariable(typePath, key,
propertySchema, propertyInfo, doc, "", out, entityDocs); v != nil {
t.properties = append(t.properties, v)
}
}
return t
}
func (t *propertyType) equals(other *propertyType) bool {
if t == nil && other == nil {
return true
}
if (t != nil) != (other != nil) {
return false
}
if t.name != other.name {
return false
}
if t.kind != other.kind {
return false
}
if !t.element.equals(other.element) {
return false
}
if len(t.properties) != len(other.properties) {
return false
}
for i, p := range t.properties {
o := other.properties[i]
if p.name != o.name {
return false
}
if p.optional() != o.optional() {
return false
}
if !p.typ.equals(o.typ) {
return false
}
}
if t.typ != other.typ {
return false
}
if t.nestedType != other.nestedType {
return false
}
if t.asset != nil && (other.asset == nil || *t.asset != *other.asset) {
return false
} else if other.asset != nil {
return false
}
if len(t.altTypes) != len(other.altTypes) {
return false
}
for i, t := range t.altTypes {
if t != other.altTypes[i] {
return false
}
}
return true
}
// variable is a schematized variable, property, argument, or return type.
type variable struct {
name string
out bool
opt bool
config bool // config is true if this variable represents a Pulumi config value.
doc string
rawdoc string
schema shim.Schema
info *tfbridge.SchemaInfo
typ *propertyType
parentPath paths.TypePath
propertyName paths.PropertyName
}
func (v *variable) Name() string { return v.name }
func (v *variable) Doc() string { return v.doc }
func (v *variable) deprecationMessage() string {
if v.schema != nil && v.schema.Deprecated() != "" {
return v.schema.Deprecated()
}
if v.info != nil && v.info.DeprecationMessage != "" {
return v.info.DeprecationMessage
}
return ""
}
func (v *variable) forceNew() bool {
// Output properties don't forceNew so we can return false by default
if v.out {
return false
}
// if we have an explicit marked as ForceNew then let's return that as that overrides
// the TF schema
if v.info != nil && v.info.ForceNew != nil {
return *v.info.ForceNew
}
return v.schema != nil && v.schema.ForceNew()
}
// optional checks whether the given property is optional, either due to Terraform or an overlay.
func (v *variable) optional() bool {
if v.opt {
return true
}
//if we have an explicit marked as optional then let's return that
if v.info != nil && v.info.MarkAsOptional != nil {
return *v.info.MarkAsOptional
}
// If we're checking a property used in an output position, it isn't optional if it's computed.
//
// Note that config values with custom defaults are _not_ considered optional unless they are marked as such.
customDefault := !v.config && v.info != nil && v.info.HasDefault()
if v.out {
return v.schema != nil && v.schema.Optional() && !v.schema.Computed() && !customDefault
}
return (v.schema != nil && v.schema.Optional() || v.schema.Computed()) || customDefault
}
// resourceType is a generated resource type that represents a Pulumi CustomResource definition.
type resourceType struct {
mod tokens.Module
name string
doc string
isProvider bool
inprops []*variable
outprops []*variable
reqprops map[string]bool
argst *propertyType // input properties.
statet *propertyType // output properties (all optional).
schema shim.Resource
info *tfbridge.ResourceInfo
entityDocs entityDocs // parsed docs.
resourcePath *paths.ResourcePath
}
func (rt *resourceType) Name() string { return rt.name }
func (rt *resourceType) Doc() string { return rt.doc }
// IsProvider is true if this resource is a ProviderResource.
func (rt *resourceType) IsProvider() bool { return rt.isProvider }
func (rt *resourceType) TypeToken() tokens.Type {
return tokens.NewTypeToken(rt.mod, tokens.TypeName(rt.name))
}
func newResourceType(resourcePath *paths.ResourcePath,
mod tokens.Module, name tokens.TypeName, entityDocs entityDocs,
schema shim.Resource, info *tfbridge.ResourceInfo,
isProvider bool) *resourceType {
// We want to add the import details to the description so we can display those for the user
description := entityDocs.Description
if entityDocs.Import != "" {
description = fmt.Sprintf("%s\n\n%s", description, entityDocs.Import)
}
return &resourceType{
mod: mod,
name: name.String(),
doc: description,
isProvider: isProvider,
schema: schema,
info: info,
reqprops: make(map[string]bool),
entityDocs: entityDocs,
resourcePath: resourcePath,
}
}
// resourceFunc is a generated resource function that is exposed to interact with Pulumi objects.
type resourceFunc struct {
mod tokens.Module
name string
doc string
args []*variable
rets []*variable
reqargs map[string]bool
argst *propertyType
retst *propertyType
schema shim.Resource
info *tfbridge.DataSourceInfo
entityDocs entityDocs
dataSourcePath *paths.DataSourcePath
}
func (rf *resourceFunc) Name() string { return rf.name }
func (rf *resourceFunc) Doc() string { return rf.doc }
func (rf *resourceFunc) ModuleMemberToken() tokens.ModuleMember {
return tokens.NewModuleMemberToken(rf.mod, tokens.ModuleMemberName(rf.name))
}
// overlayFile is a file that should be added to a module "as-is" and then exported from its index.
type overlayFile struct {
name string
src string
}
func (of *overlayFile) Name() string { return of.name }
func (of *overlayFile) Doc() string { return "" }
func (of *overlayFile) Copy() bool { return of.src != "" }
func GenerateSchema(info tfbridge.ProviderInfo, sink diag.Sink) (pschema.PackageSpec, error) {
g, err := NewGenerator(GeneratorOptions{
Package: info.Name,
Version: info.Version,
Language: Schema,
ProviderInfo: info,
Root: afero.NewMemMapFs(),
Sink: sink,
})
if err != nil {
return pschema.PackageSpec{}, errors.Wrapf(err, "failed to create generator")
}
pack, err := g.gatherPackage()
if err != nil {
return pschema.PackageSpec{}, errors.Wrapf(err, "failed to gather package metadata")
}
return genPulumiSchema(pack, g.pkg, g.version, g.info)
}
type GeneratorOptions struct {
Package string
Version string
Language Language
ProviderInfo tfbridge.ProviderInfo
Root afero.Fs
ProviderInfoSource il.ProviderInfoSource
PluginHost plugin.Host
TerraformVersion string
Sink diag.Sink
Debug bool
SkipDocs bool
SkipExamples bool
CoverageTracker *CoverageTracker
}
// NewGenerator returns a code-generator for the given language runtime and package info.
func NewGenerator(opts GeneratorOptions) (*Generator, error) {
pkgName, version, lang, info, root := opts.Package, opts.Version, opts.Language, opts.ProviderInfo, opts.Root
pkg := tokens.NewPackageToken(tokens.PackageName(tokens.IntoQName(pkgName)))
// Ensure the language is valid.
switch lang {
case Golang, NodeJS, Python, CSharp, Schema, PCL:
// OK
default:
return nil, errors.Errorf("unrecognized language runtime: %s", lang)
}
// If root is nil, default to sdk/<language>/ in the pwd.
if root == nil {
p, err := os.Getwd()
if err != nil {
return nil, err
}
p = filepath.Join(p, defaultOutDir, string(lang))
if err = os.MkdirAll(p, 0700); err != nil {
return nil, err
}
root = afero.NewBasePathFs(afero.NewOsFs(), p)
}
sink := opts.Sink
if sink == nil {
diagOpts := diag.FormatOptions{
Color: cmdutil.GetGlobalColorization(),
Debug: opts.Debug,
}
cmdutil.InitDiag(diagOpts)
sink = cmdutil.Diag()
}
pluginHost := opts.PluginHost
if pluginHost == nil {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
ctx, err := plugin.NewContext(sink, sink, nil, nil, cwd, nil, false, nil)
if err != nil {
return nil, err
}
pluginHost = ctx.Host
}
infoSources := append([]il.ProviderInfoSource{}, opts.ProviderInfoSource, il.PluginProviderInfoSource)
infoSource := il.NewCachingProviderInfoSource(il.NewMultiProviderInfoSource(infoSources...))
providerShim := newInMemoryProvider(pkg, nil, info)
host := &inmemoryProviderHost{
Host: pluginHost,
ProviderInfoSource: infoSource,
provider: providerShim,
}
return &Generator{
pkg: pkg,
version: version,
language: lang,
info: info,
root: root,
providerShim: providerShim,
pluginHost: &cachingProviderHost{
Host: host,
cache: map[string]plugin.Provider{},
},
packageCache: pcl.NewPackageCache(),
infoSource: host,
terraformVersion: opts.TerraformVersion,
sink: sink,
skipDocs: opts.SkipDocs,
skipExamples: opts.SkipExamples,
coverageTracker: opts.CoverageTracker,
}, nil
}
func (g *Generator) error(f string, args ...interface{}) {
g.sink.Errorf(diag.Message("", f), args...)
}
func (g *Generator) warn(f string, args ...interface{}) {
g.sink.Warningf(diag.Message("", f), args...)
}
func (g *Generator) debug(f string, args ...interface{}) {
g.sink.Debugf(diag.Message("", f), args...)
}
func (g *Generator) provider() shim.Provider {
return g.info.P
}
type GenerateOptions struct {
ModuleFormat string
}
// Generate creates Pulumi packages from the information it was initialized with.
func (g *Generator) Generate() error {
// First gather up the entire package contents. This structure is complete and sufficient to hand off
// to the language-specific generators to create the full output.
pack, err := g.gatherPackage()
if err != nil {
return errors.Wrapf(err, "failed to gather package metadata")
}
// Convert the package to a Pulumi schema.
pulumiPackageSpec, err := genPulumiSchema(pack, g.pkg, g.version, g.info)
if err != nil {
return errors.Wrapf(err, "failed to create Pulumi schema")
}
schemaStats = schemaTools.CountStats(pulumiPackageSpec)
// Serialize the schema and attach it to the provider shim.
g.providerShim.schema, err = json.Marshal(pulumiPackageSpec)
if err != nil {
return errors.Wrapf(err, "failed to marshal intermediate schema")
}
// Add any supplemental examples:
err = addExtraHclExamplesToResources(g.info.ExtraResourceHclExamples, &pulumiPackageSpec)
if err != nil {
return err
}
err = addExtraHclExamplesToFunctions(g.info.ExtraFunctionHclExamples, &pulumiPackageSpec)
if err != nil {
return err
}
// Convert examples.
if !g.skipExamples {
pulumiPackageSpec = g.convertExamplesInSchema(pulumiPackageSpec)
}
// Go ahead and let the language generator do its thing. If we're emitting the schema, just go ahead and serialize
// it out.
var files map[string][]byte
switch g.language {
case Schema:
// Omit the version so that the spec is stable if the version is e.g. derived from the current Git commit hash.
pulumiPackageSpec.Version = ""
bytes, err := json.MarshalIndent(pulumiPackageSpec, "", " ")
if err != nil {
return errors.Wrapf(err, "failed to marshal schema")
}
files = map[string][]byte{"schema.json": bytes}
case PCL:
if g.skipExamples {
return fmt.Errorf("Cannot set skipExamples and get PCL")
}
files = map[string][]byte{}
for path, code := range g.convertedCode {
path = strings.TrimPrefix(path, "#/") + ".pp"
files[path] = code
}
default:
pulumiPackage, diags, err := pschema.BindSpec(pulumiPackageSpec, nil)
if err != nil {
return errors.Wrapf(err, "failed to import Pulumi schema")
}
if diags.HasErrors() {
return err
}
if files, err = g.language.emitSDK(pulumiPackage, g.info, g.root); err != nil {
return errors.Wrapf(err, "failed to generate package")
}
}
// Write the result to disk. Do not overwrite the root-level README.md if any exists.
for f, contents := range files {
if f == "README.md" {
if _, err := g.root.Stat(f); err == nil {
continue
}
}
if err := emitFile(g.root, f, contents); err != nil {
return errors.Wrapf(err, "emitting file %v", f)
}
}
// Emit the Pulumi project information.
if err = g.emitProjectMetadata(pack); err != nil {
return errors.Wrapf(err, "failed to create project file")
}
// Print out some documentation stats as a summary afterwards.
printDocStats()
// Close the plugin host.
g.pluginHost.Close()
return nil
}
// gatherPackage creates a package plus module structure for the entire set of members of this package.
func (g *Generator) gatherPackage() (*pkg, error) {
// First, gather up the entire package/module structure. This includes gathering config entries, resources,
// data sources, and any supporting type information, and placing them into modules.
pack := newPkg(g.pkg, g.version, g.language, g.root)
// Place all configuration variables into a single config module.
if cfg := g.gatherConfig(); cfg != nil {
pack.addModule(cfg)
}
// Gather the provider type for this package.
provider, err := g.gatherProvider()
if err != nil {
return nil, errors.Wrapf(err, "problem gathering the provider type")
}
pack.provider = provider
// Gather up all resource modules and merge them into the current set.
resmods, err := g.gatherResources()
if err != nil {
return nil, errors.Wrapf(err, "problem gathering resources")
} else if resmods != nil {
pack.addModuleMap(resmods)
}
// Gather up all data sources into their respective modules and merge them in.
dsmods, err := g.gatherDataSources()
if err != nil {
return nil, errors.Wrapf(err, "problem gathering data sources")
} else if dsmods != nil {
pack.addModuleMap(dsmods)
}
// Now go ahead and merge in any overlays into the modules if there are any.
olaymods, err := g.gatherOverlays()
if err != nil {
return nil, errors.Wrapf(err, "problem gathering overlays")
} else if olaymods != nil {
pack.addModuleMap(olaymods)
}
return pack, nil
}
// gatherConfig returns the configuration module for this package.
func (g *Generator) gatherConfig() *module {
// If there's no config, skip creating the module.
cfg := g.provider().Schema()
if cfg.Len() == 0 {
return nil
}
config := newModule(tokens.NewModuleToken(g.pkg, configMod))
// Sort the config variables to ensure they are emitted in a deterministic order.
custom := g.info.Config
var cfgkeys []string
cfg.Range(func(key string, _ shim.Schema) bool {
cfgkeys = append(cfgkeys, key)
return true
})
sort.Strings(cfgkeys)
cfgPath := paths.NewConfigPath()
// Add an entry for each config variable.
for _, key := range cfgkeys {
// Generate a name and type to use for this key.
sch := cfg.Get(key)
prop := g.propertyVariable(cfgPath,
key, sch, custom[key], "", sch.Description(), true /*out*/, entityDocs{})
if prop != nil {
prop.config = true
config.addMember(prop)
}
}
// Ensure there weren't any keys that were unrecognized.
for key := range custom {
if _, has := cfg.GetOk(key); !has {
g.warn("custom config schema %s was not present in the Terraform metadata", key)
}
}
// Now, if there are any extra config variables, that are Pulumi-only, add them.
for key, val := range g.info.ExtraConfig {
if prop := g.propertyVariable(cfgPath,
key, val.Schema, val.Info, "", "", true /*out*/, entityDocs{}); prop != nil {
prop.config = true
config.addMember(prop)
}
}
return config
}
// gatherProvider returns the provider resource for this package.
func (g *Generator) gatherProvider() (*resourceType, error) {
cfg := g.provider().Schema()
if cfg == nil {
cfg = schema.SchemaMap{}
}
info := &tfbridge.ResourceInfo{
Tok: tokens.Type(g.pkg.String()),
Fields: g.info.Config,
}
res, err := g.gatherResource("", (&schema.Resource{Schema: cfg}).Shim(), info, true)
return res, err
}
// gatherResources returns all modules and their resources.
func (g *Generator) gatherResources() (moduleMap, error) {
// If there aren't any resources, skip this altogether.
resources := g.provider().ResourcesMap()
if resources.Len() == 0 {
return nil, nil
}
modules := make(moduleMap)
skipFailBuildOnMissingMapError := isTruthy(os.Getenv("PULUMI_SKIP_MISSING_MAPPING_ERROR")) || isTruthy(os.Getenv(
"PULUMI_SKIP_PROVIDER_MAP_ERROR"))
skipFailBuildOnExtraMapError := isTruthy(os.Getenv("PULUMI_SKIP_EXTRA_MAPPING_ERROR"))
// let's keep a list of TF mapping errors that we can present to the user
var resourceMappingErrors error
// For each resource, create its own dedicated type and module export.
var reserr error
seen := make(map[string]bool)
for _, r := range stableResources(resources) {
info := g.info.Resources[r]
if info == nil {
if ignoreMappingError(g.info.IgnoreMappings, r) {
g.debug("TF resource %q not found in provider map", r)
continue
}
if !ignoreMappingError(g.info.IgnoreMappings, r) && !skipFailBuildOnMissingMapError {
resourceMappingErrors = multierror.Append(resourceMappingErrors,
fmt.Errorf("TF resource %q not mapped to the Pulumi provider", r))