Merge remote-tracking branch 'origin/master' into ctpp

This commit is contained in:
Fraser Waters 2021-11-15 10:02:29 +00:00
commit 83e655e19f
162 changed files with 2853 additions and 799 deletions

View file

@ -16,10 +16,9 @@
"remoteUser": "user",
"extensions": ["golang.go", "ms-dotnettools.csharp", "ms-python.python"],
"extensions": ["golang.go", "ms-dotnettools.csharp", "ms-python.python", "formulahendry.dotnet-test-explorer"],
// We want to dotnet restore all projects on startup so that omnisharp doesn't complain about lots of missing types on startup.
"postCreateCommand": "find -name \"*.??proj\" | xargs -L1 dotnet restore",
"postCreateCommand": "make ensure",
"settings": {
"extensions.ignoreRecommendations": true

View file

@ -160,6 +160,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -229,6 +230,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -303,6 +305,9 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet }}
- name: Create Local Nuget
run: mkdir -p "${{ env.PULUMI_LOCAL_NUGET }}"
shell: bash
- run: dotnet nuget add source ${{ env.PULUMI_LOCAL_NUGET }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1

View file

@ -143,6 +143,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -206,6 +207,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -280,6 +282,9 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet }}
- name: Create Local Nuget
run: mkdir -p "${{ env.PULUMI_LOCAL_NUGET }}"
shell: bash
- run: dotnet nuget add source ${{ env.PULUMI_LOCAL_NUGET }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -295,9 +300,6 @@ jobs:
python-version: ${{ matrix.python-version }}
- name: Clean
run: dotnet nuget locals all --clear
- name: Create Local Nuget
run: mkdir -p "D:\\Pulumi\\nuget"
shell: bash
- name: Install Python Deps
run: |
pip3 install pyenv-win

View file

@ -236,6 +236,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -305,6 +306,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -386,6 +388,9 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet }}
- name: Create Local Nuget
run: mkdir -p "${{ env.PULUMI_LOCAL_NUGET }}"
shell: bash
- run: dotnet nuget add source ${{ env.PULUMI_LOCAL_NUGET }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1

View file

@ -82,6 +82,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -170,6 +171,7 @@ jobs:
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ matrix.dotnet-version }}
- run: mkdir -p ${{ runner.temp }}/opt/pulumi/nuget
- run: dotnet nuget add source ${{ runner.temp }}/opt/pulumi/nuget
- name: Set up Node ${{ matrix.node-version }}
uses: actions/setup-node@v1
@ -279,6 +281,9 @@ jobs:
run: |
pip3 install pyenv-win
pip3 install pipenv
- name: Create Local Nuget
run: mkdir -p "${{ env.PULUMI_LOCAL_NUGET }}"
shell: bash
- run: dotnet nuget add source ${{ env.PULUMI_LOCAL_NUGET }}
- name: Set Build Env Vars
shell: bash

View file

@ -11,4 +11,7 @@
// Experimental but seems to work and means we don't need a vscode instance per go.mod file.
"experimentalWorkspaceModule": true,
},
"omnisharp.defaultLaunchSolution": "sdk/dotnet/dotnet.sln",
"dotnet-test-explorer.testProjectPath": "sdk/dotnet",
}

View file

