pulumi/pkg/importer/language.go

234 lines
6.7 KiB
Go
Raw Normal View History

// 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.
package importer
import (
"bytes"
"fmt"
"io"
"strings"
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/pcl"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// A LangaugeGenerator generates code for a given Pulumi program to an io.Writer.
type LanguageGenerator func(w io.Writer, p *pcl.Program) error
// A NameTable maps URNs to language-specific variable names.
type NameTable map[resource.URN]string
// A DiagnosticsError captures HCL2 diagnostics.
type DiagnosticsError struct {
diagnostics hcl.Diagnostics
newDiagnosticWriter func(w io.Writer, width uint, color bool) hcl.DiagnosticWriter
}
func (e *DiagnosticsError) Diagnostics() hcl.Diagnostics {
return e.diagnostics
}
// NewDiagnosticWriter returns an hcl.DiagnosticWriter that can be used to render the error's diagnostics.
func (e *DiagnosticsError) NewDiagnosticWriter(w io.Writer, width uint, color bool) hcl.DiagnosticWriter {
return e.newDiagnosticWriter(w, width, color)
}
func (e *DiagnosticsError) Error() string {
var text bytes.Buffer
err := e.NewDiagnosticWriter(&text, 0, false).WriteDiagnostics(e.diagnostics)
contract.IgnoreError(err)
return text.String()
}
func (e *DiagnosticsError) String() string {
return e.Error()
}
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
func removeDuplicatePathedValues(pathedValues []PathedLiteralValue) []PathedLiteralValue {
uniqueValues := make([]PathedLiteralValue, 0)
occurrences := make(map[string]int)
for _, pathedValue := range pathedValues {
occurrences[pathedValue.Value]++
}
for _, pathedValue := range pathedValues {
if occurrences[pathedValue.Value] > 1 {
// a value that has occurred multiple times is not unique
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
continue
}
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
uniqueValues = append(uniqueValues, pathedValue)
}
return uniqueValues
}
func nextPropertyPath(path hcl.Traversal, key hcl.Traverser) hcl.Traversal {
return append(path, key)
}
func createPathedValue(
root string,
property resource.PropertyValue,
currentPath hcl.Traversal,
) *PathedLiteralValue {
if property.IsNull() {
return nil
}
if property.IsString() {
return &PathedLiteralValue{
Root: root,
Value: property.StringValue(),
ExpressionReference: &model.ScopeTraversalExpression{
RootName: root,
Traversal: currentPath,
},
}
}
if property.IsSecret() {
// unwrap the secret
secret := property.SecretValue()
return createPathedValue(root, secret.Element, currentPath)
}
return nil
}
func sanitizeName(name string) string {
return strings.ReplaceAll(name, ".", "_")
}
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
func createImportState(states []*resource.State, names NameTable) ImportState {
pathedLiteralValues := make([]PathedLiteralValue, 0)
for _, state := range states {
resourceID := state.ID.String()
if resourceID == "" {
continue
}
name := sanitizeName(state.URN.Name())
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
pathedLiteralValues = append(pathedLiteralValues, PathedLiteralValue{
Root: name,
Value: resourceID,
ExpressionReference: &model.ScopeTraversalExpression{
RootName: name,
Traversal: hcl.Traversal{
hcl.TraverseRoot{Name: name},
hcl.TraverseAttr{Name: "id"},
},
},
})
initialPath := hcl.Traversal{hcl.TraverseRoot{Name: name}}
for key, value := range state.Outputs {
if string(key) == "name" || string(key) == "arn" {
nextPath := nextPropertyPath(initialPath, hcl.TraverseAttr{Name: string(key)})
if output := createPathedValue(name, value, nextPath); output != nil {
pathedLiteralValues = append(pathedLiteralValues, *output)
}
}
}
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
}
return ImportState{
Names: names,
PathedLiteralValues: pathedLiteralValues,
[engine/import] Guess ID references of dependant resources when generating code for import operations (#16208) ### Description Taking an initial attempt at #10025 where we now try to guess ID references of dependant resources instead of writing out the IDs as literal values. Instead of: ```hcl // has ID=provider-generated-bucket-id-abc123 resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = "provider-generated-bucket-id-abc123" storageClass = "STANDARD" } ``` We generate: ```hcl resource exampleBucket "aws:s3/bucket:Bucket" {} resource exampleBucketObject "aws:s3/bucketObject:BucketObject" { bucket = exampleBucket.id storageClass = "STANDARD" } ``` This implies a dependency between `exampleBucketObject` and `exampleBucket` without explicitly being added into the `dependsOn` array (it would be redundant) ## Checklist - [x] I have run `make tidy` to update any new dependencies - [x] I have run `make lint` to verify my code passes the lint check - [ ] I have formatted my code using `gofumpt` <!--- Please provide details if the checkbox below is to be left unchecked. --> - [x] I have added tests that prove my fix is effective or that my feature works <!--- User-facing changes require a CHANGELOG entry. --> - [ ] I have run `make changelog` and committed the `changelog/pending/<file>` documenting my change <!-- If the change(s) in this PR is a modification of an existing call to the Pulumi Cloud, then the service should honor older versions of the CLI where this change would not exist. You must then bump the API version in /pkg/backend/httpstate/client/api.go, as well as add it to the service. --> - [ ] Yes, there are changes in this PR that warrants bumping the Pulumi Cloud API version <!-- @Pulumi employees: If yes, you must submit corresponding changes in the service repo. -->
2024-05-20 17:00:16 +00:00
}
}
// GenerateLanguageDefintions generates a list of resource definitions from the given resource states.
func GenerateLanguageDefinitions(w io.Writer, loader schema.Loader, gen LanguageGenerator, states []*resource.State,
all: Reformat with gofumpt Per team discussion, switching to gofumpt. [gofumpt][1] is an alternative, stricter alternative to gofmt. It addresses other stylistic concerns that gofmt doesn't yet cover. [1]: https://github.com/mvdan/gofumpt See the full list of [Added rules][2], but it includes: - Dropping empty lines around function bodies - Dropping unnecessary variable grouping when there's only one variable - Ensuring an empty line between multi-line functions - simplification (`-s` in gofmt) is always enabled - Ensuring multi-line function signatures end with `) {` on a separate line. [2]: https://github.com/mvdan/gofumpt#Added-rules gofumpt is stricter, but there's no lock-in. All gofumpt output is valid gofmt output, so if we decide we don't like it, it's easy to switch back without any code changes. gofumpt support is built into the tooling we use for development so this won't change development workflows. - golangci-lint includes a gofumpt check (enabled in this PR) - gopls, the LSP for Go, includes a gofumpt option (see [installation instrutions][3]) [3]: https://github.com/mvdan/gofumpt#installation This change was generated by running: ```bash gofumpt -w $(rg --files -g '*.go' | rg -v testdata | rg -v compilation_error) ``` The following files were manually tweaked afterwards: - pkg/cmd/pulumi/stack_change_secrets_provider.go: one of the lines overflowed and had comments in an inconvenient place - pkg/cmd/pulumi/destroy.go: `var x T = y` where `T` wasn't necessary - pkg/cmd/pulumi/policy_new.go: long line because of error message - pkg/backend/snapshot_test.go: long line trying to assign three variables in the same assignment I have included mention of gofumpt in the CONTRIBUTING.md.
2023-03-03 16:36:39 +00:00
names NameTable,
) error {
generateProgramText := func(importState ImportState) (*pcl.Program, hcl.Diagnostics, error) {
var hcl2Text bytes.Buffer
for i, state := range states {
hcl2Def, err := GenerateHCL2Definition(loader, state, importState)
if err != nil {
return nil, nil, err
}
pre := ""
if i > 0 {
pre = "\n"
}
_, err = fmt.Fprintf(&hcl2Text, "%s%v", pre, hcl2Def)
contract.IgnoreError(err)
}
parser := syntax.NewParser()
if err := parser.ParseFile(&hcl2Text, "anonymous.pp"); err != nil {
return nil, nil, err
}
if parser.Diagnostics.HasErrors() {
// HCL2 text generation should always generate proper code.
return nil, nil, fmt.Errorf("internal error: %w", &DiagnosticsError{
diagnostics: parser.Diagnostics,
newDiagnosticWriter: parser.NewDiagnosticWriter,
})
}
return pcl.BindProgram(parser.Files, pcl.Loader(loader), pcl.AllowMissingVariables)
}
importState := createImportState(states, names)
program, diags, err := generateProgramText(importState)
if err != nil {
if strings.Contains(err.Error(), "circular reference") {
// hitting an edge case when guessing references between resources
// this happens when an input of a _parent_ resource is equal to the ID of a _child_ resource
// for example importing the following program:
// const bucket = new aws.s3.Bucket("my-bucket", {
// website: {
// indexDocument: "index.html",
// },
// });
//
// const bucketObject = new aws.s3.BucketObject("index.html", {
// bucket: bucket.id
// });
// fallback to the old code path where we don't guess references
// and instead just generate the code with the outputs as literals
program, diags, err = generateProgramText(ImportState{Names: names})
if err != nil {
return nil
}
} else {
return err
}
}
if diags.HasErrors() {
// It is possible that the provided states do not contain appropriately-shaped inputs, so this may be user
// error.
return &DiagnosticsError{
diagnostics: diags,
newDiagnosticWriter: program.NewDiagnosticWriter,
}
}
return gen(w, program)
}