@ -1,18 +1,16 @@
### Improvements
- [codegen/docs] Edit docs codegen to document `$fnOutput` function
invoke forms in API documentation.
[#8287](https://github.com/pulumi/pulumi/pull/8287)
- [CLI] Adding the ability to use `pulumi org set [name]` to set a default org
to use when creating a stacks in the Pulumi Service backend or Self -hosted Service
[#8352](https://github.com/pulumi/pulumi/pull/8352)
- [schema] Add IsOverlay option to disable codegen for particular types
[#8338](https://github.com/pulumi/pulumi/pull/8338)
- [sdk/dotnet] - Marshal output values.
[#8316](https://github.com/pulumi/pulumi/pull/8316)
### Bug Fixes
- [automation/python] - Fix deserialization of events.
[#8375](https://github.com/pulumi/pulumi/pull/8375)
- [sdk/dotnet] - Fixes failing preview for programs that call data
sources (`F.Invoke`) with unknown outputs
[#8339](https://github.com/pulumi/pulumi/pull/8339)
- [programgen/go] - Don't change imported resource names.
[#8353](https://github.com/pulumi/pulumi/pull/8353)
- [engine] - Compute dependents correctly during targeted deletes.
[#8360](https://github.com/pulumi/pulumi/pull/8360)

View file

@ -297,7 +297,7 @@ Enum: `"boolean"` | `"integer"` | `"number"` | `"string"`
#### `deprecationMessage`
Indicates whether or not the value is deprecated.
Indicates whether the value is deprecated.
`string`
@ -339,7 +339,7 @@ Describes a function.
#### `deprecationMessage`
Indicates whether or not the function is deprecated
Indicates whether the function is deprecated
`string`
@ -564,7 +564,7 @@ Additional language-specific data about the default value.
#### `deprecationMessage`
Indicates whether or not the property is deprecated
Indicates whether the property is deprecated
`string`
@ -627,7 +627,7 @@ Items: [Alias Definition](#alias-definition)
#### `deprecationMessage`
Indicates whether or not the resource is deprecated
Indicates whether the resource is deprecated
`string`
@ -653,7 +653,15 @@ Additional properties: [Property Definition](#property-definition)
#### `isComponent`
Indicates whether or not the resource is a component.
Indicates whether the resource is a component.
`boolean`
---
#### `isOverlay`
Indicates whether the resource is an overlay (code is generated by the package rather than by the core Pulumi codegen).
`boolean`

View file

@ -21,7 +21,6 @@ import (
"os"
"strings"
"github.com/pkg/errors"
survey "gopkg.in/AlecAivazis/survey.v1"
surveycore "gopkg.in/AlecAivazis/survey.v1/core"
@ -172,7 +171,7 @@ func confirmBeforeUpdating(kind apitype.UpdateKind, stack Stack,
Options: choices,
Default: string(no),
}, &response, nil); err != nil {
return result.FromError(errors.Wrapf(err, "confirmation cancelled, not proceeding with the %s", kind))
return result.FromError(fmt.Errorf("confirmation cancelled, not proceeding with the %s: %w", kind, err))
}
if response == string(no) {

View file

@ -16,12 +16,11 @@ package backend
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/operations"
@ -298,7 +297,7 @@ func (c *backendClient) GetStackOutputs(ctx context.Context, name string) (resou
return nil, err
}
if s == nil {
return nil, errors.Errorf("unknown stack %q", name)
return nil, fmt.Errorf("unknown stack %q", name)
}
snap, err := s.Snapshot(ctx)
if err != nil {
@ -306,7 +305,7 @@ func (c *backendClient) GetStackOutputs(ctx context.Context, name string) (resou
}
res, err := stack.GetRootStackResource(snap)
if err != nil {
return nil, errors.Wrap(err, "getting root stack resources")
return nil, fmt.Errorf("getting root stack resources: %w", err)
}
if res == nil {
return resource.PropertyMap{}, nil
@ -325,7 +324,7 @@ func (c *backendClient) GetStackResourceOutputs(
return nil, err
}
if s == nil {
return nil, errors.Errorf("unknown stack %q", name)
return nil, fmt.Errorf("unknown stack %q", name)
}
snap, err := s.Snapshot(ctx)
if err != nil {

View file

@ -1,7 +1,7 @@
package display
import (
"github.com/pkg/errors"
"fmt"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/resource/stack"
@ -21,7 +21,7 @@ func ConvertEngineEvent(e engine.Event) (apitype.EngineEvent, error) {
var apiEvent apitype.EngineEvent
// Error to return if the payload doesn't match expected.
eventTypePayloadMismatch := errors.Errorf("unexpected payload for event type %v", e.Type)
eventTypePayloadMismatch := fmt.Errorf("unexpected payload for event type %v", e.Type)
switch e.Type {
case engine.CancelEvent:
@ -130,7 +130,7 @@ func ConvertEngineEvent(e engine.Event) (apitype.EngineEvent, error) {
}
default:
return apiEvent, errors.Errorf("unknown event type %q", e.Type)
return apiEvent, fmt.Errorf("unknown event type %q", e.Type)
}
return apiEvent, nil

View file

@ -17,6 +17,7 @@ package filestate
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
@ -28,7 +29,7 @@ import (
"time"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
user "github.com/tweekmonster/luser"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob" // driver for azblob://
@ -103,7 +104,7 @@ const FilePathPrefix = "file://"
func New(d diag.Sink, originalURL string) (Backend, error) {
if !IsFileStateBackendURL(originalURL) {
return nil, errors.Errorf("local URL %s has an illegal prefix; expected one of: %s",
return nil, fmt.Errorf("local URL %s has an illegal prefix; expected one of: %s",
originalURL, strings.Join(blob.DefaultURLMux().BucketSchemes(), ", "))
}
@ -130,7 +131,7 @@ func New(d diag.Sink, originalURL string) (Backend, error) {
bucket, err := blobmux.OpenBucket(context.TODO(), u)
if err != nil {
return nil, errors.Wrapf(err, "unable to open bucket %s", u)
return nil, fmt.Errorf("unable to open bucket %s: %w", u, err)
}
if !strings.HasPrefix(u, FilePathPrefix) {
@ -178,7 +179,7 @@ func massageBlobPath(path string) (string, error) {
if strings.HasPrefix(path, "~") {
usr, err := user.Current()
if err != nil {
return "", errors.Wrap(err, "Could not determine current user to resolve `file://~` path.")
return "", fmt.Errorf("Could not determine current user to resolve `file://~` path.: %w", err)
}
if path == "~" {
@ -191,7 +192,7 @@ func massageBlobPath(path string) (string, error) {
// For file:// backend, ensure a relative path is resolved. fileblob only supports absolute paths.
path, err := filepath.Abs(path)
if err != nil {
return "", errors.Wrap(err, "An IO error occurred while building the absolute path")
return "", fmt.Errorf("An IO error occurred while building the absolute path: %w", err)
}
// Using example from https://godoc.org/gocloud.dev/blob/fileblob#example-package--OpenBucket
@ -300,10 +301,10 @@ func (b *localBackend) CreateStack(ctx context.Context, stackRef backend.StackRe
tags, err := backend.GetEnvironmentTagsForCurrentStack()
if err != nil {
return nil, errors.Wrap(err, "getting stack tags")
return nil, fmt.Errorf("getting stack tags: %w", err)
}
if err = validation.ValidateStackProperties(string(stackName), tags); err != nil {
return nil, errors.Wrap(err, "validating stack properties")
return nil, fmt.Errorf("validating stack properties: %w", err)
}
file, err := b.saveStack(stackName, nil, nil)
@ -320,8 +321,9 @@ func (b *localBackend) CreateStack(ctx context.Context, stackRef backend.StackRe
func (b *localBackend) GetStack(ctx context.Context, stackRef backend.StackReference) (backend.Stack, error) {
stackName := stackRef.Name()
snapshot, path, err := b.getStack(stackName)
switch {
case gcerrors.Code(errors.Cause(err)) == gcerrors.NotFound:
case gcerrors.Code(drillError(err)) == gcerrors.NotFound:
return nil, nil
case err != nil:
return nil, err
@ -410,7 +412,7 @@ func (b *localBackend) RenameStack(ctx context.Context, stack backend.Stack,
return nil, err
}
if hasExisting {
return nil, errors.Errorf("a stack named %s already exists", newName)
return nil, fmt.Errorf("a stack named %s already exists", newName)
}
// If we have a snapshot, we need to rename the URNs inside it to use the new stack name.
@ -664,11 +666,11 @@ func (b *localBackend) apply(
if saveErr != nil {
// We swallow backupErr as it is less important than the saveErr.
return plan, changes, result.FromError(errors.Wrap(saveErr, "saving update info"))
return plan, changes, result.FromError(fmt.Errorf("saving update info: %w", saveErr))
}
if backupErr != nil {
return plan, changes, result.FromError(errors.Wrap(backupErr, "saving backup"))
return plan, changes, result.FromError(fmt.Errorf("saving backup: %w", backupErr))
}
// Make sure to print a link to the stack's checkpoint before exiting.
@ -777,7 +779,7 @@ func (b *localBackend) ExportDeployment(ctx context.Context,
sdep, err := stack.SerializeDeployment(snap, snap.SecretsManager /* showSecrsts */, false)
if err != nil {
return nil, errors.Wrap(err, "serializing deployment")
return nil, fmt.Errorf("serializing deployment: %w", err)
}
data, err := json.Marshal(sdep)
@ -841,7 +843,7 @@ func (b *localBackend) getLocalStacks() ([]tokens.QName, error) {
files, err := listBucket(b.bucket, path)
if err != nil {
return nil, errors.Wrap(err, "error listing stacks")
return nil, fmt.Errorf("error listing stacks: %w", err)
}
for _, file := range files {
@ -881,3 +883,12 @@ func (b *localBackend) UpdateStackTags(ctx context.Context,
// The local backend does not currently persist tags.
return errors.New("stack tags not supported in --local mode")
}
// Returns the original error in the chain. If `err` is nil, nil is returned.
func drillError(err error) error {
e := err
for errors.Unwrap(e) != nil {
e = errors.Unwrap(e)
}
return e
}

View file

@ -2,11 +2,11 @@ package filestate
import (
"context"
"fmt"
"io"
"path"
"path/filepath"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"gocloud.dev/blob"
)
@ -77,7 +77,7 @@ func listBucket(bucket Bucket, dir string) ([]*blob.ListObject, error) {
break
}
if err != nil {
return nil, errors.Wrap(err, "could not list bucket")
return nil, fmt.Errorf("could not list bucket: %w", err)
}
files = append(files, file)
}
@ -95,7 +95,7 @@ func objectName(obj *blob.ListObject) string {
func removeAllByPrefix(bucket Bucket, dir string) error {
files, err := listBucket(bucket, dir)
if err != nil {
return errors.Wrap(err, "unable to list bucket objects for removal")
return fmt.Errorf("unable to list bucket objects for removal: %w", err)
}
for _, file := range files {
@ -113,7 +113,7 @@ func removeAllByPrefix(bucket Bucket, dir string) error {
func renameObject(bucket Bucket, source string, dest string) error {
err := bucket.Copy(context.TODO(), dest, source, nil)
if err != nil {
return errors.Wrapf(err, "copying %s to %s", source, dest)
return fmt.Errorf("copying %s to %s: %w", source, dest, err)
}
err = bucket.Delete(context.TODO(), source)

View file

@ -3,6 +3,8 @@ package filestate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"golang.org/x/oauth2/google"
@ -11,7 +13,6 @@ import (
"cloud.google.com/go/storage"
"github.com/pkg/errors"
"gocloud.dev/blob"
"gocloud.dev/gcp"
)
@ -33,7 +34,7 @@ func googleCredentials(ctx context.Context) (*google.Credentials, error) {
// so that users can override the default creds
credentials, err := google.CredentialsFromJSON(ctx, []byte(creds), storage.ScopeReadWrite)
if err != nil {
return nil, errors.Wrap(err, "unable to parse credentials from $GOOGLE_CREDENTIALS")
return nil, fmt.Errorf("unable to parse credentials from $GOOGLE_CREDENTIALS: %w", err)
}
return credentials, nil
}
@ -43,7 +44,7 @@ func googleCredentials(ctx context.Context) (*google.Credentials, error) {
// 2. application_default_credentials.json file in ~/.config/gcloud or $APPDATA\gcloud
credentials, err := gcp.DefaultCredentials(ctx)
if err != nil {
return nil, errors.Wrap(err, "unable to find gcp credentials")
return nil, fmt.Errorf("unable to find gcp credentials: %w", err)
}
return credentials, nil
}

View file

@ -17,14 +17,13 @@ package filestate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/user"
"path"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"

View file

@ -17,6 +17,7 @@ package filestate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path"
@ -28,7 +29,6 @@ import (
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pkg/errors"
"gocloud.dev/blob"
"gocloud.dev/gcerrors"
@ -133,7 +133,7 @@ func (b *localBackend) getStack(name tokens.QName) (*deploy.Snapshot, string, er
chk, err := b.getCheckpoint(name)
if err != nil {
return nil, file, errors.Wrap(err, "failed to load checkpoint")
return nil, file, fmt.Errorf("failed to load checkpoint: %w", err)
}
// Materialize an actual snapshot object.
@ -145,8 +145,7 @@ func (b *localBackend) getStack(name tokens.QName) (*deploy.Snapshot, string, er
// Ensure the snapshot passes verification before returning it, to catch bugs early.
if !DisableIntegrityChecking {
if verifyerr := snapshot.VerifyIntegrity(); verifyerr != nil {
return nil, file,
errors.Wrapf(verifyerr, "%s: snapshot integrity failure; refusing to use it", file)
return nil, file, fmt.Errorf("%s: snapshot integrity failure; refusing to use it: %w", file, verifyerr)
}
}
@ -169,18 +168,18 @@ func (b *localBackend) saveStack(name tokens.QName, snap *deploy.Snapshot, sm se
file := b.stackPath(name)
m, ext := encoding.Detect(file)
if m == nil {
return "", errors.Errorf("resource serialization failed; illegal markup extension: '%v'", ext)
return "", fmt.Errorf("resource serialization failed; illegal markup extension: '%v'", ext)
}
if filepath.Ext(file) == "" {
file = file + ext
}
chk, err := stack.SerializeCheckpoint(name, snap, sm, false /* showSecrets */)
if err != nil {
return "", errors.Wrap(err, "serializaing checkpoint")
return "", fmt.Errorf("serializaing checkpoint: %w", err)
}
byts, err := m.Marshal(chk)
if err != nil {
return "", errors.Wrap(err, "An IO error occurred while marshalling the checkpoint")
return "", fmt.Errorf("An IO error occurred while marshalling the checkpoint: %w", err)
}
// Back up the existing file if it already exists.
@ -208,7 +207,7 @@ func (b *localBackend) saveStack(name tokens.QName, snap *deploy.Snapshot, sm se
if err != nil {
logging.V(7).Infof("Error while writing snapshot to: %s (attempt=%d, error=%s)", file, try, err)
if try > 10 {
return false, nil, errors.Wrap(err, "An IO error occurred while writing the new snapshot file")
return false, nil, fmt.Errorf("An IO error occurred while writing the new snapshot file: %w", err)
}
return false, nil, nil
}
@ -225,7 +224,7 @@ func (b *localBackend) saveStack(name tokens.QName, snap *deploy.Snapshot, sm se
// And if we are retaining historical checkpoint information, write it out again
if cmdutil.IsTruthy(os.Getenv("PULUMI_RETAIN_CHECKPOINTS")) {
if err = b.bucket.WriteAll(context.TODO(), fmt.Sprintf("%v.%v", file, time.Now().UnixNano()), byts, nil); err != nil {
return "", errors.Wrap(err, "An IO error occurred while writing the new snapshot file")
return "", fmt.Errorf("An IO error occurred while writing the new snapshot file: %w", err)
}
}
@ -234,9 +233,10 @@ func (b *localBackend) saveStack(name tokens.QName, snap *deploy.Snapshot, sm se
// out the checkpoint file since it may contain resource state updates. But we will warn the user that the
// file is already written and might be bad.
if verifyerr := snap.VerifyIntegrity(); verifyerr != nil {
return "", errors.Wrapf(verifyerr,
"%s: snapshot integrity failure; it was already written, but is invalid (backup available at %s)",
file, bck)
return "", fmt.Errorf(
"%s: snapshot integrity failure; it was already written, but is invalid (backup available at %s): %w",
file, bck, verifyerr)
}
}
@ -323,7 +323,7 @@ func (b *localBackend) getHistory(name tokens.QName, pageSize int, page int) ([]
allFiles, err := listBucket(b.bucket, dir)
if err != nil {
// History doesn't exist until a stack has been updated.
if gcerrors.Code(errors.Cause(err)) == gcerrors.NotFound {
if gcerrors.Code(drillError(err)) == gcerrors.NotFound {
return nil, nil
}
return nil, err
@ -368,11 +368,11 @@ func (b *localBackend) getHistory(name tokens.QName, pageSize int, page int) ([]
var update backend.UpdateInfo
b, err := b.bucket.ReadAll(context.TODO(), filepath)
if err != nil {
return nil, errors.Wrapf(err, "reading history file %s", filepath)
return nil, fmt.Errorf("reading history file %s: %w", filepath, err)
}
err = json.Unmarshal(b, &update)
if err != nil {
return nil, errors.Wrapf(err, "reading history file %s", filepath)
return nil, fmt.Errorf("reading history file %s: %w", filepath, err)
}
updates = append(updates, update)
@ -391,7 +391,7 @@ func (b *localBackend) renameHistory(oldName tokens.QName, newName tokens.QName)
allFiles, err := listBucket(b.bucket, oldHistory)
if err != nil {
// if there's nothing there, we don't really need to do a rename.
if gcerrors.Code(errors.Cause(err)) == gcerrors.NotFound {
if gcerrors.Code(drillError(err)) == gcerrors.NotFound {
return nil
}
return err
@ -407,10 +407,10 @@ func (b *localBackend) renameHistory(oldName tokens.QName, newName tokens.QName)
newBlob := path.Join(newHistory, newFileName)
if err := b.bucket.Copy(context.TODO(), newBlob, oldBlob, nil); err != nil {
return errors.Wrap(err, "copying history file")
return fmt.Errorf("copying history file: %w", err)
}
if err := b.bucket.Delete(context.TODO(), oldBlob); err != nil {
return errors.Wrap(err, "deleting existing history file")
return fmt.Errorf("deleting existing history file: %w", err)
}
}

View file

@ -18,6 +18,7 @@ import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
@ -31,7 +32,7 @@ import (
"time"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/skratchdot/open-golang/open"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -126,7 +127,7 @@ func New(d diag.Sink, cloudURL string) (Backend, error) {
cloudURL = ValueOrDefaultURL(cloudURL)
account, err := workspace.GetAccount(cloudURL)
if err != nil {
return nil, errors.Wrap(err, "getting stored credentials")
return nil, fmt.Errorf("getting stored credentials: %w", err)
}
apiToken := account.AccessToken
@ -163,13 +164,13 @@ func loginWithBrowser(ctx context.Context, d diag.Sink, cloudURL string, opts di
c := make(chan string)
l, err := net.Listen("tcp", "127.0.0.1:")
if err != nil {
return nil, errors.Wrap(err, "could not start listener")
return nil, fmt.Errorf("could not start listener: %w", err)
}
// Extract the port
_, port, err := net.SplitHostPort(l.Addr().String())
if err != nil {
return nil, errors.Wrap(err, "could not determine port")
return nil, fmt.Errorf("could not determine port: %w", err)
}
// Generate a nonce we'll send with the request.
@ -229,6 +230,10 @@ func loginWithBrowser(ctx context.Context, d diag.Sink, cloudURL string, opts di
return New(d, cloudURL)
}
func SetDefaultOrg(url string, orgName string) error {
return workspace.SetBackendConfigDefaultOrg(url, orgName)
}
// Login logs into the target cloud URL and returns the cloud backend for it.
func Login(ctx context.Context, d diag.Sink, cloudURL string, opts display.Options) (Backend, error) {
cloudURL = ValueOrDefaultURL(cloudURL)
@ -269,8 +274,7 @@ func Login(ctx context.Context, d diag.Sink, cloudURL string, opts display.Optio
} else if !cmdutil.Interactive() {
// If interactive mode isn't enabled, the only way to specify a token is through the environment variable.
// Fail the attempt to login.
return nil, errors.Errorf(
"%s must be set for login during non-interactive CLI sessions", AccessTokenEnvVar)
return nil, fmt.Errorf("%s must be set for login during non-interactive CLI sessions", AccessTokenEnvVar)
} else {
// If no access token is available from the environment, and we are interactive, prompt and offer to
// open a browser to make it easy to generate and use a fresh token.
@ -333,7 +337,7 @@ func Login(ctx context.Context, d diag.Sink, cloudURL string, opts display.Optio
if err != nil {
return nil, err
} else if !valid {
return nil, errors.Errorf("invalid access token")
return nil, fmt.Errorf("invalid access token")
}
// Save them.
@ -426,7 +430,7 @@ func (b *cloudBackend) parsePolicyPackReference(s string) (backend.PolicyPackRef
orgName = split[0]
policyPackName = split[1]
default:
return nil, errors.Errorf("could not parse policy pack name '%s'; must be of the form "+
return nil, fmt.Errorf("could not parse policy pack name '%s'; must be of the form "+
"<org-name>/<policy-pack-name>", s)
}
@ -507,7 +511,7 @@ func (b *cloudBackend) parseStackName(s string) (qualifiedStackReference, error)
q.Project = split[1]
q.Name = split[2]
default:
return qualifiedStackReference{}, errors.Errorf("could not parse stack name '%s'", s)
return qualifiedStackReference{}, fmt.Errorf("could not parse stack name '%s'", s)
}
return q, nil
@ -692,14 +696,14 @@ func (b *cloudBackend) CreateStack(
tags, err := backend.GetEnvironmentTagsForCurrentStack()
if err != nil {
return nil, errors.Wrap(err, "error determining initial tags")
return nil, fmt.Errorf("error determining initial tags: %w", err)
}
// Confirm the stack identity matches the environment. e.g. stack init foo/bar/baz shouldn't work
// if the project name in Pulumi.yaml is anything other than "bar".
projNameTag, ok := tags[apitype.ProjectNameTag]
if ok && stackID.Project != projNameTag {
return nil, errors.Errorf("provided project name %q doesn't match Pulumi.yaml", stackID.Project)
return nil, fmt.Errorf("provided project name %q doesn't match Pulumi.yaml", stackID.Project)
}
apistack, err := b.client.CreateStack(ctx, stackID, tags)
@ -905,7 +909,7 @@ func (b *cloudBackend) createAndStartUpdate(
// metadata changes.
tags, err := backend.GetMergedStackTags(ctx, stack)
if err != nil {
return client.UpdateIdentifier{}, 0, "", errors.Wrap(err, "getting stack tags")
return client.UpdateIdentifier{}, 0, "", fmt.Errorf("getting stack tags: %w", err)
}
version, token, err := b.client.StartUpdate(ctx, update, tags)
if err != nil {
@ -1071,7 +1075,7 @@ func (b *cloudBackend) runEngineAction(
}
completeErr := u.Complete(status)
if completeErr != nil {
res = result.Merge(res, result.FromError(errors.Wrap(completeErr, "failed to complete update")))
res = result.Merge(res, result.FromError(fmt.Errorf("failed to complete update: %w", completeErr)))
}
return plan, changes, res
@ -1088,7 +1092,7 @@ func (b *cloudBackend) CancelCurrentUpdate(ctx context.Context, stackRef backend
}
if stack.ActiveUpdate == "" {
return errors.Errorf("stack %v has never been updated", stackRef)
return fmt.Errorf("stack %v has never been updated", stackRef)
}
// Compute the update identifier and attempt to cancel the update.
@ -1123,7 +1127,7 @@ func (b *cloudBackend) GetHistory(
// Convert types from the apitype package into their internal counterparts.
cfg, err := convertConfig(update.Config)
if err != nil {
return nil, errors.Wrap(err, "converting configuration")
return nil, fmt.Errorf("converting configuration: %w", err)
}
beUpdates = append(beUpdates, backend.UpdateInfo{
@ -1218,7 +1222,9 @@ func (b *cloudBackend) ExportDeploymentForVersion(
// The first stack update version is 1, and monotonically increasing from there.
versionNumber, err := strconv.Atoi(version)
if err != nil || versionNumber <= 0 {
return nil, errors.Errorf("%q is not a valid stack version. It should be a positive integer.", version)
return nil, fmt.Errorf(
"%q is not a valid stack version. It should be a positive integer",
version)
}
return b.exportDeployment(ctx, stack.Ref(), &versionNumber)
@ -1258,9 +1264,9 @@ func (b *cloudBackend) ImportDeployment(ctx context.Context, stack backend.Stack
ctx, backend.ActionLabel(apitype.StackImportUpdate, false /*dryRun*/), update,
display.Options{Color: colors.Always})
if err != nil {
return errors.Wrap(err, "waiting for import")
return fmt.Errorf("waiting for import: %w", err)
} else if status != apitype.StatusSucceeded {
return errors.Errorf("import unsuccessful: status %v", status)
return fmt.Errorf("import unsuccessful: status %v", status)
}
return nil
}
@ -1449,7 +1455,7 @@ func IsValidAccessToken(ctx context.Context, cloudURL, accessToken string) (bool
if errResp, ok := err.(*apitype.ErrorResponse); ok && errResp.Code == 401 {
return false, "", nil
}
return false, "", errors.Wrapf(err, "getting user info from %v", cloudURL)
return false, "", fmt.Errorf("getting user info from %v: %w", cloudURL, err)
}
return true, username, nil
@ -1481,7 +1487,7 @@ func (c httpstateBackendClient) GetStackOutputs(ctx context.Context, name string
// When using the cloud backend, require that stack references are fully qualified so they
// look like "<org>/<project>/<stack>"
if strings.Count(name, "/") != 2 {
return nil, errors.Errorf("a stack reference's name should be of the form " +
return nil, fmt.Errorf("a stack reference's name should be of the form " +
"'<organization>/<project>/<stack>'. See https://pulumi.io/help/stack-reference for more information.")
}

View file

@ -14,9 +14,10 @@
package httpstate
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestValueOrDefaultURL(t *testing.T) {

View file

@ -19,6 +19,7 @@ import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -31,7 +32,6 @@ import (
"github.com/google/go-querystring/query"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/util/tracing"
"github.com/pulumi/pulumi/pkg/v3/version"
@ -134,14 +134,14 @@ func pulumiAPICall(ctx context.Context, d diag.Sink, cloudAPI, method, path stri
writer := gzip.NewWriter(&buf)
defer contract.IgnoreClose(writer)
if _, err := writer.Write(body); err != nil {
return "", nil, errors.Wrapf(err, "compressing payload")
return "", nil, fmt.Errorf("compressing payload: %w", err)
}
// gzip.Writer will not actually write anything unless it is flushed,
// and it will not actually write the GZip footer unless it is closed. (Close also flushes)
// Without this, the compressed bytes do not decompress properly e.g. in python.
if err := writer.Close(); err != nil {
return "", nil, errors.Wrapf(err, "closing compressed payload")
return "", nil, fmt.Errorf("closing compressed payload: %w", err)
}
logging.V(apiRequestDetailLogLevel).Infof("gzip compression ratio: %f, original size: %d bytes",
@ -153,7 +153,7 @@ func pulumiAPICall(ctx context.Context, d diag.Sink, cloudAPI, method, path stri
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
return "", nil, errors.Wrapf(err, "creating new HTTP request")
return "", nil, fmt.Errorf("creating new HTTP request: %w", err)
}
requestSpan, requestContext := opentracing.StartSpanFromContext(ctx, getEndpointName(method, path),
@ -210,7 +210,7 @@ func pulumiAPICall(ctx context.Context, d diag.Sink, cloudAPI, method, path stri
}
if err != nil {
return "", nil, errors.Wrapf(err, "performing HTTP request")
return "", nil, fmt.Errorf("performing HTTP request: %w", err)
}
logging.V(apiRequestLogLevel).Infof("Pulumi API call response code (%s): %v", url, resp.Status)
@ -228,8 +228,7 @@ func pulumiAPICall(ctx context.Context, d diag.Sink, cloudAPI, method, path stri
// type, and if not just return the raw response text.
respBody, err := readBody(resp)
if err != nil {
return "", nil, errors.Wrapf(
err, "API call failed (%s), could not read response", resp.Status)
return "", nil, fmt.Errorf("API call failed (%s), could not read response: %w", resp.Status, err)
}
// Provide a better error if using an authenticated call without having logged in first.
@ -260,7 +259,7 @@ func pulumiRESTCall(ctx context.Context, diag diag.Sink, cloudAPI, method, path
if queryObj != nil {
queryValues, err := query.Values(queryObj)
if err != nil {
return errors.Wrapf(err, "marshalling query object as JSON")
return fmt.Errorf("marshalling query object as JSON: %w", err)
}
query := queryValues.Encode()
if len(query) > 0 {
@ -274,7 +273,7 @@ func pulumiRESTCall(ctx context.Context, diag diag.Sink, cloudAPI, method, path
if reqObj != nil {
reqBody, err = json.Marshal(reqObj)
if err != nil {
return errors.Wrapf(err, "marshalling request object as JSON")
return fmt.Errorf("marshalling request object as JSON: %w", err)
}
}
@ -287,7 +286,7 @@ func pulumiRESTCall(ctx context.Context, diag diag.Sink, cloudAPI, method, path
// Read API response
respBody, err := readBody(resp)
if err != nil {
return errors.Wrapf(err, "reading response from API")
return fmt.Errorf("reading response from API: %w", err)
}
if logging.V(apiRequestDetailLogLevel) {
logging.V(apiRequestDetailLogLevel).Infof("Pulumi API call response body (%s): %v", url, string(respBody))
@ -303,7 +302,7 @@ func pulumiRESTCall(ctx context.Context, diag diag.Sink, cloudAPI, method, path
} else {
// Else, unmarshal as JSON.
if err = json.Unmarshal(respBody, respObj); err != nil {
return errors.Wrapf(err, "unmarshalling response object")
return fmt.Errorf("unmarshalling response object: %w", err)
}
}
}
@ -323,7 +322,7 @@ func readBody(resp *http.Response) ([]byte, error) {
if len(contentEncoding) > 1 {
// We only know how to deal with gzip. We can't handle additional encodings layered on top of it.
return nil, errors.Errorf("can't handle content encodings %v", contentEncoding)
return nil, fmt.Errorf("can't handle content encodings %v", contentEncoding)
}
switch contentEncoding[0] {
@ -337,11 +336,11 @@ func readBody(resp *http.Response) ([]byte, error) {
defer contract.IgnoreClose(reader)
}
if err != nil {
return nil, errors.Wrap(err, "reading gzip-compressed body")
return nil, fmt.Errorf("reading gzip-compressed body: %w", err)
}
return ioutil.ReadAll(reader)
default:
return nil, errors.Errorf("unrecognized encoding %s", contentEncoding[0])
return nil, fmt.Errorf("unrecognized encoding %s", contentEncoding[0])
}
}

View file

@ -17,6 +17,7 @@ package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -28,7 +29,6 @@ import (
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/util/validation"
@ -303,7 +303,7 @@ func (pc *Client) CreateStack(
ctx context.Context, stackID StackIdentifier, tags map[apitype.StackTagName]string) (apitype.Stack, error) {
// Validate names and tags.
if err := validation.ValidateStackProperties(stackID.Stack, tags); err != nil {
return apitype.Stack{}, errors.Wrap(err, "validating stack properties")
return apitype.Stack{}, fmt.Errorf("validating stack properties: %w", err)
}
stack := apitype.Stack{
@ -521,7 +521,7 @@ func (pc *Client) StartUpdate(ctx context.Context, update UpdateIdentifier,
// Validate names and tags.
if err := validation.ValidateStackProperties(update.StackIdentifier.Stack, tags); err != nil {
return 0, "", errors.Wrap(err, "validating stack properties")
return 0, "", fmt.Errorf("validating stack properties: %w", err)
}
req := apitype.StartUpdateRequest{
@ -543,7 +543,7 @@ func (pc *Client) ListPolicyGroups(ctx context.Context, orgName string, inContTo
var resp apitype.ListPolicyGroupsResponse
err := pc.restCall(ctx, "GET", listPolicyGroupsPath(orgName), nil, nil, &resp)
if err != nil {
return resp, nil, errors.Wrapf(err, "List Policy Groups failed")
return resp, nil, fmt.Errorf("List Policy Groups failed: %w", err)
}
return resp, nil, nil
}
@ -555,7 +555,7 @@ func (pc *Client) ListPolicyPacks(ctx context.Context, orgName string, inContTok
var resp apitype.ListPolicyPacksResponse
err := pc.restCall(ctx, "GET", listPolicyPacksPath(orgName), nil, nil, &resp)
if err != nil {
return resp, nil, errors.Wrapf(err, "List Policy Packs failed")
return resp, nil, fmt.Errorf("List Policy Packs failed: %w", err)
}
return resp, nil, nil
}
@ -609,7 +609,7 @@ func (pc *Client) PublishPolicyPack(ctx context.Context, orgName string,
var resp apitype.CreatePolicyPackResponse
err := pc.restCall(ctx, "POST", publishPolicyPackPath(orgName), nil, req, &resp)
if err != nil {
return "", errors.Wrapf(err, "Publish policy pack failed")
return "", fmt.Errorf("Publish policy pack failed: %w", err)
}
//
@ -619,7 +619,7 @@ func (pc *Client) PublishPolicyPack(ctx context.Context, orgName string,
putReq, err := http.NewRequest(http.MethodPut, resp.UploadURI, dirArchive)
if err != nil {
return "", errors.Wrapf(err, "Failed to upload compressed PolicyPack")
return "", fmt.Errorf("Failed to upload compressed PolicyPack: %w", err)
}
for k, v := range resp.RequiredHeaders {
@ -628,7 +628,7 @@ func (pc *Client) PublishPolicyPack(ctx context.Context, orgName string,
_, err = http.DefaultClient.Do(putReq)
if err != nil {
return "", errors.Wrapf(err, "Failed to upload compressed PolicyPack")
return "", fmt.Errorf("Failed to upload compressed PolicyPack: %w", err)
}
//
@ -645,7 +645,7 @@ func (pc *Client) PublishPolicyPack(ctx context.Context, orgName string,
err = pc.restCall(ctx, "POST",
publishPolicyPackPublishComplete(orgName, analyzerInfo.Name, version), nil, nil, nil)
if err != nil {
return "", errors.Wrapf(err, "Request to signal completion of the publish operation failed")
return "", fmt.Errorf("Request to signal completion of the publish operation failed: %w", err)
}
return version, nil
@ -708,7 +708,7 @@ func (pc *Client) ApplyPolicyPack(ctx context.Context, orgName, policyGroup,
err := pc.restCall(ctx, http.MethodPatch, updatePolicyGroupPath(orgName, policyGroup), nil, req, nil)
if err != nil {
return errors.Wrapf(err, "Enable policy pack failed")
return fmt.Errorf("Enable policy pack failed: %w", err)
}
return nil
}
@ -720,7 +720,7 @@ func (pc *Client) GetPolicyPackSchema(ctx context.Context, orgName,
err := pc.restCall(ctx, http.MethodGet,
getPolicyPackConfigSchemaPath(orgName, policyPackName, versionTag), nil, nil, &resp)
if err != nil {
return nil, errors.Wrap(err, "Retrieving policy pack config schema failed")
return nil, fmt.Errorf("Retrieving policy pack config schema failed: %w", err)
}
return &resp, nil
}
@ -744,7 +744,7 @@ func (pc *Client) DisablePolicyPack(ctx context.Context, orgName string, policyG
err := pc.restCall(ctx, http.MethodPatch, updatePolicyGroupPath(orgName, policyGroup), nil, req, nil)
if err != nil {
return errors.Wrapf(err, "Request to disable policy pack failed")
return fmt.Errorf("Request to disable policy pack failed: %w", err)
}
return nil
}
@ -754,7 +754,7 @@ func (pc *Client) RemovePolicyPack(ctx context.Context, orgName string, policyPa
path := deletePolicyPackPath(orgName, policyPackName)
err := pc.restCall(ctx, http.MethodDelete, path, nil, nil, nil)
if err != nil {
return errors.Wrapf(err, "Request to remove policy pack failed")
return fmt.Errorf("Request to remove policy pack failed: %w", err)
}
return nil
}
@ -767,7 +767,7 @@ func (pc *Client) RemovePolicyPackByVersion(ctx context.Context, orgName string,
path := deletePolicyPackVersionPath(orgName, policyPackName, versionTag)
err := pc.restCall(ctx, http.MethodDelete, path, nil, nil, nil)
if err != nil {
return errors.Wrapf(err, "Request to remove policy pack failed")
return fmt.Errorf("Request to remove policy pack failed: %w", err)
}
return nil
}
@ -776,12 +776,12 @@ func (pc *Client) RemovePolicyPackByVersion(ctx context.Context, orgName string,
func (pc *Client) DownloadPolicyPack(ctx context.Context, url string) (io.ReadCloser, error) {
getS3Req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, errors.Wrapf(err, "Failed to download compressed PolicyPack")
return nil, fmt.Errorf("Failed to download compressed PolicyPack: %w", err)
}
resp, err := http.DefaultClient.Do(getS3Req)
if err != nil {
return nil, errors.Wrapf(err, "Failed to download compressed PolicyPack")
return nil, fmt.Errorf("Failed to download compressed PolicyPack: %w", err)
}
return resp.Body, nil

View file

@ -12,7 +12,6 @@ import (
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate/client"
"github.com/pulumi/pulumi/pkg/v3/engine"
@ -183,8 +182,7 @@ func (pack *cloudPolicyPack) Publish(
if strings.EqualFold(runtime, "nodejs") {
packTarball, err = npm.Pack(op.PlugCtx.Pwd, os.Stderr)
if err != nil {
return result.FromError(
errors.Wrap(err, "could not publish policies because of error running npm pack"))
return result.FromError(fmt.Errorf("could not publish policies because of error running npm pack: %w", err))
}
} else {
// npm pack puts all the files in a "package" subdirectory inside the .tgz it produces, so we'll do
@ -192,8 +190,7 @@ func (pack *cloudPolicyPack) Publish(
// package directory to determine the runtime of the policy pack.
packTarball, err = archive.TGZ(op.PlugCtx.Pwd, "package", true /*useDefaultExcludes*/)
if err != nil {
return result.FromError(
errors.Wrap(err, "could not publish policies because of error creating the .tgz"))
return result.FromError(fmt.Errorf("could not publish policies because of error creating the .tgz: %w", err))
}
}
@ -253,18 +250,18 @@ func installRequiredPolicy(finalDir string, tgz io.ReadCloser) error {
// If part of the directory tree is missing, ioutil.TempDir will return an error, so make sure
// the path we're going to create the temporary folder in actually exists.
if err := os.MkdirAll(filepath.Dir(finalDir), 0700); err != nil {
return errors.Wrap(err, "creating plugin root")
return fmt.Errorf("creating plugin root: %w", err)
}
tempDir, err := ioutil.TempDir(filepath.Dir(finalDir), fmt.Sprintf("%s.tmp", filepath.Base(finalDir)))
if err != nil {
return errors.Wrapf(err, "creating plugin directory %s", tempDir)
return fmt.Errorf("creating plugin directory %s: %w", tempDir, err)
}
// The policy pack files are actually in a directory called `package`.
tempPackageDir := filepath.Join(tempDir, packageDir)
if err := os.MkdirAll(tempPackageDir, 0700); err != nil {
return errors.Wrap(err, "creating plugin root")
return fmt.Errorf("creating plugin root: %w", err)
}
// If we early out of this function, try to remove the temp folder we created.
@ -284,13 +281,13 @@ func installRequiredPolicy(finalDir string, tgz io.ReadCloser) error {
// unable to rename the directory. That's OK, just ignore the error. The temp directory created
// as part of the install will be cleaned up when we exit by the defer above.
if err := os.Rename(tempPackageDir, finalDir); err != nil && !os.IsExist(err) {
return errors.Wrap(err, "moving plugin")
return fmt.Errorf("moving plugin: %w", err)
}
projPath := filepath.Join(finalDir, "PulumiPolicy.yaml")
proj, err := workspace.LoadPolicyPack(projPath)
if err != nil {
return errors.Wrapf(err, "failed to load policy project at %s", finalDir)
return fmt.Errorf("failed to load policy project at %s: %w", finalDir, err)
}
// TODO[pulumi/pulumi#1334]: move to the language plugins so we don't have to hard code here.
@ -312,10 +309,9 @@ func installRequiredPolicy(finalDir string, tgz io.ReadCloser) error {
func completeNodeJSInstall(finalDir string) error {
if bin, err := npm.Install(finalDir, false /*production*/, nil, os.Stderr); err != nil {
return errors.Wrapf(
err,
"failed to install dependencies of policy pack; you may need to re-run `%s install` "+
"in %q before this policy pack works", bin, finalDir)
return fmt.Errorf("failed to install dependencies of policy pack; you may need to re-run `%s install` "+
"in %q before this policy pack works"+": %w", bin, finalDir, err)
}
return nil
@ -330,7 +326,7 @@ func completePythonInstall(finalDir, projPath string, proj *workspace.PolicyPack
// Save project with venv info.
proj.Runtime.SetOption("virtualenv", venvDir)
if err := proj.Save(projPath); err != nil {
return errors.Wrapf(err, "saving project at %s", projPath)
return fmt.Errorf("saving project at %s: %w", projPath, err)
}
return nil

View file

@ -16,8 +16,8 @@ package httpstate
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate/client"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
@ -45,7 +45,7 @@ func (persister *cloudSnapshotPersister) Save(snapshot *deploy.Snapshot) error {
}
deployment, err := stack.SerializeDeployment(snapshot, persister.sm, false /* showSecrets */)
if err != nil {
return errors.Wrap(err, "serializing deployment")
return fmt.Errorf("serializing deployment: %w", err)
}
return persister.backend.client.PatchUpdateCheckpoint(persister.context, persister.update, deployment, token)
}

View file

@ -24,7 +24,6 @@ import (
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate/client"
@ -171,7 +170,7 @@ func (u *cloudUpdate) recordEngineEvents(startingSeqNumber int, events []engine.
for idx, event := range events {
apiEvent, convErr := display.ConvertEngineEvent(event)
if convErr != nil {
return errors.Wrap(convErr, "converting engine event")
return fmt.Errorf("converting engine event: %w", convErr)
}
// Each event within an update must have a unique sequence number. Any request to
@ -294,7 +293,7 @@ func (b *cloudBackend) getTarget(ctx context.Context, stackRef backend.StackRefe
return nil, fmt.Errorf("the stack '%s' is newer than what this version of the Pulumi CLI understands. "+
"Please update your version of the Pulumi CLI", stackRef.Name())
default:
return nil, errors.Wrap(err, "could not deserialize deployment")
return nil, fmt.Errorf("could not deserialize deployment: %w", err)
}
}

View file

@ -15,12 +15,12 @@
package backend
import (
"errors"
"fmt"
"reflect"
"sort"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/pkg/v3/secrets"
@ -603,14 +603,14 @@ func (sm *SnapshotManager) snap() *deploy.Snapshot {
func (sm *SnapshotManager) saveSnapshot() error {
snap := sm.snap()
if err := snap.NormalizeURNReferences(); err != nil {
return errors.Wrap(err, "failed to normalize URN references")
return fmt.Errorf("failed to normalize URN references: %w", err)
}
if err := sm.persister.Save(snap); err != nil {
return errors.Wrap(err, "failed to save snapshot")
return fmt.Errorf("failed to save snapshot: %w", err)
}
if sm.doVerify {
if err := snap.VerifyIntegrity(); err != nil {
return errors.Wrapf(err, "failed to verify snapshot")
return fmt.Errorf("failed to verify snapshot: %w", err)
}
}
return nil

View file

@ -19,8 +19,6 @@ import (
"fmt"
"path/filepath"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/operations"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
@ -185,7 +183,7 @@ func GetEnvironmentTagsForCurrentStack() (map[apitype.StackTagName]string, error
if projPath != "" {
proj, err := workspace.LoadProject(projPath)
if err != nil {
return nil, errors.Wrapf(err, "error loading project %q", projPath)
return nil, fmt.Errorf("error loading project %q: %w", projPath, err)
}
tags[apitype.ProjectNameTag] = proj.Name.String()
tags[apitype.ProjectRuntimeTag] = proj.Runtime.Name()
@ -226,7 +224,7 @@ func addGitMetadataToStackTags(tags map[apitype.StackTagName]string, projPath st
tags[apitype.VCSRepositoryNameTag] = vcsInfo.Repo
tags[apitype.VCSRepositoryKindTag] = vcsInfo.Kind
} else {
return errors.Wrapf(err, "detecting VCS info for stack tags for remote %v", remoteURL)
return fmt.Errorf("detecting VCS info for stack tags for remote %v: %w", remoteURL, err)
}
// Set the old stack tags keys as GitHub so that the UI will continue to work,
// regardless of whether the remote URL is a GitHub URL or not.

View file

@ -17,6 +17,7 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
@ -29,7 +30,6 @@ import (
"strings"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/host"
"github.com/spf13/cobra"
@ -117,7 +117,7 @@ func getSummaryAbout(transitiveDependencies bool) summaryAbout {
}
var plugins []pluginAbout
addError := func(err error, message string) {
err = errors.Wrap(err, message)
err = fmt.Errorf("%s: %w", message, err)
result.ErrorMessages = append(result.ErrorMessages, err.Error())
result.Errors = append(result.Errors, err)
}
@ -439,7 +439,7 @@ func getGoProgramDependencies(transitive bool) ([]programDependencieAbout, error
cmd := exec.Command(ex, cmdArgs...)
var out []byte
if out, err = cmd.Output(); err != nil {
return nil, errors.Wrap(err, "Failed to get modules")
return nil, fmt.Errorf("Failed to get modules: %w", err)
}
dec := json.NewDecoder(bytes.NewReader(out))
@ -450,7 +450,7 @@ func getGoProgramDependencies(transitive bool) ([]programDependencieAbout, error
if err == io.EOF {
break
}
return nil, errors.Wrapf(err, "Failed to parse \"%s %s\" output", ex, strings.Join(cmdArgs, " "))
return nil, fmt.Errorf("Failed to parse \"%s %s\" output: %w", ex, strings.Join(cmdArgs, " "), err)
}
parsed = append(parsed, m)
@ -525,7 +525,7 @@ func getPythonProgramDependencies(proj *workspace.Project, rootDir string,
var result []programDependencieAbout
err = json.Unmarshal([]byte(out), &result)
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse \"python %s\" result", strings.Join(cmdArgs, " "))
return nil, fmt.Errorf("Failed to parse \"python %s\" result: %w", strings.Join(cmdArgs, " "), err)
}
return result, nil
@ -553,7 +553,7 @@ func getDotNetProgramDependencies(proj *workspace.Project, transitive bool) ([]p
}
cmd := exec.Command(ex, cmdArgs...)
if out, err = cmd.Output(); err != nil {
return nil, errors.Wrapf(err, "Failed to call \"%s\"", ex)
return nil, fmt.Errorf("Failed to call \"%s\": %w", ex, err)
}
lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
var packages []programDependencieAbout
@ -577,7 +577,7 @@ func getDotNetProgramDependencies(proj *workspace.Project, transitive bool) ([]p
// Transitive package => name version
version = 1
} else {
return nil, errors.Errorf("Failed to parse \"%s\"", p)
return nil, fmt.Errorf("Failed to parse \"%s\"", p)
}
packages = append(packages, programDependencieAbout{
Name: nameRequiredVersion[0],
@ -607,18 +607,18 @@ type yarnLockTree struct {
func parseYarnLockFile(path string) ([]programDependencieAbout, error) {
ex, err := executable.FindExecutable("yarn")
if err != nil {
return nil, errors.Wrapf(err, "Found %s but no yarn executable", path)
return nil, fmt.Errorf("Found %s but no yarn executable: %w", path, err)
}
cmdArgs := []string{"list", "--json"}
cmd := exec.Command(ex, cmdArgs...)
out, err := cmd.Output()
if err != nil {
return nil, errors.Wrapf(err, "Failed to run \"%s %s\"", ex, strings.Join(cmdArgs, " "))
return nil, fmt.Errorf("Failed to run \"%s %s\": %w", ex, strings.Join(cmdArgs, " "), err)
}
var lock yarnLock
if err = json.Unmarshal(out, &lock); err != nil {
return nil, errors.Wrapf(err, "Failed to parse\"%s %s\"", ex, strings.Join(cmdArgs, " "))
return nil, fmt.Errorf("Failed to parse\"%s %s\": %w", ex, strings.Join(cmdArgs, " "), err)
}
leafs := lock.Data.Trees
@ -627,11 +627,11 @@ func parseYarnLockFile(path string) ([]programDependencieAbout, error) {
// Has the form name@version
splitName := func(index int, nameVersion string) (string, string, error) {
if nameVersion == "" {
return "", "", errors.Errorf("Expected \"name\" in dependency %d", index)
return "", "", fmt.Errorf("Expected \"name\" in dependency %d", index)
}
split := strings.LastIndex(nameVersion, "@")
if split == -1 {
return "", "", errors.Errorf("Failed to parse name and version from %s", nameVersion)
return "", "", fmt.Errorf("Failed to parse name and version from %s", nameVersion)
}
return nameVersion[:split], nameVersion[split+1:], nil
}
@ -667,17 +667,17 @@ type npmPackage struct {
func parseNpmLockFile(path string) ([]programDependencieAbout, error) {
ex, err := executable.FindExecutable("npm")
if err != nil {
return nil, errors.Wrapf(err, "Found %s but not npm", path)
return nil, fmt.Errorf("Found %s but not npm: %w", path, err)
}
cmdArgs := []string{"ls", "--json", "--depth=0"}
cmd := exec.Command(ex, cmdArgs...)
out, err := cmd.Output()
if err != nil {
return nil, errors.Wrapf(err, `Failed to run "%s %s"`, ex, strings.Join(cmdArgs, " "))
return nil, fmt.Errorf(`Failed to run "%s %s": %w`, ex, strings.Join(cmdArgs, " "), err)
}
file := npmFile{}
if err = json.Unmarshal(out, &file); err != nil {
return nil, errors.Wrapf(err, `Failed to parse \"%s %s"`, ex, strings.Join(cmdArgs, " "))
return nil, fmt.Errorf(`Failed to parse \"%s %s": %w`, ex, strings.Join(cmdArgs, " "), err)
}
result := make([]programDependencieAbout, len(file.Dependencies))
var i int
@ -704,7 +704,7 @@ func crossCheckPackageJSONFile(path string, file []byte,
var body packageJSON
if err := json.Unmarshal(file, &body); err != nil {
return nil, errors.Wrapf(err, "Could not parse %s", path)
return nil, fmt.Errorf("Could not parse %s: %w", path, err)
}
dependencies := make(map[string]string)
for k, v := range body.Dependencies {
@ -761,19 +761,19 @@ func getNodeProgramDependencies(rootDir string, transitive bool) ([]programDepen
return nil, err
}
} else if os.IsNotExist(err) {
return nil, errors.Errorf("Could not find either %s or %s", yarnFile, npmFile)
return nil, fmt.Errorf("Could not find either %s or %s", yarnFile, npmFile)
} else {
return nil, errors.Wrap(err, "Could not get node dependency data")
return nil, fmt.Errorf("Could not get node dependency data: %w", err)
}
if !transitive {
file, err := ioutil.ReadFile(packageFile)
if os.IsNotExist(err) {
return nil, errors.Errorf("Could not find %s. "+
return nil, fmt.Errorf("Could not find %s. "+
"Please include this in your report and run "+
`pulumi about --transitive" to get a list of used packages`,
packageFile)
} else if err != nil {
return nil, errors.Wrapf(err, "Could not read %s", packageFile)
return nil, fmt.Errorf("Could not read %s: %w", packageFile, err)
}
return crossCheckPackageJSONFile(packageFile, file, result)
}
@ -793,7 +793,7 @@ func getProgramDependenciesAbout(proj *workspace.Project, root string,
case langDotnet:
return getDotNetProgramDependencies(proj, transitive)
default:
return nil, errors.Errorf("Unknown Language: %s", language)
return nil, fmt.Errorf("Unknown Language: %s", language)
}
}
@ -872,11 +872,11 @@ func getProjectRuntimeAbout(proj *workspace.Project) (projectRuntimeAbout, error
case langNodejs:
ex, err = executable.FindExecutable("node")
if err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Could not find node executable")
return projectRuntimeAbout{}, fmt.Errorf("Could not find node executable: %w", err)
}
cmd := exec.Command(ex, "--version")
if out, err = cmd.Output(); err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Failed to get node version")
return projectRuntimeAbout{}, fmt.Errorf("Failed to get node version: %w", err)
}
version = string(out)
case langPython:
@ -889,31 +889,31 @@ func getProjectRuntimeAbout(proj *workspace.Project) (projectRuntimeAbout, error
return projectRuntimeAbout{}, err
}
if out, err = cmd.Output(); err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Failed to get python version")
return projectRuntimeAbout{}, fmt.Errorf("Failed to get python version: %w", err)
}
version = "v" + strings.TrimPrefix(string(out), "Python ")
case langGo:
ex, err = executable.FindExecutable("go")
if err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Could not find python executable")
return projectRuntimeAbout{}, fmt.Errorf("Could not find python executable: %w", err)
}
cmd := exec.Command(ex, "version")
if out, err = cmd.Output(); err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Failed to get go version")
return projectRuntimeAbout{}, fmt.Errorf("Failed to get go version: %w", err)
}
version = "v" + strings.TrimPrefix(string(out), "go version go")
case langDotnet:
ex, err = executable.FindExecutable("dotnet")
if err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Could not find dotnet executable")
return projectRuntimeAbout{}, fmt.Errorf("Could not find dotnet executable: %w", err)
}
cmd := exec.Command(ex, "--version")
if out, err = cmd.Output(); err != nil {
return projectRuntimeAbout{}, errors.Wrap(err, "Failed to get dotnet version")
return projectRuntimeAbout{}, fmt.Errorf("Failed to get dotnet version: %w", err)
}
version = "v" + string(out)
default:
return projectRuntimeAbout{}, errors.Errorf("Unknown Language: %s", language)
return projectRuntimeAbout{}, fmt.Errorf("Unknown Language: %s: %w", language, err)
}
version = strings.TrimSpace(version)
return projectRuntimeAbout{

View file

@ -16,6 +16,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
@ -24,7 +25,7 @@ import (
"strings"
zxcvbn "github.com/nbutton23/zxcvbn-go"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
@ -152,7 +153,7 @@ func copySingleConfigKey(configKey string, path bool, currentStack backend.Stack
var decrypter config.Decrypter
key, err := parseConfigKey(configKey)
if err != nil {
return errors.Wrap(err, "invalid configuration key")
return fmt.Errorf("invalid configuration key: %w", err)
}
v, ok, err := currentProjectStack.Config.Get(key, path)
@ -163,7 +164,7 @@ func copySingleConfigKey(configKey string, path bool, currentStack backend.Stack
if v.Secure() {
var err error
if decrypter, err = getStackDecrypter(currentStack); err != nil {
return errors.Wrap(err, "could not create a decrypter")
return fmt.Errorf("could not create a decrypter: %w", err)
}
} else {
decrypter = config.NewPanicCrypter()
@ -187,8 +188,7 @@ func copySingleConfigKey(configKey string, path bool, currentStack backend.Stack
return saveProjectStack(destinationStack, destinationProjectStack)
}
return errors.Errorf(
"configuration key '%s' not found for stack '%s'", prettyKey(key), currentStack.Ref())
return fmt.Errorf("configuration key '%s' not found for stack '%s'", prettyKey(key), currentStack.Ref())
}
func copyEntireConfigMap(currentStack backend.Stack,
@ -264,7 +264,7 @@ func newConfigGetCmd(stack *string) *cobra.Command {
key, err := parseConfigKey(args[0])
if err != nil {
return errors.Wrap(err, "invalid configuration key")
return fmt.Errorf("invalid configuration key: %w", err)
}
return getConfig(s, key, path, jsonOut)
@ -305,7 +305,7 @@ func newConfigRmCmd(stack *string) *cobra.Command {
key, err := parseConfigKey(args[0])
if err != nil {
return errors.Wrap(err, "invalid configuration key")
return fmt.Errorf("invalid configuration key: %w", err)
}
ps, err := loadProjectStack(s)
@ -359,7 +359,7 @@ func newConfigRmAllCmd(stack *string) *cobra.Command {
for _, arg := range args {
key, err := parseConfigKey(arg)
if err != nil {
return errors.Wrap(err, "invalid configuration key")
return fmt.Errorf("invalid configuration key: %w", err)
}
err = ps.Config.Remove(key, path)
@ -424,13 +424,13 @@ func newConfigRefreshCmd(stack *string) *cobra.Command {
_, err = os.Stat(backupFile)
if os.IsNotExist(err) {
if err = os.Rename(configPath, backupFile); err != nil {
return errors.Wrap(err, "backing up existing configuration file")
return fmt.Errorf("backing up existing configuration file: %w", err)
}
fmt.Printf("backed up existing configuration file to %s\n", backupFile)
break
} else if err != nil {
return errors.Wrap(err, "backing up existing configuration file")
return fmt.Errorf("backing up existing configuration file: %w", err)
}
backupFile = backupFile + ".bak"
@ -481,7 +481,7 @@ func newConfigSetCmd(stack *string) *cobra.Command {
key, err := parseConfigKey(args[0])
if err != nil {
return errors.Wrap(err, "invalid configuration key")
return fmt.Errorf("invalid configuration key: %w", err)
}
var value string
@ -525,9 +525,8 @@ func newConfigSetCmd(stack *string) *cobra.Command {
// If we saved a plaintext configuration value, and --plaintext was not passed, warn the user.
if !plaintext && looksLikeSecret(key, value) {
return errors.Errorf(
"config value for '%s' looks like a secret; "+
"rerun with --secret to encrypt it, or --plaintext if you meant to store in plaintext",
return fmt.Errorf("config value for '%s' looks like a secret; "+
"rerun with --secret to encrypt it, or --plaintext if you meant to store in plaintext",
key)
}
}
@ -662,7 +661,7 @@ func parseKeyValuePair(pair string) (config.Key, string, error) {
}
key, err := parseConfigKey(splitArg[0])
if err != nil {
return config.Key{}, "", errors.Wrap(err, "invalid configuration key")
return config.Key{}, "", fmt.Errorf("invalid configuration key: %w", err)
}
value := splitArg[1]
@ -769,7 +768,7 @@ func listConfig(stack backend.Stack, showSecrets bool, jsonOut bool) error {
decrypted, err := cfg[key].Value(decrypter)
if err != nil {
return errors.Wrap(err, "could not decrypt configuration value")
return fmt.Errorf("could not decrypt configuration value: %w", err)
}
entry.Value = &decrypted
@ -800,7 +799,7 @@ func listConfig(stack backend.Stack, showSecrets bool, jsonOut bool) error {
for _, key := range keys {
decrypted, err := cfg[key].Value(decrypter)
if err != nil {
return errors.Wrap(err, "could not decrypt configuration value")
return fmt.Errorf("could not decrypt configuration value: %w", err)
}
rows = append(rows, cmdutil.TableRow{Columns: []string{prettyKey(key), decrypted}})
@ -832,14 +831,14 @@ func getConfig(stack backend.Stack, key config.Key, path, jsonOut bool) error {
if v.Secure() {
var err error
if d, err = getStackDecrypter(stack); err != nil {
return errors.Wrap(err, "could not create a decrypter")
return fmt.Errorf("could not create a decrypter: %w", err)
}
} else {
d = config.NewPanicCrypter()
}
raw, err := v.Value(d)
if err != nil {
return errors.Wrap(err, "could not decrypt configuration value")
return fmt.Errorf("could not decrypt configuration value: %w", err)
}
if jsonOut {
@ -868,8 +867,7 @@ func getConfig(stack backend.Stack, key config.Key, path, jsonOut bool) error {
return nil
}
return errors.Errorf(
"configuration key '%s' not found for stack '%s'", prettyKey(key), stack.Ref())
return fmt.Errorf("configuration key '%s' not found for stack '%s'", prettyKey(key), stack.Ref())
}
var (
@ -911,7 +909,7 @@ func looksLikeSecret(k config.Key, v string) bool {
func getStackConfiguration(stack backend.Stack, sm secrets.Manager) (backend.StackConfiguration, error) {
workspaceStack, err := loadProjectStack(stack)
if err != nil {
return backend.StackConfiguration{}, errors.Wrap(err, "loading stack configuration")
return backend.StackConfiguration{}, fmt.Errorf("loading stack configuration: %w", err)
}
// If there are no secrets in the configuration, we should never use the decrypter, so it is safe to return
@ -926,7 +924,7 @@ func getStackConfiguration(stack backend.Stack, sm secrets.Manager) (backend.Sta
crypter, err := sm.Decrypter()
if err != nil {
return backend.StackConfiguration{}, errors.Wrap(err, "getting configuration decrypter")
return backend.StackConfiguration{}, fmt.Errorf("getting configuration decrypter: %w", err)
}
return backend.StackConfiguration{

View file

@ -15,10 +15,10 @@
package main
import (
"fmt"
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/filestate"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate"
@ -70,7 +70,7 @@ func getStackSecretsManager(s backend.Stack) (secrets.Manager, error) {
return newServiceSecretsManager(s.(httpstate.Stack), s.Ref().Name(), stackConfigFile)
}
return nil, errors.Errorf("unknown stack type %s", reflect.TypeOf(s))
return nil, fmt.Errorf("unknown stack type %s", reflect.TypeOf(s))
}()
if err != nil {
return nil, err
@ -86,9 +86,8 @@ func validateSecretsProvider(typ string) error {
return nil
}
}
return errors.Errorf(
"unknown secrets provider type '%s' (supported values: %s)",
return fmt.Errorf("unknown secrets provider type '%s' (supported values: %s)",
kind,
strings.Join(supportedKinds, ","),
)
strings.Join(supportedKinds, ","))
}

View file

@ -17,13 +17,13 @@ package main
import (
cryptorand "crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/secrets"
"github.com/pulumi/pulumi/pkg/v3/secrets/passphrase"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -42,11 +42,11 @@ func readPassphraseImpl(prompt string, useEnv bool) (phrase string, interactive
if phraseFile, ok := os.LookupEnv("PULUMI_CONFIG_PASSPHRASE_FILE"); ok {
phraseFilePath, err := filepath.Abs(phraseFile)
if err != nil {
return "", false, errors.Wrap(err, "unable to construct a path the PULUMI_CONFIG_PASSPHRASE_FILE")
return "", false, fmt.Errorf("unable to construct a path the PULUMI_CONFIG_PASSPHRASE_FILE: %w", err)
}
phraseDetails, err := ioutil.ReadFile(phraseFilePath)
if err != nil {
return "", false, errors.Wrap(err, "unable to read PULUMI_CONFIG_PASSPHRASE_FILE")
return "", false, fmt.Errorf("unable to read PULUMI_CONFIG_PASSPHRASE_FILE: %w", err)
}
return strings.TrimSpace(string(phraseDetails)), false, nil
}

View file

@ -16,9 +16,9 @@ package main
import (
"context"
"errors"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -127,17 +127,17 @@ func newDestroyCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
targetUrns := []resource.URN{}

View file

@ -18,6 +18,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
@ -25,7 +26,7 @@ import (
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -187,7 +188,7 @@ func getCurrentDeploymentForStack(s backend.Stack) (*deploy.Snapshot, error) {
return nil, fmt.Errorf("the stack '%s' is newer than what this version of the Pulumi CLI understands. "+
"Please update your version of the Pulumi CLI", s.Ref().Name())
}
return nil, errors.Wrap(err, "could not deserialize deployment")
return nil, fmt.Errorf("could not deserialize deployment: %w", err)
}
return snap, err
}
@ -351,7 +352,7 @@ func newImportCmd() *cobra.Command {
}
f, err := readImportFile(importFilePath)
if err != nil {
return result.FromError(errors.Wrap(err, "could not read import file"))
return result.FromError(fmt.Errorf("could not read import file: %w", err))
}
importFile = f
} else {
@ -454,17 +455,17 @@ func newImportCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
opts.Engine = engine.UpdateOptions{
@ -493,7 +494,7 @@ func newImportCmd() *cobra.Command {
protectResources)
if err != nil {
if _, ok := err.(*importer.DiagnosticsError); ok {
err = errors.Wrap(err, "internal error")
err = fmt.Errorf("internal error: %w", err)
}
return result.FromError(err)
}

View file

@ -15,12 +15,12 @@
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -33,6 +33,7 @@ import (
func newLoginCmd() *cobra.Command {
var cloudURL string
var defaultOrg string
var localMode bool
cmd := &cobra.Command{
@ -55,6 +56,9 @@ func newLoginCmd() *cobra.Command {
"to log in to a self-hosted Pulumi service running at the api.pulumi.acmecorp.com domain.\n" +
"\n" +
"For `https://` URLs, the CLI will speak REST to a service that manages state and concurrency control.\n" +
"You can specify a default org to use when logging into the Pulumi service backend or a " +
"self-hosted Pulumi service.\n" +
"\n" +
"[PREVIEW] If you prefer to operate Pulumi independently of a service, and entirely local to your computer,\n" +
"pass `file://<path>`, where `<path>` will be where state checkpoints will be stored. For instance,\n" +
"\n" +
@ -114,7 +118,7 @@ func newLoginCmd() *cobra.Command {
var err error
cloudURL, err = workspace.GetCurrentCloudURL()
if err != nil {
return errors.Wrap(err, "could not determine current cloud")
return fmt.Errorf("could not determine current cloud: %w", err)
}
} else {
// Ensure we have the correct cloudurl type before logging in
@ -127,11 +131,24 @@ func newLoginCmd() *cobra.Command {
var err error
if filestate.IsFileStateBackendURL(cloudURL) {
be, err = filestate.Login(cmdutil.Diag(), cloudURL)
if defaultOrg != "" {
return fmt.Errorf("unable to set default org for this type of backend")
}
} else {
be, err = httpstate.Login(commandContext(), cmdutil.Diag(), cloudURL, displayOptions)
// if the user has specified a default org to associate with the backend
if defaultOrg != "" {
cloudURL, err := workspace.GetCurrentCloudURL()
if err != nil {
return err
}
if err := httpstate.SetDefaultOrg(cloudURL, defaultOrg); err != nil {
return err
}
}
}
if err != nil {
return errors.Wrapf(err, "problem logging in")
return fmt.Errorf("problem logging in: %w", err)
}
if currentUser, err := be.CurrentUser(); err == nil {
@ -145,6 +162,8 @@ func newLoginCmd() *cobra.Command {
}
cmd.PersistentFlags().StringVarP(&cloudURL, "cloud-url", "c", "", "A cloud URL to log in to")
cmd.PersistentFlags().StringVar(&defaultOrg, "default-org", "", "A default org to associate with the login. "+
"Please note, currently, only the managed and self-hosted backends support organizations")
cmd.PersistentFlags().BoolVarP(&localMode, "local", "l", false, "Use Pulumi in local-only mode")
return cmd
@ -158,9 +177,8 @@ func validateCloudBackendType(typ string) error {
return nil
}
}
return errors.Errorf(
"unknown backend cloudUrl format '%s' (supported Url formats are: "+
"azblob://, gs://, s3://, file://, https:// and http://)",
kind,
)
return fmt.Errorf("unknown backend cloudUrl format '%s' (supported Url formats are: "+
"azblob://, gs://, s3://, file://, https:// and http://)",
kind)
}

View file

@ -15,7 +15,9 @@
package main
import (
"github.com/pkg/errors"
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -65,7 +67,7 @@ func newLogoutCmd() *cobra.Command {
var err error
cloudURL, err = workspace.GetCurrentCloudURL()
if err != nil {
return errors.Wrap(err, "could not determine current cloud")
return fmt.Errorf("could not determine current cloud: %w", err)
}
}

View file

@ -20,7 +20,7 @@ import (
"time"
mobytime "github.com/docker/docker/api/types/time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -63,17 +63,17 @@ func newLogsCmd() *cobra.Command {
sm, err := getStackSecretsManager(s)
if err != nil {
return errors.Wrap(err, "getting secrets manager")
return fmt.Errorf("getting secrets manager: %w", err)
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return errors.Wrap(err, "getting stack configuration")
return fmt.Errorf("getting stack configuration: %w", err)
}
startTime, err := parseSince(since, time.Now())
if err != nil {
return errors.Wrapf(err, "failed to parse argument to '--since' as duration or timestamp")
return fmt.Errorf("failed to parse argument to '--since' as duration or timestamp: %w", err)
}
var resourceFilter *operations.ResourceFilter
if resource != "" {
@ -102,7 +102,7 @@ func newLogsCmd() *cobra.Command {
ResourceFilter: resourceFilter,
})
if err != nil {
return errors.Wrapf(err, "failed to get logs")
return fmt.Errorf("failed to get logs: %w", err)
}
// When we are emitting a fixed number of log entries, and outputing JSON, wrap them in an array.

View file

@ -16,6 +16,7 @@
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
@ -26,7 +27,6 @@ import (
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/spf13/cobra"
survey "gopkg.in/AlecAivazis/survey.v1"
surveycore "gopkg.in/AlecAivazis/survey.v1/core"
@ -83,7 +83,7 @@ func runNew(args newArgs) error {
// Validate name (if specified) before further prompts/operations.
if args.name != "" && workspace.ValidateProjectName(args.name) != nil {
return errors.Errorf("'%s' is not a valid project name. %s.", args.name, workspace.ValidateProjectName(args.name))
return fmt.Errorf("'%s' is not a valid project name. %s", args.name, workspace.ValidateProjectName(args.name))
}
// Validate secrets provider type
@ -94,7 +94,7 @@ func runNew(args newArgs) error {
// Get the current working directory.
cwd, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "getting the working directory")
return fmt.Errorf("getting the working directory: %w", err)
}
originalCwd := cwd
@ -159,7 +159,7 @@ func runNew(args newArgs) error {
if !args.force {
if err = workspace.CopyTemplateFilesDryRun(template.Dir, cwd, args.name); err != nil {
if os.IsNotExist(err) {
return errors.Wrapf(err, "template '%s' not found", args.templateNameOrURL)
return fmt.Errorf("template '%s' not found: %w", args.templateNameOrURL, err)
}
return err
}
@ -172,7 +172,11 @@ func runNew(args newArgs) error {
// created via the web app.
var s backend.Stack
if args.stack != "" && strings.Count(args.stack, "/") == 2 {
existingStack, existingName, existingDesc, err := getStack(args.stack, opts)
stackName, err := buildStackName(args.stack)
if err != nil {
return err
}
existingStack, existingName, existingDesc, err := getStack(stackName, opts)
if err != nil {
return err
}
@ -228,7 +232,7 @@ func runNew(args newArgs) error {
// Actually copy the files.
if err = workspace.CopyTemplateFiles(template.Dir, cwd, args.force, args.name, args.description); err != nil {
if os.IsNotExist(err) {
return errors.Wrapf(err, "template '%s' not found", args.templateNameOrURL)
return fmt.Errorf("template '%s' not found: %w", args.templateNameOrURL, err)
}
return err
}
@ -245,7 +249,7 @@ func runNew(args newArgs) error {
proj.Description = &args.description
proj.Template = nil
if err = workspace.SaveProject(proj); err != nil {
return errors.Wrap(err, "saving project")
return fmt.Errorf("saving project: %w", err)
}
// Create the stack, if needed.
@ -299,19 +303,19 @@ func runNew(args newArgs) error {
func useSpecifiedDir(dir string) (string, error) {
// Ensure the directory exists.
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return "", errors.Wrap(err, "creating the directory")
return "", fmt.Errorf("creating the directory: %w", err)
}
// Change the working directory to the specified directory.
if err := os.Chdir(dir); err != nil {
return "", errors.Wrap(err, "changing the working directory")
return "", fmt.Errorf("changing the working directory: %w", err)
}
// Get the new working directory.
var cwd string
var err error
if cwd, err = os.Getwd(); err != nil {
return "", errors.Wrap(err, "getting the working directory")
return "", fmt.Errorf("getting the working directory: %w", err)
}
return cwd, nil
}
@ -445,7 +449,7 @@ func errorIfNotEmptyDirectory(path string) error {
}
if len(infos) > 0 {
return errors.Errorf("%s is not empty; "+
return fmt.Errorf("%s is not empty; "+
"rerun in an empty directory, pass the path to an empty directory to --dir, or use --force", path)
}
@ -518,7 +522,11 @@ func promptAndCreateStack(prompt promptForValueFunc,
}
if stack != "" {
s, err := stackInit(b, stack, setCurrent, secretsProvider)
stackName, err := buildStackName(stack)
if err != nil {
return nil, err
}
s, err := stackInit(b, stackName, setCurrent, secretsProvider)
if err != nil {
return nil, err
}
@ -536,7 +544,14 @@ func promptAndCreateStack(prompt promptForValueFunc,
if err != nil {
return nil, err
}
s, err := stackInit(b, stackName, setCurrent, secretsProvider)
formattedStackName, err := buildStackName(stackName)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
s, err := stackInit(b, formattedStackName, setCurrent, secretsProvider)
if err != nil {
if !yes {
// Let the user know about the error and loop around to try again.
@ -577,8 +592,9 @@ func installDependencies(proj *workspace.Project, root string) error {
// TODO[pulumi/pulumi#1334]: move to the language plugins so we don't have to hard code here.
if strings.EqualFold(proj.Runtime.Name(), "nodejs") {
if bin, err := nodeInstallDependencies(); err != nil {
return errors.Wrapf(err, "%s install failed; rerun manually to try again, "+
"then run 'pulumi up' to perform an initial deployment", bin)
return fmt.Errorf("%s install failed; rerun manually to try again, "+
"then run 'pulumi up' to perform an initial deployment"+": %w", bin, err)
}
} else if strings.EqualFold(proj.Runtime.Name(), "python") {
return pythonInstallDependencies(proj, root)
@ -620,7 +636,7 @@ func pythonInstallDependencies(proj *workspace.Project, root string) error {
// Save project with venv info.
proj.Runtime.SetOption("virtualenv", venvDir)
if err := workspace.SaveProject(proj); err != nil {
return errors.Wrap(err, "saving project")
return fmt.Errorf("saving project: %w", err)
}
return nil
}
@ -671,8 +687,9 @@ func goInstallDependencies() error {
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "`go mod tidy` failed to install dependencies; rerun manually to try again, "+
"then run 'pulumi up' to perform an initial deployment")
return fmt.Errorf("`go mod tidy` failed to install dependencies; rerun manually to try again, "+
"then run 'pulumi up' to perform an initial deployment"+": %w", err)
}
fmt.Println("Finished installing dependencies")

View file

@ -16,13 +16,14 @@ package main
import (
"context"
"fmt"
"github.com/stretchr/testify/require"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"

153
pkg/cmd/pulumi/org.go Normal file
View file

@ -0,0 +1,153 @@
// 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.
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
)
func newOrgCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "org",
Short: "Manage Organization configuration",
Long: "Manage Organization configuration.\n" +
"\n" +
"Use this command to manage organization configuration, " +
"e.g. setting the default organization for a backend",
Args: cmdutil.NoArgs,
Run: cmdutil.RunFunc(func(cmd *cobra.Command, args []string) error {
cloudURL, err := workspace.GetCurrentCloudURL()
if err != nil {
return err
}
defaultOrg, err := workspace.GetBackendConfigDefaultOrg()
if err != nil {
return err
}
fmt.Printf("Current Backend: %s\n", cloudURL)
if defaultOrg != "" {
fmt.Printf("Default Org: %s", defaultOrg)
} else {
fmt.Println("No Default Org Specified")
}
return nil
}),
}
cmd.AddCommand(newOrgSetDefaultCmd())
cmd.AddCommand(newOrgGetDefaultCmd())
return cmd
}
func newOrgSetDefaultCmd() *cobra.Command {
var orgName string
var cmd = &cobra.Command{
Use: "set-default [NAME]",
Args: cmdutil.ExactArgs(1),
Short: "Set the default organization for the current backend",
Long: "Set the default organization for the current backend.\n" +
"\n" +
"This command is used to set the default organization in which to create \n" +
"projects and stacks for the current backend.\n" +
"\n" +
"Currently, only the managed and self-hosted backends support organizations. " +
"If you try and set a default organization for a backend that does not \n" +
"support create organizations, then an error will be returned by the CLI",
Run: cmdutil.RunFunc(func(cmd *cobra.Command, args []string) error {
displayOpts := display.Options{
Color: cmdutil.GetGlobalColorization(),
}
orgName = args[0]
currentBe, err := currentBackend(displayOpts)
if err != nil {
return err
}
if !currentBe.SupportsOrganizations() {
return fmt.Errorf("unable to set a default organization for backend type: %s",
currentBe.Name())
}
if _, ok := currentBe.(httpstate.Backend); ok {
cloudURL, err := workspace.GetCurrentCloudURL()
if err != nil {
return err
}
if err := httpstate.SetDefaultOrg(cloudURL, orgName); err != nil {
return err
}
}
return nil
}),
}
return cmd
}
func newOrgGetDefaultCmd() *cobra.Command {
var cmd = &cobra.Command{
Use: "get-default",
Short: "Get the default org for the current backend",
Long: "Get the default org for the current backend.\n" +
"\n" +
"This command is used to get the default organization for which and stacks are created in " +
"the current backend.\n" +
"\n" +
"Currently, only the managed and self-hosted backends support organizations.",
Run: cmdutil.RunFunc(func(cmd *cobra.Command, args []string) error {
displayOpts := display.Options{
Color: cmdutil.GetGlobalColorization(),
}
currentBe, err := currentBackend(displayOpts)
if err != nil {
return err
}
if !currentBe.SupportsOrganizations() {
return fmt.Errorf("backends of this type %q do not support organizations",
currentBe.Name())
}
defaultOrg, err := workspace.GetBackendConfigDefaultOrg()
if err != nil {
return err
}
if defaultOrg != "" {
fmt.Println(defaultOrg)
} else {
fmt.Println("No Default Org Specified")
}
return nil
}),
}
return cmd
}

View file

@ -15,6 +15,7 @@
package main
import (
"errors"
"fmt"
"io"
"os"
@ -22,7 +23,7 @@ import (
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -59,7 +60,7 @@ func newPluginInstallCmd() *cobra.Command {
var installs []workspace.PluginInfo
if len(args) > 0 {
if !workspace.IsPluginKind(args[0]) {
return errors.Errorf("unrecognized plugin kind: %s", args[0])
return fmt.Errorf("unrecognized plugin kind: %s", args[0])
} else if len(args) < 2 {
return errors.New("missing plugin name argument")
} else if len(args) < 3 {
@ -67,7 +68,7 @@ func newPluginInstallCmd() *cobra.Command {
}
version, err := semver.ParseTolerant(args[2])
if err != nil {
return errors.Wrap(err, "invalid plugin semver")
return fmt.Errorf("invalid plugin semver: %w", err)
}
installs = append(installs, workspace.PluginInfo{
Kind: workspace.PluginKind(args[0]),
@ -124,19 +125,19 @@ func newPluginInstallCmd() *cobra.Command {
if file == "" {
var size int64
if tarball, size, err = install.Download(); err != nil {
return errors.Wrapf(err, "%s downloading from %s", label, install.ServerURL)
return fmt.Errorf("%s downloading from %s: %w", label, install.ServerURL, err)
}
tarball = workspace.ReadCloserProgressBar(tarball, size, "Downloading plugin", displayOpts.Color)
} else {
source = file
logging.V(1).Infof("%s opening tarball from %s", label, file)
if tarball, err = os.Open(file); err != nil {
return errors.Wrapf(err, "opening file %s", source)
return fmt.Errorf("opening file %s: %w", source, err)
}
}
logging.V(1).Infof("%s installing tarball ...", label)
if err = install.Install(tarball); err != nil {
return errors.Wrapf(err, "installing %s from %s", label, source)
return fmt.Errorf("installing %s from %s: %w", label, source, err)
}
}

View file

@ -19,7 +19,7 @@ import (
"sort"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
@ -39,11 +39,11 @@ func newPluginLsCmd() *cobra.Command {
var err error
if projectOnly {
if plugins, err = getProjectPlugins(); err != nil {
return errors.Wrapf(err, "loading project plugins")
return fmt.Errorf("loading project plugins: %w", err)
}
} else {
if plugins, err = workspace.GetPluginsWithMetadata(); err != nil {
return errors.Wrapf(err, "loading plugins")
return fmt.Errorf("loading plugins: %w", err)
}
}

View file

@ -16,11 +16,12 @@ package main
import (
"fmt"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/blang/semver"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -58,11 +59,11 @@ func newPluginRmCmd() *cobra.Command {
var version *semver.Range
if len(args) > 0 {
if !workspace.IsPluginKind(args[0]) {
return errors.Errorf("unrecognized plugin kind: %s", kind)
return fmt.Errorf("unrecognized plugin kind: %s", kind)
}
kind = workspace.PluginKind(args[0])
} else if !all {
return errors.Errorf("please pass --all if you'd like to remove all plugins")
return fmt.Errorf("please pass --all if you'd like to remove all plugins")
}
if len(args) > 1 {
name = args[1]
@ -70,7 +71,7 @@ func newPluginRmCmd() *cobra.Command {
if len(args) > 2 {
r, err := semver.ParseRange(args[2])
if err != nil {
return errors.Wrap(err, "invalid plugin semver")
return fmt.Errorf("invalid plugin semver: %w", err)
}
version = &r
}
@ -79,7 +80,7 @@ func newPluginRmCmd() *cobra.Command {
var deletes []workspace.PluginInfo
plugins, err := workspace.GetPlugins()
if err != nil {
return errors.Wrap(err, "loading plugins")
return fmt.Errorf("loading plugins: %w", err)
}
for _, plugin := range plugins {
if (kind == "" || plugin.Kind == kind) &&
@ -112,7 +113,7 @@ func newPluginRmCmd() *cobra.Command {
for _, plugin := range deletes {
if err := plugin.Delete(); err != nil {
result = multierror.Append(
result, errors.Wrapf(err, "failed to delete %s plugin %s", plugin.Kind, plugin))
result, fmt.Errorf("failed to delete %s plugin %s: %w", plugin.Kind, plugin, err))
}
}
if result != nil {

View file

@ -15,12 +15,12 @@
package main
import (
"errors"
"fmt"
"os"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag/colors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
@ -98,7 +98,7 @@ func runNewPolicyPack(args newPolicyArgs) error {
// Get the current working directory.
cwd, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "getting the working directory")
return fmt.Errorf("getting the working directory: %w", err)
}
// If dir was specified, ensure it exists and use it as the
@ -147,7 +147,7 @@ func runNewPolicyPack(args newPolicyArgs) error {
if !args.force {
if err = workspace.CopyTemplateFilesDryRun(template.Dir, cwd, ""); err != nil {
if os.IsNotExist(err) {
return errors.Wrapf(err, "template '%s' not found", args.templateNameOrURL)
return fmt.Errorf("template '%s' not found: %w", args.templateNameOrURL, err)
}
return err
}
@ -156,7 +156,7 @@ func runNewPolicyPack(args newPolicyArgs) error {
// Actually copy the files.
if err = workspace.CopyTemplateFiles(template.Dir, cwd, args.force, "", ""); err != nil {
if os.IsNotExist(err) {
return errors.Wrapf(err, "template '%s' not found", args.templateNameOrURL)
return fmt.Errorf("template '%s' not found: %w", args.templateNameOrURL, err)
}
return err
}
@ -190,7 +190,7 @@ func installPolicyPackDependencies(proj *workspace.PolicyPackProject, projPath,
// TODO[pulumi/pulumi#1334]: move to the language plugins so we don't have to hard code here.
if strings.EqualFold(proj.Runtime.Name(), "nodejs") {
if bin, err := nodeInstallDependencies(); err != nil {
return errors.Wrapf(err, "`%s install` failed; rerun manually to try again.", bin)
return fmt.Errorf("`%s install` failed; rerun manually to try again.: %w", bin, err)
}
} else if strings.EqualFold(proj.Runtime.Name(), "python") {
const venvDir = "venv"
@ -201,7 +201,7 @@ func installPolicyPackDependencies(proj *workspace.PolicyPackProject, projPath,
// Save project with venv info.
proj.Runtime.SetOption("virtualenv", venvDir)
if err := proj.Save(projPath); err != nil {
return errors.Wrapf(err, "saving project at %s", projPath)
return fmt.Errorf("saving project at %s: %w", projPath, err)
}
}
return nil

View file

@ -15,10 +15,10 @@
package main
import (
"errors"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate"
@ -110,8 +110,8 @@ func requirePolicyPack(policyPack string) (backend.PolicyPack, error) {
cloudURL, err := workspace.GetCurrentCloudURL()
if err != nil {
return nil, errors.Wrap(err,
"`pulumi policy` command requires the user to be logged into the Pulumi service")
return nil, fmt.Errorf("`pulumi policy` command requires the user to be logged into the Pulumi service: %w", err)
}
displayOptions := display.Options{

View file

@ -16,6 +16,7 @@ package main
import (
"fmt"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"

View file

@ -15,7 +15,9 @@
package main
import (
"github.com/pkg/errors"
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -134,17 +136,17 @@ func newPreviewCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
targetURNs := []resource.URN{}

View file

@ -18,8 +18,8 @@ import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
user "github.com/tweekmonster/luser"
"net/http"
"net/url"
"os"
@ -30,10 +30,12 @@ import (
"strings"
"time"
user "github.com/tweekmonster/luser"
"github.com/blang/semver"
"github.com/djherbis/times"
"github.com/docker/docker/pkg/term"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -210,6 +212,7 @@ func NewPulumiCmd() *cobra.Command {
cmd.AddCommand(newConsoleCmd())
cmd.AddCommand(newAboutCmd())
cmd.AddCommand(newSchemaCmd())
cmd.AddCommand(newOrgCmd())
// Less common, and thus hidden, commands:
cmd.AddCommand(newGenCompletionCmd(cmd))
@ -435,7 +438,7 @@ func isBrewInstall(exe string) (bool, error) {
if ee, ok := err.(*exec.ExitError); ok {
ee.Stderr = stderr.Bytes()
}
return false, errors.Wrapf(err, "'brew --prefix pulumi' failed")
return false, fmt.Errorf("'brew --prefix pulumi' failed: %w", err)
}
brewPrefixCmdOutput := strings.TrimSpace(stdout.String())

View file

@ -16,8 +16,9 @@ package main
import (
"context"
"errors"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -124,17 +125,17 @@ func newRefreshCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
targetUrns := []resource.URN{}

View file

@ -16,13 +16,14 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"

View file

@ -18,6 +18,7 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/resource/stack"

View file

@ -16,9 +16,9 @@ package main
import (
"encoding/json"
"fmt"
"os"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/resource/stack"
"github.com/spf13/cobra"
@ -69,8 +69,7 @@ func newStackExportCmd() *cobra.Command {
be := s.Backend()
specificExpBE, ok := be.(backend.SpecificDeploymentExporter)
if !ok {
return errors.Errorf(
"the current backend (%s) does not provide the ability to export previous deployments",
return fmt.Errorf("the current backend (%s) does not provide the ability to export previous deployments",
be.Name())
}
@ -85,7 +84,7 @@ func newStackExportCmd() *cobra.Command {
if file != "" {
writer, err = os.Create(file)
if err != nil {
return errors.Wrap(err, "could not open file")
return fmt.Errorf("could not open file: %w", err)
}
}
@ -116,7 +115,7 @@ func newStackExportCmd() *cobra.Command {
enc.SetIndent("", " ")
if err = enc.Encode(deployment); err != nil {
return errors.Wrap(err, "could not export deployment")
return fmt.Errorf("could not export deployment: %w", err)
}
return nil

View file

@ -15,7 +15,7 @@
package main
import (
"github.com/pkg/errors"
"fmt"
"os"
"strings"
@ -68,7 +68,7 @@ func newStackGraphCmd() *cobra.Command {
// This will prevent a panic when trying to assemble a dependencyGraph when no snapshot is found
if snap == nil {
return errors.Errorf("unable to find snapshot for stack %q", stackName)
return fmt.Errorf("unable to find snapshot for stack %q", stackName)
}
dg := makeDependencyGraph(snap)

View file

@ -8,7 +8,7 @@ import (
"time"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -47,13 +47,13 @@ This command displays data about previous updates for a stack.`,
b := s.Backend()
updates, err := b.GetHistory(commandContext(), s.Ref(), pageSize, page)
if err != nil {
return errors.Wrap(err, "getting history")
return fmt.Errorf("getting history: %w", err)
}
var decrypter config.Decrypter
if showSecrets {
crypter, err := getStackDecrypter(s)
if err != nil {
return errors.Wrap(err, "decrypting secrets")
return fmt.Errorf("decrypting secrets: %w", err)
}
decrypter = crypter
}

View file

@ -16,11 +16,12 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -61,7 +62,7 @@ func newStackImportCmd() *cobra.Command {
if file != "" {
reader, err = os.Open(file)
if err != nil {
return errors.Wrap(err, "could not open file")
return fmt.Errorf("could not open file: %w", err)
}
}
@ -122,7 +123,7 @@ func newStackImportCmd() *cobra.Command {
}
sdp, err := stack.SerializeDeployment(snapshot, snapshot.SecretsManager, false /* showSecrets */)
if err != nil {
return errors.Wrap(err, "constructing deployment for upload")
return fmt.Errorf("constructing deployment for upload: %w", err)
}
bytes, err := json.Marshal(sdp)
@ -137,7 +138,7 @@ func newStackImportCmd() *cobra.Command {
// Now perform the deployment.
if err = s.ImportDeployment(commandContext(), &dep); err != nil {
return errors.Wrap(err, "could not import deployment")
return fmt.Errorf("could not import deployment: %w", err)
}
fmt.Printf("Import successful.\n")
return nil

View file

@ -15,9 +15,9 @@
package main
import (
"errors"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -107,11 +107,15 @@ func newStackInitCmd() *cobra.Command {
return errors.New("missing stack name")
}
if err := b.ValidateStackName(stackName); err != nil {
formattedStackName, err := buildStackName(stackName)
if err != nil {
return err
}
if err := b.ValidateStackName(formattedStackName); err != nil {
return err
}
stackRef, err := b.ParseStackReference(stackName)
stackRef, err := b.ParseStackReference(formattedStackName)
if err != nil {
return err
}

View file

@ -15,12 +15,14 @@
package main
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/dustin/go-humanize"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -110,14 +112,14 @@ func runStackLS(args stackLSArgs) error {
// Ensure we are in a project; if not, we will fail.
projPath, err := workspace.DetectProjectPath()
if err != nil {
return errors.Wrapf(err, "could not detect current project")
return fmt.Errorf("could not detect current project: %w", err)
} else if projPath == "" {
return errors.New("no Pulumi.yaml found; please run this command in a project directory")
}
proj, err := workspace.LoadProject(projPath)
if err != nil {
return errors.Wrap(err, "could not load current project")
return fmt.Errorf("could not load current project: %w", err)
}
projName := string(proj.Name)
filter.Project = &projName

View file

@ -17,7 +17,6 @@ package main
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -57,7 +56,7 @@ func newStackOutputCmd() *cobra.Command {
outputs, err := getStackOutputs(snap, showSecrets)
if err != nil {
return errors.Wrap(err, "getting outputs")
return fmt.Errorf("getting outputs: %w", err)
}
if outputs == nil {
outputs = make(map[string]interface{})
@ -76,7 +75,7 @@ func newStackOutputCmd() *cobra.Command {
fmt.Printf("%v\n", stringifyOutput(v))
}
} else {
return errors.Errorf("current stack does not have output property '%v'", name)
return fmt.Errorf("current stack does not have output property '%v'", name)
}
} else if jsonOut {
if err := printJSON(outputs); err != nil {

View file

@ -21,7 +21,6 @@ import (
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -79,15 +78,15 @@ func newStackRenameCmd() *cobra.Command {
// Stack doesn't have any configuration, ignore.
case configStatErr == nil:
if err := os.Rename(oldConfigPath, newConfigPath); err != nil {
return errors.Wrapf(err, "renaming configuration file to %s", filepath.Base(newConfigPath))
return fmt.Errorf("renaming configuration file to %s: %w", filepath.Base(newConfigPath), err)
}
default:
return errors.Wrapf(err, "checking current configuration file %v", oldConfigPath)
return fmt.Errorf("checking current configuration file %v: %w", oldConfigPath, err)
}
// Update the current workspace state to have selected the new stack.
if err := state.SetCurrentStack(newStackName); err != nil {
return errors.Wrap(err, "setting current stack")
return fmt.Errorf("setting current stack: %w", err)
}
fmt.Printf("Renamed %s to %s\n", s.Ref().String(), newStackRef.String())

View file

@ -15,7 +15,9 @@
package main
import (
"github.com/pkg/errors"
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
@ -80,7 +82,7 @@ func newStackSelectCmd() *cobra.Command {
return state.SetCurrentStack(s.Ref().String())
}
return errors.Errorf("no stack named '%s' found", stackRef)
return fmt.Errorf("no stack named '%s' found", stackRef)
}
// If no stack was given, prompt the user to select a name from the available ones.

View file

@ -18,7 +18,6 @@ import (
"fmt"
"sort"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -79,8 +78,7 @@ func newStackTagGetCmd(stack *string) *cobra.Command {
return nil
}
return errors.Errorf(
"stack tag '%s' not found for stack '%s'", name, s.Ref())
return fmt.Errorf("stack tag '%s' not found for stack '%s'", name, s.Ref())
}),
}
}

View file

@ -16,9 +16,9 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/pkg/v3/resource/edit"
@ -57,7 +57,7 @@ func locateStackResource(opts display.Options, snap *deploy.Snapshot, urn resour
candidateResources := edit.LocateResource(snap, urn)
switch {
case len(candidateResources) == 0: // resource was not found
return nil, errors.Errorf("No such resource %q exists in the current state", urn)
return nil, fmt.Errorf("No such resource %q exists in the current state", urn)
case len(candidateResources) == 1: // resource was unambiguously found
return candidateResources[0], nil
}
@ -170,7 +170,7 @@ func runTotalStateEdit(
sdep, err := stack.SerializeDeployment(snap, snap.SecretsManager, false /* showSecrets */)
if err != nil {
return result.FromError(errors.Wrap(err, "serializing deployment"))
return result.FromError(fmt.Errorf("serializing deployment: %w", err))
}
// Once we've mutated the snapshot, import it back into the backend so that it can be persisted.

View file

@ -16,12 +16,12 @@ package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"math"
"os"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -97,17 +97,17 @@ func newUpCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
targetURNs := []resource.URN{}
@ -225,7 +225,7 @@ func newUpCmd() *cobra.Command {
// Change the working directory to the "virtual workspace" directory.
if err = os.Chdir(temp); err != nil {
return result.FromError(errors.Wrap(err, "changing the working directory"))
return result.FromError(fmt.Errorf("changing the working directory: %w", err))
}
// If a stack was specified via --stack, see if it already exists.
@ -273,7 +273,7 @@ func newUpCmd() *cobra.Command {
proj.Description = &description
proj.Template = nil
if err = workspace.SaveProject(proj); err != nil {
return result.FromError(errors.Wrap(err, "saving project"))
return result.FromError(fmt.Errorf("saving project: %w", err))
}
// Create the stack, if needed.
@ -297,17 +297,17 @@ func newUpCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, execAgent)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
refreshOption, err := getRefreshOption(proj, refresh)
@ -613,7 +613,7 @@ func handleConfig(
// Save the config.
if len(c) > 0 {
if err = saveConfig(s, c); err != nil {
return errors.Wrap(err, "saving config")
return fmt.Errorf("saving config: %w", err)
}
fmt.Println("Saved config")

View file

@ -18,6 +18,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
@ -30,7 +31,7 @@ import (
multierror "github.com/hashicorp/go-multierror"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
survey "gopkg.in/AlecAivazis/survey.v1"
surveycore "gopkg.in/AlecAivazis/survey.v1/core"
git "gopkg.in/src-d/go-git.v4"
@ -102,7 +103,7 @@ func isFilestateBackend(opts display.Options) (bool, error) {
url, err := workspace.GetCurrentCloudURL()
if err != nil {
return false, errors.Wrapf(err, "could not get cloud url")
return false, fmt.Errorf("could not get cloud url: %w", err)
}
return filestate.IsFileStateBackendURL(url), nil
@ -115,7 +116,7 @@ func currentBackend(opts display.Options) (backend.Backend, error) {
url, err := workspace.GetCurrentCloudURL()
if err != nil {
return nil, errors.Wrapf(err, "could not get cloud url")
return nil, fmt.Errorf("could not get cloud url: %w", err)
}
if filestate.IsFileStateBackendURL(url) {
@ -187,7 +188,7 @@ func createSecretsManager(b backend.Backend, stackRef backend.StackReference, se
if strings.HasPrefix(secretsProvider, "azurekeyvault://") {
parsed, err := url.Parse(secretsProvider)
if err != nil {
return errors.Wrap(err, "failed to parse secrets provider URL")
return fmt.Errorf("failed to parse secrets provider URL: %w", err)
}
if parsed.Query().Get("algorithm") == "" {
@ -218,7 +219,7 @@ func createStack(
if _, ok := err.(*backend.OverStackLimitError); ok {
return nil, err
}
return nil, errors.Wrapf(err, "could not create stack")
return nil, fmt.Errorf("could not create stack: %w", err)
}
if err := createSecretsManager(b, stackRef, secretsProvider,
@ -275,7 +276,7 @@ func requireStack(
return createStack(b, stackRef, nil, setCurrent, "")
}
return nil, errors.Errorf("no stack named '%s' found", stackName)
return nil, fmt.Errorf("no stack named '%s' found", stackName)
}
func requireCurrentStack(offerNew bool, opts display.Options, setCurrent bool) (backend.Stack, error) {
@ -327,7 +328,7 @@ func chooseStack(
for {
summaries, outContToken, err := b.ListStacks(ctx, backend.ListStacksFilter{Project: &project}, inContToken)
if err != nil {
return nil, errors.Wrapf(err, "could not query backend for stacks")
return nil, fmt.Errorf("could not query backend for stacks: %w", err)
}
allSummaries = append(allSummaries, summaries...)
@ -407,15 +408,15 @@ func chooseStack(
// With the stack name selected, look it up from the backend.
stackRef, err := b.ParseStackReference(option)
if err != nil {
return nil, errors.Wrap(err, "parsing selected stack")
return nil, fmt.Errorf("parsing selected stack: %w", err)
}
// GetStack may return (nil, nil) if the stack isn't found.
stack, err := b.GetStack(ctx, stackRef)
if err != nil {
return nil, errors.Wrap(err, "getting selected stack")
return nil, fmt.Errorf("getting selected stack: %w", err)
}
if stack == nil {
return nil, errors.Errorf("no stack named '%s' found", stackRef)
return nil, fmt.Errorf("no stack named '%s' found", stackRef)
}
// If setCurrent is true, we'll persist this choice so it'll be used for future CLI operations.
@ -440,7 +441,7 @@ func parseAndSaveConfigArray(s backend.Stack, configArray []string, path bool) e
}
if err = saveConfig(s, commandLineConfig); err != nil {
return errors.Wrap(err, "saving config")
return fmt.Errorf("saving config: %w", err)
}
return nil
}
@ -475,8 +476,9 @@ func readProject() (*workspace.Project, string, error) {
// Now that we got here, we have a path, so we will try to load it.
path, err := workspace.DetectProjectPathFrom(pwd)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to find current Pulumi project because of "+
"an error when searching for the Pulumi.yaml file (searching upwards from %s)", pwd)
return nil, "", fmt.Errorf("failed to find current Pulumi project because of "+
"an error when searching for the Pulumi.yaml file (searching upwards from %s)"+": %w", pwd, err)
} else if path == "" {
return nil, "", fmt.Errorf(
"no Pulumi.yaml project file found (searching upwards from %s). If you have not "+
@ -484,7 +486,7 @@ func readProject() (*workspace.Project, string, error) {
}
proj, err := workspace.LoadProject(path)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to load Pulumi project located at %q", path)
return nil, "", fmt.Errorf("failed to load Pulumi project located at %q: %w", path, err)
}
return proj, filepath.Dir(path), nil
@ -502,14 +504,15 @@ func readPolicyProject() (*workspace.PolicyPackProject, string, string, error) {
// Now that we got here, we have a path, so we will try to load it.
path, err := workspace.DetectPolicyPackPathFrom(pwd)
if err != nil {
return nil, "", "", errors.Wrapf(err, "failed to find current Pulumi project because of "+
"an error when searching for the PulumiPolicy.yaml file (searching upwards from %s)", pwd)
return nil, "", "", fmt.Errorf("failed to find current Pulumi project because of "+
"an error when searching for the PulumiPolicy.yaml file (searching upwards from %s)"+": %w", pwd, err)
} else if path == "" {
return nil, "", "", fmt.Errorf("no PulumiPolicy.yaml project file found (searching upwards from %s)", pwd)
}
proj, err := workspace.LoadPolicyPack(path)
if err != nil {
return nil, "", "", errors.Wrapf(err, "failed to load Pulumi policy project located at %q", path)
return nil, "", "", fmt.Errorf("failed to load Pulumi policy project located at %q: %w", path, err)
}
return proj, path, filepath.Dir(path), nil
@ -543,7 +546,7 @@ func isGitWorkTreeDirty(repoRoot string) (bool, error) {
if ee, ok := err.(*exec.ExitError); ok {
ee.Stderr = stderr.Bytes()
}
return false, errors.Wrapf(err, "'git status' failed")
return false, fmt.Errorf("'git status' failed: %w", err)
}
return bool(anyOutput), nil
@ -575,7 +578,7 @@ func addGitMetadata(repoRoot string, m *backend.UpdateMetadata) error {
// Gather git-related data as appropriate. (Returns nil, nil if no repo found.)
repo, err := gitutil.GetGitRepository(repoRoot)
if err != nil {
return errors.Wrapf(err, "detecting Git repository")
return fmt.Errorf("detecting Git repository: %w", err)
}
if repo == nil {
return nil
@ -599,7 +602,7 @@ func AddGitRemoteMetadataToMap(repo *git.Repository, env map[string]string) erro
// Get the remote URL for this repo.
remoteURL, err := gitutil.GetGitRemoteURL(repo, "origin")
if err != nil {
return errors.Wrap(err, "detecting Git remote URL")
return fmt.Errorf("detecting Git remote URL: %w", err)
}
if remoteURL == "" {
return nil
@ -618,7 +621,7 @@ func addVCSMetadataToEnvironment(remoteURL string, env map[string]string) error
// We don't require a cloud-hosted VCS, so swallow errors.
vcsInfo, err := gitutil.TryGetVCSInfo(remoteURL)
if err != nil {
return errors.Wrap(err, "detecting VCS project information")
return fmt.Errorf("detecting VCS project information: %w", err)
}
env[backend.VCSRepoOwner] = vcsInfo.Owner
env[backend.VCSRepoName] = vcsInfo.Repo
@ -636,14 +639,14 @@ func addGitCommitMetadata(repo *git.Repository, repoRoot string, m *backend.Upda
// Commit at HEAD
head, err := repo.Head()
if err != nil {
return errors.Wrap(err, "getting repository HEAD")
return fmt.Errorf("getting repository HEAD: %w", err)
}
hash := head.Hash()
m.Environment[backend.GitHead] = hash.String()
commit, commitErr := repo.CommitObject(hash)
if commitErr != nil {
return errors.Wrap(commitErr, "getting HEAD commit info")
return fmt.Errorf("getting HEAD commit info: %w", commitErr)
}
// If in detached head, will be "HEAD", and fallback to use value from CI/CD system if possible.
@ -674,7 +677,7 @@ func addGitCommitMetadata(repo *git.Repository, repoRoot string, m *backend.Upda
// If the worktree is dirty, set a bit, as this could be a mistake.
isDirty, err := isGitWorkTreeDirty(repoRoot)
if err != nil {
return errors.Wrapf(err, "checking git worktree dirty state")
return fmt.Errorf("checking git worktree dirty state: %w", err)
}
m.Environment[backend.GitDirty] = strconv.FormatBool(isDirty)
@ -840,7 +843,7 @@ func checkDeploymentVersionError(err error, stackName string) error {
return fmt.Errorf("the stack '%s' is newer than what this version of the Pulumi CLI understands. "+
"Please update your version of the Pulumi CLI", stackName)
}
return errors.Wrap(err, "could not deserialize deployment")
return fmt.Errorf("could not deserialize deployment: %w", err)
}
func getRefreshOption(proj *workspace.Project, refresh string) (bool, error) {
@ -893,3 +896,20 @@ func readPlan(path string, dec config.Decrypter, enc config.Encrypter) (deploy.P
}
return stack.DeserializePlan(deploymentPlan, dec, enc)
}
func buildStackName(stackName string) (string, error) {
if strings.Count(stackName, "/") == 2 {
return stackName, nil
}
defaultOrg, err := workspace.GetBackendConfigDefaultOrg()
if err != nil {
return "", err
}
if defaultOrg != "" {
return fmt.Sprintf("%s/%s", defaultOrg, stackName), nil
}
return stackName, nil
}

View file

@ -16,8 +16,9 @@ package main
import (
"context"
"errors"
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/pulumi/pulumi/pkg/v3/backend"
@ -101,17 +102,17 @@ func newWatchCmd() *cobra.Command {
m, err := getUpdateMetadata(message, root, execKind, "" /* execAgent */)
if err != nil {
return result.FromError(errors.Wrap(err, "gathering environment metadata"))
return result.FromError(fmt.Errorf("gathering environment metadata: %w", err))
}
sm, err := getStackSecretsManager(s)
if err != nil {
return result.FromError(errors.Wrap(err, "getting secrets manager"))
return result.FromError(fmt.Errorf("getting secrets manager: %w", err))
}
cfg, err := getStackConfiguration(s, sm)
if err != nil {
return result.FromError(errors.Wrap(err, "getting stack configuration"))
return result.FromError(fmt.Errorf("getting stack configuration: %w", err))
}
opts.Engine = engine.UpdateOptions{

View file

@ -23,6 +23,7 @@ package docs
import (
"bytes"
"embed"
"errors"
"fmt"
"html"
"html/template"
@ -31,7 +32,6 @@ import (
"strings"
"github.com/golang/glog"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/dotnet"
@ -431,7 +431,7 @@ func (dctx *docGenContext) getLanguageDocHelper(lang string) codegen.DocLanguage
if h, ok := dctx.docHelpers[lang]; ok {
return h
}
panic(errors.Errorf("could not find a doc lang helper for %s", lang))
panic(fmt.Errorf("could not find a doc lang helper for %s", lang))
}
type propertyCharacteristics struct {
@ -1174,7 +1174,7 @@ func (mod *modContext) getConstructorResourceInfo(resourceTypeName string) map[s
resourceTypeName = fmt.Sprintf("Pulumi.%s.%s.%s", namespace, modName, resourceTypeName)
default:
panic(errors.Errorf("cannot generate constructor info for unhandled language %q", lang))
panic(fmt.Errorf("cannot generate constructor info for unhandled language %q", lang))
}
parts := strings.Split(resourceTypeName, ".")

View file

@ -23,7 +23,6 @@ import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
go_gen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
"github.com/pulumi/pulumi/pkg/v3/codegen/python"
@ -113,7 +112,7 @@ func (mod *modContext) getFunctionResourceInfo(f *schema.Function, outputVersion
case "python":
resultTypeName = docLangHelper.GetResourceFunctionResultName(mod.mod, f)
default:
panic(errors.Errorf("cannot generate function resource info for unhandled language %q", lang))
panic(fmt.Errorf("cannot generate function resource info for unhandled language %q", lang))
}
parts := strings.Split(resultTypeName, ".")

View file

@ -20,10 +20,11 @@ package docs
import (
"fmt"
"testing"
"github.com/pulumi/pulumi/pkg/v3/codegen/internal/test"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/stretchr/testify/assert"
"testing"
)
const (

View file

@ -1,7 +1,7 @@
package docs
import (
"github.com/pkg/errors"
"fmt"
"sort"
)
@ -36,7 +36,7 @@ func generatePackageTree(rootMod modContext) ([]PackageTreeItem, error) {
children, err := generatePackageTree(*m)
if err != nil {
return nil, errors.Wrapf(err, "generating children for module %s (mod token: %s)", displayName, m.mod)
return nil, fmt.Errorf("generating children for module %s (mod token: %s): %w", displayName, m.mod, err)
}
ti := PackageTreeItem{

View file

@ -32,7 +32,6 @@ import (
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -767,7 +766,7 @@ func primitiveValue(value interface{}) (string, error) {
case reflect.String:
return fmt.Sprintf("%q", v.String()), nil
default:
return "", errors.Errorf("unsupported default value of type %T", value)
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
@ -796,7 +795,7 @@ func (mod *modContext) getDefaultValue(dv *schema.DefaultValue, t schema.Type) (
break
}
if val == "" {
return "", errors.Errorf("default value '%v' not found in enum '%s'", dv.Value, enumName)
return "", fmt.Errorf("default value '%v' not found in enum '%s'", dv.Value, enumName)
}
default:
v, err := primitiveValue(dv.Value)
@ -1995,6 +1994,11 @@ func (mod *modContext) gen(fs fs) error {
// Resources
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
imports := map[string]codegen.StringSet{}
mod.getImportsForResource(r, imports, r)
@ -2017,6 +2021,11 @@ func (mod *modContext) gen(fs fs) error {
// Functions
for _, f := range mod.functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
code, err := mod.genFunctionFileCode(f)
if err != nil {
return err
@ -2026,6 +2035,11 @@ func (mod *modContext) gen(fs fs) error {
// Nested types
for _, t := range mod.types {
if t.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
if mod.details(t).inputType {
buffer := &bytes.Buffer{}
mod.genHeader(buffer, pulumiImports)
@ -2186,6 +2200,11 @@ func generateModuleContextMap(tool string, pkg *schema.Package) (map[string]*mod
computePropertyNames(pkg.Config, propertyNames)
computePropertyNames(pkg.Provider.InputProperties, propertyNames)
for _, r := range pkg.Resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
computePropertyNames(r.Properties, propertyNames)
computePropertyNames(r.InputProperties, propertyNames)
if r.StateInputs != nil {
@ -2193,6 +2212,11 @@ func generateModuleContextMap(tool string, pkg *schema.Package) (map[string]*mod
}
}
for _, f := range pkg.Functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
if f.Inputs != nil {
computePropertyNames(f.Inputs.Properties, propertyNames)
}
@ -2289,6 +2313,11 @@ func generateModuleContextMap(tool string, pkg *schema.Package) (map[string]*mod
// Find input and output types referenced by functions.
for _, f := range pkg.Functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
mod := getModFromToken(f.Token, pkg)
if !f.IsMethod {
mod.functions = append(mod.functions, f)
@ -2347,6 +2376,11 @@ func LanguageResources(tool string, pkg *schema.Package) (map[string]LanguageRes
continue
}
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
lr := LanguageResource{
Resource: r,
Package: namespaceName(info.Namespaces, modName),

View file

@ -15,13 +15,12 @@
package dotnet
import (
"fmt"
"regexp"
"strings"
"unicode"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pkg/errors"
)
// isReservedWord returns true if s is a C# reserved word as per
@ -97,7 +96,7 @@ func makeSafeEnumName(name, typeName string) (string, error) {
// If the name is one illegal character, return an error.
if len(safeName) == 1 && !isLegalIdentifierStart(rune(safeName[0])) {
return "", errors.Errorf("enum name %s is not a valid identifier", safeName)
return "", fmt.Errorf("enum name %s is not a valid identifier", safeName)
}
// Capitalize and make a valid identifier.

View file

@ -1,6 +1,8 @@
package dotnet
import "testing"
import (
"testing"
)
func TestMakeSafeEnumName(t *testing.T) {
tests := []struct {

View file

@ -31,8 +31,6 @@ import (
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -1283,7 +1281,7 @@ func goPrimitiveValue(value interface{}) (string, error) {
case reflect.String:
return fmt.Sprintf("%q", v.String()), nil
default:
return "", errors.Errorf("unsupported default value of type %T", value)
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
@ -2019,6 +2017,10 @@ func rewriteCyclicObjectFields(pkg *schema.Package) {
func (pkg *pkgContext) genType(w io.Writer, obj *schema.ObjectType) {
contract.Assert(!obj.IsInputShape())
if obj.IsOverlay {
// This type is generated by the provider, so no further action is required.
return
}
pkg.genPlainType(w, pkg.tokenToType(obj.Token), obj.Comment, "", obj.Properties)
pkg.genInputTypes(w, obj.InputShape, pkg.detailsForType(obj))
@ -2130,6 +2132,10 @@ func (pkg *pkgContext) genTypeRegistrations(w io.Writer, objTypes []*schema.Obje
// Input types.
if !pkg.disableInputTypeRegistrations {
for _, obj := range objTypes {
if obj.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
name, details := pkg.tokenToType(obj.Token), pkg.detailsForType(obj)
fmt.Fprintf(w, "\tpulumi.RegisterInputType(reflect.TypeOf((*%[1]sInput)(nil)).Elem(), %[1]sArgs{})\n", name)
if details.ptrElement {
@ -2152,6 +2158,10 @@ func (pkg *pkgContext) genTypeRegistrations(w io.Writer, objTypes []*schema.Obje
// Output types.
for _, obj := range objTypes {
if obj.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
name, details := pkg.tokenToType(obj.Token), pkg.detailsForType(obj)
fmt.Fprintf(w, "\tpulumi.RegisterOutputType(%sOutput{})\n", name)
if details.ptrElement {
@ -2510,6 +2520,17 @@ func (pkg *pkgContext) genConfig(w io.Writer, variables []*schema.Property) erro
// definition and its registration to support rehydrating providers.
func (pkg *pkgContext) genResourceModule(w io.Writer) {
contract.Assert(len(pkg.resources) != 0)
allResourcesAreOverlays := true
for _, r := range pkg.resources {
if !r.IsOverlay {
allResourcesAreOverlays = false
break
}
}
if allResourcesAreOverlays {
// If all resources in this module are overlays, skip further code generation.
return
}
basePath := pkg.importBasePath
@ -2545,6 +2566,10 @@ func (pkg *pkgContext) genResourceModule(w io.Writer) {
fmt.Fprintf(w, "func (m *module) Construct(ctx *pulumi.Context, name, typ, urn string) (r pulumi.Resource, err error) {\n")
fmt.Fprintf(w, "\tswitch typ {\n")
for _, r := range pkg.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
if r.IsProvider {
contract.Assert(provider == nil)
provider = r
@ -3029,6 +3054,11 @@ func LanguageResources(tool string, pkg *schema.Package) (map[string]LanguageRes
pkg := packages[mod]
for _, r := range pkg.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
packagePath := path.Join(goPkgInfo.ImportBasePath, pkg.mod)
resources[r.Token] = LanguageResource{
Resource: r,
@ -3098,14 +3128,14 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
setFile := func(relPath, contents string) {
relPath = path.Join(pathPrefix, relPath)
if _, ok := files[relPath]; ok {
panic(errors.Errorf("duplicate file: %s", relPath))
panic(fmt.Errorf("duplicate file: %s", relPath))
}
// Run Go formatter on the code before saving to disk
formattedSource, err := format.Source([]byte(contents))
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid content:\n%s\n%s\n", relPath, contents)
panic(errors.Wrapf(err, "invalid Go source code:\n\n%s\n", relPath))
panic(fmt.Errorf("invalid Go source code:\n\n%s\n: %w", relPath, err))
}
files[relPath] = formattedSource
@ -3142,6 +3172,11 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
// Resources
for _, r := range pkg.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
importsAndAliases := map[string]string{}
pkg.getImports(r, importsAndAliases)
@ -3157,6 +3192,11 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
// Functions
for _, f := range pkg.functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
fileName := path.Join(mod, camel(tokenToName(f.Token))+".go")
code := pkg.genFunctionCodeFile(f)
setFile(fileName, code)
@ -3248,7 +3288,7 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
}
// If there are resources in this module, register the module with the runtime.
if len(pkg.resources) != 0 {
if len(pkg.resources) != 0 && !allResourcesAreOverlays(pkg.resources) {
buffer := &bytes.Buffer{}
pkg.genResourceModule(buffer)
@ -3259,6 +3299,15 @@ func GeneratePackage(tool string, pkg *schema.Package) (map[string][]byte, error
return files, nil
}
func allResourcesAreOverlays(resources []*schema.Resource) bool {
for _, r := range resources {
if !r.IsOverlay {
return false
}
}
return true
}
// goPackage returns the suggested package name for the given string.
func goPackage(name string) string {
return strings.ReplaceAll(name, "-", "")

View file

@ -2,8 +2,8 @@ package gen
import (
"bytes"
"fmt"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
@ -37,7 +37,7 @@ func CRDTypes(tool string, pkg *schema.Package) (map[string]*bytes.Buffer, error
pkg.genHeader(buffer, []string{"context", "reflect"}, importsAndAliases)
if err := pkg.genResource(buffer, r, goPkgInfo.GenerateResourceContainerTypes); err != nil {
return nil, errors.Wrapf(err, "generating resource %s", mod)
return nil, fmt.Errorf("generating resource %s: %w", mod, err)
}
}

View file

@ -9,7 +9,7 @@ import (
"sync"
"github.com/hashicorp/hcl/v2"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model/format"
@ -93,7 +93,7 @@ func GenerateProgram(program *pcl.Program) (map[string][]byte, hcl.Diagnostics,
// Run Go formatter on the code before saving to disk
formattedSource, err := gofmt.Source(index.Bytes())
if err != nil {
panic(errors.Errorf("invalid Go source code:\n\n%s", index.String()))
panic(fmt.Errorf("invalid Go source code:\n\n%s", index.String()))
}
files := map[string][]byte{
@ -287,7 +287,7 @@ func (g *generator) getVersionPath(program *pcl.Program, pkg string) (string, er
}
}
return "", errors.Errorf("could not find package version information for pkg: %s", pkg)
return "", fmt.Errorf("could not find package version information for pkg: %s", pkg)
}

View file

@ -20,7 +20,6 @@ import (
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
)
@ -84,7 +83,7 @@ func makeSafeEnumName(name, typeName string) (string, error) {
// If the name is one illegal character, return an error.
if len(safeName) == 1 && !isLegalIdentifierStart(rune(safeName[0])) {
return "", errors.Errorf("enum name %s is not a valid identifier", safeName)
return "", fmt.Errorf("enum name %s is not a valid identifier", safeName)
}
// Capitalize and make a valid identifier.

View file

@ -14,7 +14,9 @@
package format
import "fmt"
import (
"fmt"
)
// Func is a function type that implements the fmt.Formatter interface. This can be used to conveniently
// implement this interface for types defined in other packages.

View file

@ -14,7 +14,9 @@
package model
import "github.com/hashicorp/hcl/v2"
import (
"github.com/hashicorp/hcl/v2"
)
// unwrapIterableSourceType removes any eventual types that wrap a type intended for iteration.
func unwrapIterableSourceType(t Type) Type {

View file

@ -19,7 +19,7 @@ import (
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
@ -55,7 +55,7 @@ func MustNewOpaqueType(name string, annotations ...interface{}) *OpaqueType {
// NewOpaqueType creates a new opaque type with the given name.
func NewOpaqueType(name string, annotations ...interface{}) (*OpaqueType, error) {
if _, ok := opaqueTypes[name]; ok {
return nil, errors.Errorf("opaque type %s is already defined", name)
return nil, fmt.Errorf("opaque type %s is already defined", name)
}
t := &OpaqueType{Name: name, Annotations: annotations}

View file

@ -1,6 +1,8 @@
package syntax
import "github.com/hashicorp/hcl/v2/hclsyntax"
import (
"github.com/hashicorp/hcl/v2/hclsyntax"
)
// None is an HCL syntax node that can be used when a syntax node is required but none is appropriate.
var None hclsyntax.Node = &hclsyntax.Body{}

View file

@ -17,6 +17,7 @@ package test
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -26,7 +27,6 @@ import (
"sort"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
@ -442,7 +442,7 @@ func currentVersion(path string) (string, error) {
}
json, ok := data.(map[string]interface{})
if !ok {
return "", errors.Errorf("%s could not be read", path)
return "", fmt.Errorf("%s could not be read", path)
}
version, ok := json["version"]
if !ok {
@ -468,7 +468,7 @@ func replaceSchema(c chan error, path, version, url string) {
err = os.Remove(path)
if !os.IsNotExist(err) && err != nil {
c <- errors.Wrap(err, "failed to replace schema")
c <- fmt.Errorf("failed to replace schema: %w", err)
return
}
schemaFile, err := os.Create(path)

View file

@ -217,11 +217,11 @@ type SDKCodegenOptions struct {
Checks map[string]CodegenCheck
}
// `TestSDKCodegen` runs the complete set of SDK code generation tests
// TestSDKCodegen runs the complete set of SDK code generation tests
// against a particular language's code generator. It also verifies
// that the generated code is structurally sound.
//
// The tests files live in `pkg/codegen/internal/test/testdata` and
// The test files live in `pkg/codegen/internal/test/testdata` and
// are registered in `var sdkTests` in `sdk_driver.go`.
//
// An SDK code generation test files consists of a schema and a set of
@ -245,7 +245,7 @@ type SDKCodegenOptions struct {
// PULUMI_ACCEPT=true go test ./...
//
// This will rebuild subfolders such as `go/` from scratch and store
// the set of code-generated file names in `go/codegen-manfiest.json`.
// the set of code-generated file names in `go/codegen-manifest.json`.
// If these outputs look correct, they need to be checked into git and
// will then serve as the expected values for the normal test runs:
//

View file

@ -0,0 +1,87 @@
{
"version": "0.0.1",
"name": "example",
"types": {
"example::ConfigMap": {
"properties": {
"config": {
"type": "string"
}
},
"type": "object"
},
"example::ConfigMapOverlay": {
"isOverlay": true,
"properties": {
"config": {
"type": "string"
}
},
"type": "object"
}
},
"resources": {
"example::Resource": {
"properties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"inputProperties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"type": "object"
},
"example::OverlayResource": {
"isOverlay": true,
"properties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"inputProperties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"type": "object"
}
},
"functions": {
"example::Function": {
"inputs": {
"properties": {
"arg1": {
"type": "string"
}
}
},
"outputs": {
"properties": {
"result": {
"type": "string"
}
}
}
},
"example::OverlayFunction": {
"isOverlay": true,
"inputs": {
"properties": {
"arg1": {
"type": "string"
}
}
},
"outputs": {
"properties": {
"result": {
"type": "string"
}
}
}
}
}
}

View file

@ -14,6 +14,7 @@ no_edit_this_page: true
<h2 id="resources">Resources</h2>
<ul class="api">
<li><a href="otherresource" title="OtherResource"><span class="api-symbol api-symbol--resource"></span>OtherResource</a></li>
<li><a href="overlayresource" title="OverlayResource"><span class="api-symbol api-symbol--resource"></span>OverlayResource</a></li>
<li><a href="provider" title="Provider"><span class="api-symbol api-symbol--resource"></span>Provider</a></li>
<li><a href="resource" title="Resource"><span class="api-symbol api-symbol--resource"></span>Resource</a></li>
<li><a href="typeuses" title="TypeUses"><span class="api-symbol api-symbol--resource"></span>TypeUses</a></li>
@ -22,6 +23,7 @@ no_edit_this_page: true
<h2 id="functions">Functions</h2>
<ul class="api">
<li><a href="argfunction" title="ArgFunction"><span class="api-symbol api-symbol--function"></span>ArgFunction</a></li>
<li><a href="overlayfunction" title="OverlayFunction"><span class="api-symbol api-symbol--function"></span>OverlayFunction</a></li>
</ul>
<h2 id="package-details">Package Details</h2>

View file

@ -3,6 +3,8 @@
"_index.md",
"argfunction/_index.md",
"otherresource/_index.md",
"overlayfunction/_index.md",
"overlayresource/_index.md",
"provider/_index.md",
"resource/_index.md",
"typeuses/_index.md"

View file

@ -0,0 +1,190 @@
---
title: "overlayFunction"
title_tag: "example.overlayFunction"
meta_desc: "Documentation for the example.overlayFunction function with examples, input properties, output properties, and supporting types."
layout: api
no_edit_this_page: true
---
<!-- WARNING: this file was generated by test. -->
<!-- Do not edit by hand unless you're certain you know what you are doing! -->
## Using overlayFunction {#using}
Two invocation forms are available. The direct form accepts plain
arguments and either blocks until the result value is available, or
returns a Promise-wrapped result. The output form accepts
Input-wrapped arguments and returns an Output-wrapped result.
{{< chooser language "typescript,python,go,csharp" / >}}
{{% choosable language nodejs %}}
<div class="highlight"
><pre class="chroma"><code class="language-typescript" data-lang="typescript"
><span class="k">function </span>overlayFunction<span class="p">(</span><span class="nx">args</span><span class="p">:</span> <span class="nx">OverlayFunctionArgs</span><span class="p">,</span> <span class="nx">opts</span><span class="p">?:</span> <span class="nx"><a href="/docs/reference/pkg/nodejs/pulumi/pulumi/#InvokeOptions">InvokeOptions</a></span><span class="p">): Promise&lt;<span class="nx"><a href="#result">OverlayFunctionResult</a></span>></span
><span class="k">
function </span>overlayFunctionOutput<span class="p">(</span><span class="nx">args</span><span class="p">:</span> <span class="nx">OverlayFunctionOutputArgs</span><span class="p">,</span> <span class="nx">opts</span><span class="p">?:</span> <span class="nx"><a href="/docs/reference/pkg/nodejs/pulumi/pulumi/#InvokeOptions">InvokeOptions</a></span><span class="p">): Output&lt;<span class="nx"><a href="#result">OverlayFunctionResult</a></span>></span
></code></pre></div>
{{% /choosable %}}
{{% choosable language python %}}
<div class="highlight"><pre class="chroma"><code class="language-python" data-lang="python"
><span class="k">def </span>overlay_function<span class="p">(</span><span class="nx">arg1</span><span class="p">:</span> <span class="nx">Optional[Resource]</span> = None<span class="p">,</span>
<span class="nx">opts</span><span class="p">:</span> <span class="nx"><a href="/docs/reference/pkg/python/pulumi/#pulumi.InvokeOptions">Optional[InvokeOptions]</a></span> = None<span class="p">) -&gt;</span> <span>OverlayFunctionResult</span
><span class="k">
def </span>overlay_function_output<span class="p">(</span><span class="nx">arg1</span><span class="p">:</span> <span class="nx">Optional[pulumi.Input[Resource]]</span> = None<span class="p">,</span>
<span class="nx">opts</span><span class="p">:</span> <span class="nx"><a href="/docs/reference/pkg/python/pulumi/#pulumi.InvokeOptions">Optional[InvokeOptions]</a></span> = None<span class="p">) -&gt;</span> <span>Output[OverlayFunctionResult]</span
></code></pre></div>
{{% /choosable %}}
{{% choosable language go %}}
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"
><span class="k">func </span>OverlayFunction<span class="p">(</span><span class="nx">ctx</span><span class="p"> *</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#Context">Context</a></span><span class="p">,</span> <span class="nx">args</span><span class="p"> *</span><span class="nx">OverlayFunctionArgs</span><span class="p">,</span> <span class="nx">opts</span><span class="p"> ...</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#InvokeOption">InvokeOption</a></span><span class="p">) (*<span class="nx"><a href="#result">OverlayFunctionResult</a></span>, error)</span
><span class="k">
func </span>OverlayFunctionOutput<span class="p">(</span><span class="nx">ctx</span><span class="p"> *</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#Context">Context</a></span><span class="p">,</span> <span class="nx">args</span><span class="p"> *</span><span class="nx">OverlayFunctionOutputArgs</span><span class="p">,</span> <span class="nx">opts</span><span class="p"> ...</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#InvokeOption">InvokeOption</a></span><span class="p">) OverlayFunctionResultOutput</span
></code></pre></div>
&gt; Note: This function is named `OverlayFunction` in the Go SDK.
{{% /choosable %}}
{{% choosable language csharp %}}
<div class="highlight"><pre class="chroma"><code class="language-csharp" data-lang="csharp"><span class="k">public static class </span><span class="nx">OverlayFunction </span><span class="p">
{</span><span class="k">
public static </span>Task&lt;<span class="nx"><a href="#result">OverlayFunctionResult</a></span>> <span class="p">InvokeAsync(</span><span class="nx">OverlayFunctionArgs</span><span class="p"> </span><span class="nx">args<span class="p">,</span> <span class="nx"><a href="/docs/reference/pkg/dotnet/Pulumi/Pulumi.InvokeOptions.html">InvokeOptions</a></span><span class="p">? </span><span class="nx">opts = null<span class="p">)</span><span class="k">
public static </span>Output&lt;<span class="nx"><a href="#result">OverlayFunctionResult</a></span>> <span class="p">Invoke(</span><span class="nx">OverlayFunctionInvokeArgs</span><span class="p"> </span><span class="nx">args<span class="p">,</span> <span class="nx"><a href="/docs/reference/pkg/dotnet/Pulumi/Pulumi.InvokeOptions.html">InvokeOptions</a></span><span class="p">? </span><span class="nx">opts = null<span class="p">)</span><span class="p">
}</span></code></pre></div>
{{% /choosable %}}
The following arguments are supported:
{{% choosable language csharp %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="arg1_csharp">
<a href="#arg1_csharp" style="color: inherit; text-decoration: inherit;">Arg1</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Pulumi.<wbr>Example.<wbr>Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="arg1_go">
<a href="#arg1_go" style="color: inherit; text-decoration: inherit;">Arg1</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="arg1_nodejs">
<a href="#arg1_nodejs" style="color: inherit; text-decoration: inherit;">arg1</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="arg1_python">
<a href="#arg1_python" style="color: inherit; text-decoration: inherit;">arg1</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
## overlayFunction Result {#result}
The following output properties are available:
{{% choosable language csharp %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="result_csharp">
<a href="#result_csharp" style="color: inherit; text-decoration: inherit;">Result</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Pulumi.<wbr>Example.<wbr>Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="result_go">
<a href="#result_go" style="color: inherit; text-decoration: inherit;">Result</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="result_nodejs">
<a href="#result_nodejs" style="color: inherit; text-decoration: inherit;">result</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="result_python">
<a href="#result_python" style="color: inherit; text-decoration: inherit;">result</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">Resource</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
<h2 id="package-details">Package Details</h2>
<dl class="package-details">
<dt>Repository</dt>
<dd><a href=""></a></dd>
<dt>License</dt>
<dd></dd>
</dl>

View file

@ -0,0 +1,328 @@
---
title: "OverlayResource"
title_tag: "example.OverlayResource"
meta_desc: "Documentation for the example.OverlayResource resource with examples, input properties, output properties, lookup functions, and supporting types."
layout: api
no_edit_this_page: true
---
<!-- WARNING: this file was generated by test. -->
<!-- Do not edit by hand unless you're certain you know what you are doing! -->
## Create a OverlayResource Resource {#create}
{{< chooser language "typescript,python,go,csharp" / >}}
{{% choosable language nodejs %}}
<div class="highlight"><pre class="chroma"><code class="language-typescript" data-lang="typescript"><span class="k">new </span><span class="nx">OverlayResource</span><span class="p">(</span><span class="nx">name</span><span class="p">:</span> <span class="nx">string</span><span class="p">,</span> <span class="nx">args</span><span class="p">?:</span> <span class="nx"><a href="#inputs">OverlayResourceArgs</a></span><span class="p">,</span> <span class="nx">opts</span><span class="p">?:</span> <span class="nx"><a href="/docs/reference/pkg/nodejs/pulumi/pulumi/#CustomResourceOptions">CustomResourceOptions</a></span><span class="p">);</span></code></pre></div>
{{% /choosable %}}
{{% choosable language python %}}
<div class="highlight"><pre class="chroma"><code class="language-python" data-lang="python"><span class=nd>@overload</span>
<span class="k">def </span><span class="nx">OverlayResource</span><span class="p">(</span><span class="nx">resource_name</span><span class="p">:</span> <span class="nx">str</span><span class="p">,</span>
<span class="nx">opts</span><span class="p">:</span> <span class="nx"><a href="/docs/reference/pkg/python/pulumi/#pulumi.ResourceOptions">Optional[ResourceOptions]</a></span> = None<span class="p">,</span>
<span class="nx">foo</span><span class="p">:</span> <span class="nx">Optional[ConfigMapOverlayArgs]</span> = None<span class="p">)</span>
<span class=nd>@overload</span>
<span class="k">def </span><span class="nx">OverlayResource</span><span class="p">(</span><span class="nx">resource_name</span><span class="p">:</span> <span class="nx">str</span><span class="p">,</span>
<span class="nx">args</span><span class="p">:</span> <span class="nx"><a href="#inputs">Optional[OverlayResourceArgs]</a></span> = None<span class="p">,</span>
<span class="nx">opts</span><span class="p">:</span> <span class="nx"><a href="/docs/reference/pkg/python/pulumi/#pulumi.ResourceOptions">Optional[ResourceOptions]</a></span> = None<span class="p">)</span></code></pre></div>
{{% /choosable %}}
{{% choosable language go %}}
<div class="highlight"><pre class="chroma"><code class="language-go" data-lang="go"><span class="k">func </span><span class="nx">NewOverlayResource</span><span class="p">(</span><span class="nx">ctx</span><span class="p"> *</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#Context">Context</a></span><span class="p">,</span> <span class="nx">name</span><span class="p"> </span><span class="nx">string</span><span class="p">,</span> <span class="nx">args</span><span class="p"> *</span><span class="nx"><a href="#inputs">OverlayResourceArgs</a></span><span class="p">,</span> <span class="nx">opts</span><span class="p"> ...</span><span class="nx"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#ResourceOption">ResourceOption</a></span><span class="p">) (*<span class="nx">OverlayResource</span>, error)</span></code></pre></div>
{{% /choosable %}}
{{% choosable language csharp %}}
<div class="highlight"><pre class="chroma"><code class="language-csharp" data-lang="csharp"><span class="k">public </span><span class="nx">OverlayResource</span><span class="p">(</span><span class="nx">string</span><span class="p"> </span><span class="nx">name<span class="p">,</span> <span class="nx"><a href="#inputs">OverlayResourceArgs</a></span><span class="p">? </span><span class="nx">args = null<span class="p">,</span> <span class="nx"><a href="/docs/reference/pkg/dotnet/Pulumi/Pulumi.CustomResourceOptions.html">CustomResourceOptions</a></span><span class="p">? </span><span class="nx">opts = null<span class="p">)</span></code></pre></div>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt
class="property-required" title="Required">
<span>name</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>The unique name of the resource.</dd><dt
class="property-optional" title="Optional">
<span>args</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#inputs">OverlayResourceArgs</a></span>
</dt>
<dd>The arguments to resource properties.</dd><dt
class="property-optional" title="Optional">
<span>opts</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="/docs/reference/pkg/nodejs/pulumi/pulumi/#CustomResourceOptions">CustomResourceOptions</a></span>
</dt>
<dd>Bag of options to control resource&#39;s behavior.</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt
class="property-required" title="Required">
<span>resource_name</span>
<span class="property-indicator"></span>
<span class="property-type">str</span>
</dt>
<dd>The unique name of the resource.</dd><dt
class="property-optional" title="Optional">
<span>args</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#inputs">OverlayResourceArgs</a></span>
</dt>
<dd>The arguments to resource properties.</dd><dt
class="property-optional" title="Optional">
<span>opts</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="/docs/reference/pkg/python/pulumi/#pulumi.ResourceOptions">ResourceOptions</a></span>
</dt>
<dd>Bag of options to control resource&#39;s behavior.</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt
class="property-optional" title="Optional">
<span>ctx</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#Context">Context</a></span>
</dt>
<dd>Context object for the current deployment.</dd><dt
class="property-required" title="Required">
<span>name</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>The unique name of the resource.</dd><dt
class="property-optional" title="Optional">
<span>args</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#inputs">OverlayResourceArgs</a></span>
</dt>
<dd>The arguments to resource properties.</dd><dt
class="property-optional" title="Optional">
<span>opts</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="https://pkg.go.dev/github.com/pulumi/pulumi/sdk/v3/go/pulumi?tab=doc#ResourceOption">ResourceOption</a></span>
</dt>
<dd>Bag of options to control resource&#39;s behavior.</dd></dl>
{{% /choosable %}}
{{% choosable language csharp %}}
<dl class="resources-properties"><dt
class="property-required" title="Required">
<span>name</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>The unique name of the resource.</dd><dt
class="property-optional" title="Optional">
<span>args</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#inputs">OverlayResourceArgs</a></span>
</dt>
<dd>The arguments to resource properties.</dd><dt
class="property-optional" title="Optional">
<span>opts</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="/docs/reference/pkg/dotnet/Pulumi/Pulumi.CustomResourceOptions.html">CustomResourceOptions</a></span>
</dt>
<dd>Bag of options to control resource&#39;s behavior.</dd></dl>
{{% /choosable %}}
## OverlayResource Resource Properties {#properties}
To learn more about resource properties and how to use them, see [Inputs and Outputs]({{< relref "/docs/intro/concepts/inputs-outputs" >}}) in the Architecture and Concepts docs.
### Inputs
The OverlayResource resource accepts the following [input]({{< relref "/docs/intro/concepts/inputs-outputs" >}}) properties:
{{% choosable language csharp %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="foo_csharp">
<a href="#foo_csharp" style="color: inherit; text-decoration: inherit;">Foo</a>
</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#configmapoverlay">Config<wbr>Map<wbr>Overlay<wbr>Args</a></span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="foo_go">
<a href="#foo_go" style="color: inherit; text-decoration: inherit;">Foo</a>
</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#configmapoverlay">Config<wbr>Map<wbr>Overlay<wbr>Args</a></span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="foo_nodejs">
<a href="#foo_nodejs" style="color: inherit; text-decoration: inherit;">foo</a>
</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#configmapoverlay">Config<wbr>Map<wbr>Overlay<wbr>Args</a></span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="foo_python">
<a href="#foo_python" style="color: inherit; text-decoration: inherit;">foo</a>
</span>
<span class="property-indicator"></span>
<span class="property-type"><a href="#configmapoverlay">Config<wbr>Map<wbr>Overlay<wbr>Args</a></span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
### Outputs
All [input](#inputs) properties are implicitly available as output properties. Additionally, the OverlayResource resource produces the following output properties:
{{% choosable language csharp %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="id_csharp">
<a href="#id_csharp" style="color: inherit; text-decoration: inherit;">Id</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}The provider-assigned unique ID for this managed resource.{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="id_go">
<a href="#id_go" style="color: inherit; text-decoration: inherit;">Id</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}The provider-assigned unique ID for this managed resource.{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="id_nodejs">
<a href="#id_nodejs" style="color: inherit; text-decoration: inherit;">id</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}The provider-assigned unique ID for this managed resource.{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt class="property-"
title="">
<span id="id_python">
<a href="#id_python" style="color: inherit; text-decoration: inherit;">id</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">str</span>
</dt>
<dd>{{% md %}}The provider-assigned unique ID for this managed resource.{{% /md %}}</dd></dl>
{{% /choosable %}}
## Supporting Types
<h4 id="configmapoverlay">Config<wbr>Map<wbr>Overlay</h4>
{{% choosable language csharp %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="config_csharp">
<a href="#config_csharp" style="color: inherit; text-decoration: inherit;">Config</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language go %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="config_go">
<a href="#config_go" style="color: inherit; text-decoration: inherit;">Config</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language nodejs %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="config_nodejs">
<a href="#config_nodejs" style="color: inherit; text-decoration: inherit;">config</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">string</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
{{% choosable language python %}}
<dl class="resources-properties"><dt class="property-optional"
title="Optional">
<span id="config_python">
<a href="#config_python" style="color: inherit; text-decoration: inherit;">config</a>
</span>
<span class="property-indicator"></span>
<span class="property-type">str</span>
</dt>
<dd>{{% md %}}{{% /md %}}</dd></dl>
{{% /choosable %}}
<h2 id="package-details">Package Details</h2>
<dl class="package-details">
<dt>Repository</dt>
<dd><a href=""></a></dd>
<dt>License</dt>
<dd></dd>
</dl>

View file

@ -66,6 +66,15 @@
},
"type": "object"
},
"example::ConfigMapOverlay": {
"isOverlay": true,
"properties": {
"config": {
"type": "string"
}
},
"type": "object"
},
"example::ObjectWithNodeOptionalInputs": {
"properties": {
"foo": {
@ -114,6 +123,20 @@
},
"type": "object"
},
"example::OverlayResource": {
"isOverlay": true,
"properties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"inputProperties": {
"foo": {
"$ref": "#/types/example::ConfigMapOverlay"
}
},
"type": "object"
},
"example::TypeUses": {
"properties": {
"foo": {
@ -156,6 +179,23 @@
}
}
}
},
"example::overlayFunction": {
"isOverlay": true,
"inputs": {
"properties": {
"arg1": {
"$ref": "#/resources/example::Resource"
}
}
},
"outputs": {
"properties": {
"result": {
"$ref": "#/resources/example::Resource"
}
}
}
}
},
"language": {

View file

@ -21,6 +21,7 @@ package nodejs
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"path"
@ -31,8 +32,6 @@ import (
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/internal/tstypes"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
@ -443,7 +442,7 @@ func tsPrimitiveValue(value interface{}) (string, error) {
case reflect.String:
return fmt.Sprintf("%q", v.String()), nil
default:
return "", errors.Errorf("unsupported default value of type %T", value)
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
@ -1404,6 +1403,11 @@ func (mod *modContext) sdkImports(nested, utilities bool) []string {
func (mod *modContext) genTypes() (string, string) {
externalImports, imports := codegen.NewStringSet(), map[string]codegen.StringSet{}
for _, t := range mod.types {
if t.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
mod.getImports(t, externalImports, imports)
}
@ -1454,6 +1458,11 @@ func (mod *modContext) getNamespaces() map[string]*namespace {
}
for _, t := range mod.types {
if t.IsOverlay {
// This type is generated by the provider, so no further action is required.
continue
}
modName := mod.pkg.TokenToModule(t.Token)
if override, ok := mod.modToPkg[modName]; ok {
modName = override
@ -1599,6 +1608,11 @@ func (mod *modContext) gen(fs fs) error {
// Resources
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
externalImports, imports := codegen.NewStringSet(), map[string]codegen.StringSet{}
referencesNestedTypes := mod.getImportsForResource(r, externalImports, imports, r)
@ -1615,6 +1629,11 @@ func (mod *modContext) gen(fs fs) error {
// Functions
for _, f := range mod.functions {
if f.IsOverlay {
// This function code is generated by the provider, so no further action is required.
continue
}
externalImports, imports := codegen.NewStringSet(), map[string]codegen.StringSet{}
referencesNestedTypes := mod.getImports(f, externalImports, imports)
@ -1770,6 +1789,11 @@ func (mod *modContext) genResourceModule(w io.Writer) {
} else {
registrations, first := codegen.StringSet{}, true
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
if r.IsProvider {
contract.Assert(provider == nil)
provider = r
@ -1792,6 +1816,11 @@ func (mod *modContext) genResourceModule(w io.Writer) {
fmt.Fprintf(w, " switch (type) {\n")
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
if r.IsProvider {
continue
}
@ -2107,6 +2136,11 @@ func generateModuleContextMap(tool string, pkg *schema.Package, extraFiles map[s
})
scanResource := func(r *schema.Resource) {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
return
}
mod := getModFromToken(r.Token)
mod.resources = append(mod.resources, r)
visitObjectTypes(r.Properties, func(t *schema.ObjectType) {
@ -2225,6 +2259,11 @@ func LanguageResources(pkg *schema.Package) (map[string]LanguageResource, error)
for modName, mod := range modules {
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
packagePath := strings.Replace(modName, "/", ".", -1)
lr := LanguageResource{
Resource: r,

View file

@ -14,7 +14,9 @@
package nodejs
import "github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
import (
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
)
const (
// intrinsicAwait is the name of the await intrinsic.

View file

@ -15,12 +15,12 @@
package nodejs
import (
"fmt"
"io"
"regexp"
"strings"
"unicode"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
)
@ -109,7 +109,7 @@ func makeSafeEnumName(name, typeName string) (string, error) {
// If the name is one illegal character, return an error.
if len(safeName) == 1 && !isLegalIdentifierStart(rune(safeName[0])) {
return "", errors.Errorf("enum name %s is not a valid identifier", safeName)
return "", fmt.Errorf("enum name %s is not a valid identifier", safeName)
}
// Capitalize and make a valid identifier.

View file

@ -1,7 +1,9 @@
// nolint: lll
package nodejs
import "testing"
import (
"testing"
)
func TestMakeSafeEnumName(t *testing.T) {
tests := []struct {

View file

@ -32,7 +32,6 @@ import (
"unicode"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
@ -472,6 +471,11 @@ func (mod *modContext) gen(fs fs) error {
// 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
@ -490,6 +494,11 @@ func (mod *modContext) gen(fs fs) error {
// 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
@ -523,6 +532,9 @@ func (mod *modContext) gen(fs fs) error {
}
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
@ -875,12 +887,31 @@ func (mod *modContext) genConfigStubs(variables []*schema.Property) (string, err
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 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) {
@ -909,6 +940,11 @@ func (mod *modContext) genTypes(dir string, fs fs) error {
// Export only the symbols we want exported.
fmt.Fprintf(w, "__all__ = [\n")
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 || !input && mod.details(t).outputType {
fmt.Fprintf(w, " '%s',\n", mod.unqualifiedObjectTypeName(t, input))
}
@ -917,6 +953,11 @@ func (mod *modContext) genTypes(dir string, fs fs) error {
var hasTypes bool
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 {
if err := mod.genObjectType(w, t, true); err != nil {
return err
@ -1062,8 +1103,7 @@ func (mod *modContext) genResource(res *schema.Resource) (string, error) {
for _, t := range mod.types {
if mod.details(t).inputType {
if mod.unqualifiedObjectTypeName(t, true) == resourceArgsName {
return "", errors.Errorf(
"resource args class named %s in %s conflicts with input type", resourceArgsName, mod.mod)
return "", fmt.Errorf("resource args class named %s in %s conflicts with input type", resourceArgsName, mod.mod)
}
}
}
@ -1841,7 +1881,7 @@ func (mod *modContext) genEnum(w io.Writer, enum *schema.EnumType) error {
}
}
default:
return errors.Errorf("enums of type %s are not yet implemented for this language", enum.ElementType.String())
return fmt.Errorf("enums of type %s are not yet implemented for this language", enum.ElementType.String())
}
return nil
@ -2012,15 +2052,15 @@ func genPackageMetadata(
// We expect a specific pattern of ">=version,<version" here.
matches := requirementRegex.FindStringSubmatch(pulumiReq)
if len(matches) != 2 {
return "", errors.Errorf("invalid requirement specifier \"%s\"; expected \">=version1,<version2\"", pulumiReq)
return "", fmt.Errorf("invalid requirement specifier \"%s\"; expected \">=version1,<version2\"", pulumiReq)
}
lowerBound, err := pep440VersionToSemver(matches[1])
if err != nil {
return "", errors.Errorf("invalid version for lower bound: %v", err)
return "", fmt.Errorf("invalid version for lower bound: %v", err)
}
if lowerBound.LT(oldestAllowedPulumi) {
return "", errors.Errorf("lower version bound must be at least %v", oldestAllowedPulumi)
return "", fmt.Errorf("lower version bound must be at least %v", oldestAllowedPulumi)
}
} else {
if requires == nil {
@ -2502,7 +2542,7 @@ func getPrimitiveValue(value interface{}) (string, error) {
case reflect.String:
return fmt.Sprintf("'%s'", v.String()), nil
default:
return "", errors.Errorf("unsupported default value of type %T", value)
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
@ -2735,6 +2775,11 @@ func LanguageResources(tool string, pkg *schema.Package) (map[string]LanguageRes
continue
}
for _, r := range mod.resources {
if r.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
packagePath := strings.Replace(modName, "/", ".", -1)
lr := LanguageResource{
Resource: r,

View file

@ -103,6 +103,11 @@ func collectResourceModuleInfos(mctx *modContext) []resourceModuleInfo {
byMod := make(map[string]resourceModuleInfo)
for _, res := range mctx.resources {
if res.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
if !res.IsProvider {
pkg := mctx.pkg.Name
mod := mctx.pkg.TokenToRuntimeModule(res.Token)
@ -158,6 +163,11 @@ func allResourcePackageInfos(root *modContext) []resourcePackageInfo {
func collectResourcePackageInfos(mctx *modContext) []resourcePackageInfo {
var out []resourcePackageInfo
for _, res := range mctx.resources {
if res.IsOverlay {
// This resource code is generated by the provider, so no further action is required.
continue
}
if res.IsProvider {
pkg := mctx.pkg.Name
token := res.Token

View file

@ -1,12 +1,13 @@
package python
import (
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"fmt"
"io"
"regexp"
"strings"
"unicode"
"github.com/pulumi/pulumi/pkg/v3/codegen"
)
// isLegalIdentifierStart returns true if it is legal for c to be the first character of a Python identifier as per
@ -66,7 +67,7 @@ func makeSafeEnumName(name, typeName string) (string, error) {
// If the name is one illegal character, return an error.
if len(safeName) == 1 && !isLegalIdentifierStart(rune(safeName[0])) {
return "", errors.Errorf("enum name %s is not a valid identifier", safeName)
return "", fmt.Errorf("enum name %s is not a valid identifier", safeName)
}
// If it's camelCase, change it to snake_case.

View file

@ -10,7 +10,7 @@ import (
"github.com/blang/semver"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"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/workspace"
@ -110,15 +110,15 @@ func (l *pluginLoader) ensurePlugin(pkg string, version *semver.Version) error {
if !workspace.HasPlugin(pkgPlugin) {
tarball, err := downloadToFileWithRetry()
if err != nil {
return errors.Wrapf(err, "failed to download plugin: %s", pkgPlugin)
return fmt.Errorf("failed to download plugin: %s: %w", pkgPlugin, err)
}
defer os.Remove(tarball)
reader, err := os.Open(tarball)
if err != nil {
return errors.Wrapf(err, "failed to open downloaded plugin: %s", pkgPlugin)
return fmt.Errorf("failed to open downloaded plugin: %s: %w", pkgPlugin, err)
}
if err := pkgPlugin.Install(reader); err != nil {
return errors.Wrapf(err, "failed to install plugin %s", pkgPlugin)
return fmt.Errorf("failed to install plugin %s: %w", pkgPlugin, err)
}
}

View file

@ -30,7 +30,7 @@ import (
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"github.com/pkg/errors"
"github.com/santhosh-tekuri/jsonschema/v5"
"gopkg.in/yaml.v3"
@ -228,6 +228,9 @@ type ObjectType struct {
Properties []*Property
// Language specifies additional language-specific data about the object type.
Language map[string]interface{}
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
// InputShape is the input shape for this object. Only valid if IsPlainShape returns true.
InputShape *ObjectType
@ -398,6 +401,9 @@ type Resource struct {
IsComponent bool
// Methods is the list of methods for the resource.
Methods []*Method
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
}
// The set of resource paths where ReplaceOnChanges is true.
@ -434,7 +440,7 @@ func (r *Resource) ReplaceOnChanges() (changes [][]*Property, err []error) {
}
}
for i, e := range err {
err[i] = errors.Wrapf(e, "Failed to genereate full `ReplaceOnChanges`")
err[i] = fmt.Errorf("Failed to genereate full `ReplaceOnChanges`: %w", e)
}
return changes, err
}
@ -461,7 +467,7 @@ func replaceOnChangesType(t Type, stack *map[string]struct{}) ([][]*Property, []
delete(*stack, p.Type.String())
} else {
err = append(err, errors.Errorf("Found recursive object %q", p.Name))
err = append(err, fmt.Errorf("Found recursive object %q", p.Name))
}
}
// We don't want to emit errors where replaceOnChanges is not used.
@ -533,6 +539,9 @@ type Function struct {
Language map[string]interface{}
// IsMethod indicates whether the function is a method of a resource.
IsMethod bool
// IsOverlay indicates whether the function is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool
}
// Package describes a Pulumi package.
@ -623,7 +632,7 @@ func importDefaultLanguages(def *DefaultValue, languages map[string]Language) er
if lang, ok := languages[name]; ok {
val, err := lang.ImportDefaultSpec(def, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
def.Language[name] = val
}
@ -635,7 +644,7 @@ func importDefaultLanguages(def *DefaultValue, languages map[string]Language) er
func importPropertyLanguages(property *Property, languages map[string]Language) error {
if property.DefaultValue != nil {
if err := importDefaultLanguages(property.DefaultValue, languages); err != nil {
return errors.Wrapf(err, "importing default value")
return fmt.Errorf("importing default value: %w", err)
}
}
@ -645,7 +654,7 @@ func importPropertyLanguages(property *Property, languages map[string]Language)
if lang, ok := languages[name]; ok {
val, err := lang.ImportPropertySpec(property, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
property.Language[name] = val
}
@ -657,7 +666,7 @@ func importPropertyLanguages(property *Property, languages map[string]Language)
func importObjectTypeLanguages(object *ObjectType, languages map[string]Language) error {
for _, property := range object.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return errors.Wrapf(err, "importing property %v", property.Name)
return fmt.Errorf("importing property %v: %w", property.Name, err)
}
}
@ -667,7 +676,7 @@ func importObjectTypeLanguages(object *ObjectType, languages map[string]Language
if lang, ok := languages[name]; ok {
val, err := lang.ImportObjectTypeSpec(object, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
object.Language[name] = val
}
@ -679,20 +688,20 @@ func importObjectTypeLanguages(object *ObjectType, languages map[string]Language
func importResourceLanguages(resource *Resource, languages map[string]Language) error {
for _, property := range resource.InputProperties {
if err := importPropertyLanguages(property, languages); err != nil {
return errors.Wrapf(err, "importing input property %v", property.Name)
return fmt.Errorf("importing input property %v: %w", property.Name, err)
}
}
for _, property := range resource.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return errors.Wrapf(err, "importing property %v", property.Name)
return fmt.Errorf("importing property %v: %w", property.Name, err)
}
}
if resource.StateInputs != nil {
for _, property := range resource.StateInputs.Properties {
if err := importPropertyLanguages(property, languages); err != nil {
return errors.Wrapf(err, "importing state input property %v", property.Name)
return fmt.Errorf("importing state input property %v: %w", property.Name, err)
}
}
}
@ -703,7 +712,7 @@ func importResourceLanguages(resource *Resource, languages map[string]Language)
if lang, ok := languages[name]; ok {
val, err := lang.ImportResourceSpec(resource, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
resource.Language[name] = val
}
@ -715,12 +724,12 @@ func importResourceLanguages(resource *Resource, languages map[string]Language)
func importFunctionLanguages(function *Function, languages map[string]Language) error {
if function.Inputs != nil {
if err := importObjectTypeLanguages(function.Inputs, languages); err != nil {
return errors.Wrapf(err, "importing inputs")
return fmt.Errorf("importing inputs: %w", err)
}
}
if function.Outputs != nil {
if err := importObjectTypeLanguages(function.Outputs, languages); err != nil {
return errors.Wrapf(err, "importing outputs")
return fmt.Errorf("importing outputs: %w", err)
}
}
@ -730,7 +739,7 @@ func importFunctionLanguages(function *Function, languages map[string]Language)
if lang, ok := languages[name]; ok {
val, err := lang.ImportFunctionSpec(function, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
function.Language[name] = val
}
@ -758,32 +767,32 @@ func (pkg *Package) ImportLanguages(languages map[string]Language) error {
for _, t := range pkg.Types {
if object, ok := t.(*ObjectType); ok {
if err := importObjectTypeLanguages(object, languages); err != nil {
return errors.Wrapf(err, "importing object type %v", object.Token)
return fmt.Errorf("importing object type %v: %w", object.Token, err)
}
}
}
for _, config := range pkg.Config {
if err := importPropertyLanguages(config, languages); err != nil {
return errors.Wrapf(err, "importing configuration property %v", config.Name)
return fmt.Errorf("importing configuration property %v: %w", config.Name, err)
}
}
if pkg.Provider != nil {
if err := importResourceLanguages(pkg.Provider, languages); err != nil {
return errors.Wrapf(err, "importing provider")
return fmt.Errorf("importing provider: %w", err)
}
}
for _, resource := range pkg.Resources {
if err := importResourceLanguages(resource, languages); err != nil {
return errors.Wrapf(err, "importing resource %v", resource.Token)
return fmt.Errorf("importing resource %v: %w", resource.Token, err)
}
}
for _, function := range pkg.Functions {
if err := importFunctionLanguages(function, languages); err != nil {
return errors.Wrapf(err, "importing function %v", function.Token)
return fmt.Errorf("importing function %v: %w", function.Token, err)
}
}
@ -793,7 +802,7 @@ func (pkg *Package) ImportLanguages(languages map[string]Language) error {
if lang, ok := languages[name]; ok {
val, err := lang.ImportPackageSpec(pkg, raw)
if err != nil {
return errors.Wrapf(err, "importing %v metadata", name)
return fmt.Errorf("importing %v metadata: %w", name, err)
}
pkg.Language[name] = val
}
@ -1011,6 +1020,7 @@ func (pkg *Package) marshalResource(r *Resource) (ResourceSpec, error) {
if err != nil {
return ResourceSpec{}, fmt.Errorf("marshaling properties: %w", err)
}
object.IsOverlay = r.IsOverlay
requiredInputs, inputs, err := pkg.marshalProperties(r.InputProperties, false)
if err != nil {
@ -1381,6 +1391,9 @@ type ObjectTypeSpec struct {
Plain []string `json:"plain,omitempty" yaml:"plain,omitempty"`
// Language specifies additional language-specific data about the type.
Language map[string]RawMessage `json:"language,omitempty" yaml:"language,omitempty"`
// IsOverlay indicates whether the type is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool `json:"isOverlay,omitempty" yaml:"isOverlay,omitempty"`
}
// ComplexTypeSpec is the serializable form of an object or enum type.
@ -1449,6 +1462,9 @@ type FunctionSpec struct {
DeprecationMessage string `json:"deprecationMessage,omitempty" yaml:"deprecationMessage,omitempty"`
// Language specifies additional language-specific data about the function.
Language map[string]RawMessage `json:"language,omitempty" yaml:"language,omitempty"`
// IsOverlay indicates whether the function is an overlay provided by the package. Overlay code is generated by the
// package rather than using the core Pulumi codegen libraries.
IsOverlay bool `json:"isOverlay,omitempty" yaml:"isOverlay,omitempty"`
}
// ConfigSpec is the serializable description of a package's configuration variables.
@ -2332,6 +2348,7 @@ func (t *types) bindObjectTypeDetails(path string, obj *ObjectType, token string
obj.Language = language
obj.Properties = properties
obj.properties = propertyMap
obj.IsOverlay = spec.IsOverlay
obj.InputShape.Package = t.pkg
obj.InputShape.Token = token
@ -2346,6 +2363,7 @@ func (t *types) bindObjectTypeDetails(path string, obj *ObjectType, token string
func (t *types) bindObjectType(path, token string, spec ObjectTypeSpec) (*ObjectType, hcl.Diagnostics, error) {
obj := &ObjectType{}
obj.InputShape = &ObjectType{PlainShape: obj}
obj.IsOverlay = spec.IsOverlay
diags, err := t.bindObjectTypeDetails(path, obj, token, spec)
if err != nil {
@ -2448,7 +2466,7 @@ func bindTypes(pkg *Package, complexTypes map[string]ComplexTypeSpec, loader Loa
// object type is its token. While this doesn't affect object types directly, it breaks the interning of types
// that reference object types (e.g. arrays, maps, unions)
typ := &ObjectType{Token: token}
typ.InputShape = &ObjectType{Token: token, PlainShape: typ}
typ.InputShape = &ObjectType{Token: token, PlainShape: typ, IsOverlay: spec.IsOverlay}
typs.objects[token] = typ
typs.named[token] = typ
} else if len(spec.Enum) > 0 {
@ -2602,6 +2620,7 @@ func bindResource(path, token string, spec ResourceSpec, types *types,
Language: language,
IsComponent: spec.IsComponent,
Methods: methods,
IsOverlay: spec.IsOverlay,
}, diags, nil
}
@ -2717,6 +2736,7 @@ func bindFunction(token string, spec FunctionSpec, types *types) (*Function, hcl
Outputs: outputs,
DeprecationMessage: spec.DeprecationMessage,
Language: language,
IsOverlay: spec.IsOverlay,
}, diags, nil
}

View file

@ -22,6 +22,7 @@ import (
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"github.com/blang/semver"
@ -412,6 +413,43 @@ func TestMethods(t *testing.T) {
}
}
// TestIsOverlay tests that the IsOverlay field is set correctly for resources, types, and functions. Does not test
// codegen.
func TestIsOverlay(t *testing.T) {
t.Run("overlay", func(t *testing.T) {
pkgSpec := readSchemaFile(filepath.Join("schema", "overlay.json"))
pkg, err := ImportSpec(pkgSpec, nil)
if err != nil {
t.Error(err)
}
for _, v := range pkg.Resources {
if strings.Contains(v.Token, "Overlay") {
assert.Truef(t, v.IsOverlay, "resource %q", v.Token)
} else {
assert.Falsef(t, v.IsOverlay, "resource %q", v.Token)
}
}
for _, v := range pkg.Types {
switch v := v.(type) {
case *ObjectType:
if strings.Contains(v.Token, "Overlay") {
assert.Truef(t, v.IsOverlay, "object type %q", v.Token)
} else {
assert.Falsef(t, v.IsOverlay, "object type %q", v.Token)
}
}
}
for _, v := range pkg.Functions {
if strings.Contains(v.Token, "Overlay") {
assert.Truef(t, v.IsOverlay, "function %q", v.Token)
} else {
assert.Falsef(t, v.IsOverlay, "function %q", v.Token)
}
}
})
}
// Tests that the method ReplaceOnChanges works as expected. Does not test
// codegen.
func TestReplaceOnChanges(t *testing.T) {

View file

@ -1,6 +1,8 @@
package codegen
import "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
import (
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
func visitTypeClosure(t schema.Type, visitor func(t schema.Type), seen Set) {
if seen.Has(t) {

View file

@ -16,10 +16,12 @@ package engine
import (
"context"
"errors"
"fmt"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -176,7 +178,7 @@ func newDeployment(ctx *Context, info *deploymentContext, opts deploymentOptions
imp := &opts.imports[i]
_, err := tokens.ParseTypeToken(imp.Type.String())
if err != nil {
return nil, errors.Errorf("import type %q is not a valid resource type token. "+
return nil, fmt.Errorf("import type %q is not a valid resource type token. "+
"Type tokens must be of the format <package>:<module>:<type> - "+
"refer to the import section of the provider resource documentation.", imp.Type.String())
}

View file

@ -1,7 +1,7 @@
package engine
import (
"github.com/pkg/errors"
"errors"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/pkg/v3/secrets"

View file

@ -17,6 +17,7 @@ package lifecycletest
import (
"context"
"errors"
"flag"
"fmt"
"os"
@ -26,7 +27,7 @@ import (
"github.com/blang/semver"
pbempty "github.com/golang/protobuf/ptypes/empty"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
@ -656,7 +657,7 @@ func TestStackReference(t *testing.T) {
"foo": "bar",
}), nil
default:
return nil, errors.Errorf("unknown stack \"%s\"", name)
return nil, fmt.Errorf("unknown stack \"%s\"", name)
}
},
},
@ -2104,7 +2105,7 @@ func (ctx *updateContext) Run(_ context.Context, req *pulumirpc.RunRequest) (*pu
rpcutil.GrpcChannelOptions(),
)
if err != nil {
return nil, errors.Wrapf(err, "could not connect to resource monitor")
return nil, fmt.Errorf("could not connect to resource monitor: %w", err)
}
defer contract.IgnoreClose(conn)

View file

@ -33,15 +33,21 @@ func TestDestroyTarget(t *testing.T) {
destroySpecificTargets(
t, []string{"A"}, true, /*targetDependents*/
func(urns []resource.URN, deleted map[resource.URN]bool) {
// when deleting 'A' we expect A, B, C, E, F, and K to be deleted
// when deleting 'A' we expect A, B, C, D, E, F, G, H, I, J, K, and L to be deleted
names := complexTestDependencyGraphNames
assert.Equal(t, map[resource.URN]bool{
pickURN(t, urns, names, "A"): true,
pickURN(t, urns, names, "B"): true,
pickURN(t, urns, names, "C"): true,
pickURN(t, urns, names, "D"): true,
pickURN(t, urns, names, "E"): true,
pickURN(t, urns, names, "F"): true,
pickURN(t, urns, names, "G"): true,
pickURN(t, urns, names, "H"): true,
pickURN(t, urns, names, "I"): true,
pickURN(t, urns, names, "J"): true,
pickURN(t, urns, names, "K"): true,
pickURN(t, urns, names, "L"): true,
}, deleted)
})

Some files were not shown because too many files have changed in this diff Show more