Update error handling (#8406)

This is the result of a change applied via `go-rewrap-errors`.
This commit is contained in:
Ian Wahbe 2021-11-12 18:37:17 -08:00 committed by GitHub
parent 164a2ec818
commit 272c4643b2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
120 changed files with 688 additions and 654 deletions

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"
@ -171,7 +170,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.
@ -663,11 +665,11 @@ func (b *localBackend) apply(
if saveErr != nil {
// We swallow backupErr as it is less important than the saveErr.
return changes, result.FromError(errors.Wrap(saveErr, "saving update info"))
return changes, result.FromError(fmt.Errorf("saving update info: %w", saveErr))
}
if backupErr != nil {
return changes, result.FromError(errors.Wrap(backupErr, "saving backup"))
return changes, result.FromError(fmt.Errorf("saving backup: %w", backupErr))
}
// Make sure to print a link to the stack's checkpoint before exiting.
@ -776,7 +778,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)
@ -840,7 +842,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 {
@ -880,3 +882,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.
@ -273,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.
@ -337,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.
@ -430,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)
}
@ -511,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
@ -696,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)
@ -909,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 {
@ -1074,7 +1074,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 changes, res
@ -1091,7 +1091,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.
@ -1126,7 +1126,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{
@ -1221,7 +1221,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)
@ -1261,9 +1263,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
}
@ -1452,7 +1454,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
@ -1484,7 +1486,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"
@ -178,7 +176,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()
@ -219,7 +217,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"
@ -118,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
@ -148,7 +148,7 @@ func newLoginCmd() *cobra.Command {
}
}
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 {
@ -177,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
}
@ -232,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
}
@ -249,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.
@ -303,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
}
@ -449,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)
}
@ -592,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)
@ -635,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
}
@ -686,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"

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"
@ -132,17 +134,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"
@ -436,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"

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"
@ -96,17 +96,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{}
@ -208,7 +208,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.
@ -256,7 +256,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.
@ -280,17 +280,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)
@ -588,7 +588,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"
@ -99,7 +100,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
@ -112,7 +113,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) {
@ -184,7 +185,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") == "" {
@ -215,7 +216,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,
@ -272,7 +273,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) {
@ -324,7 +325,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...)
@ -404,15 +405,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.
@ -437,7 +438,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
}
@ -472,8 +473,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 "+
@ -481,7 +483,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
@ -499,14 +501,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
@ -540,7 +543,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
@ -572,7 +575,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
@ -596,7 +599,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
@ -615,7 +618,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
@ -633,14 +636,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.
@ -671,7 +674,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)
@ -837,7 +840,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) {

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)

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)
}
}
@ -3130,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

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

@ -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)
}
}

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"
@ -1104,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)
}
}
}
@ -1883,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
@ -2054,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 {
@ -2544,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)
}
}

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"
@ -440,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
}
@ -467,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.
@ -632,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
}
@ -644,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)
}
}
@ -654,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
}
@ -666,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)
}
}
@ -676,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
}
@ -688,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)
}
}
}
@ -712,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
}
@ -724,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)
}
}
@ -739,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
}
@ -767,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)
}
}
@ -802,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
}

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

@ -15,7 +15,8 @@
package engine
import (
"github.com/pkg/errors"
"fmt"
"google.golang.org/grpc"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
@ -34,7 +35,7 @@ func connectToLanguageRuntime(ctx *plugin.Context, address string) (plugin.Host,
conn, err := grpc.Dial(address, grpc.WithInsecure(),
grpc.WithUnaryInterceptor(rpcutil.OpenTracingClientInterceptor()), rpcutil.GrpcChannelOptions())
if err != nil {
return nil, errors.Wrap(err, "could not connect to language host")
return nil, fmt.Errorf("could not connect to language host: %w", err)
}
client := pulumirpc.NewLanguageRuntimeClient(conn)

View file

@ -20,7 +20,7 @@ import (
"sort"
"github.com/blang/semver"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
@ -183,8 +183,9 @@ func installPlugin(plugin workspace.PluginInfo) error {
logging.V(preparePluginVerboseLog).Infof(
"installPlugin(%s, %s): extracting tarball to installation directory", plugin.Name, plugin.Version)
if err := plugin.Install(stream); err != nil {
return errors.Wrapf(err, "installing plugin; run `pulumi plugin install %s %s v%s` to retry manually",
plugin.Kind, plugin.Name, plugin.Version)
return fmt.Errorf("installing plugin; run `pulumi plugin install %s %s v%s` to retry manually: %w",
plugin.Kind, plugin.Name, plugin.Version, err)
}
logging.V(7).Infof("installPlugin(%s, %s): successfully installed", plugin.Name, plugin.Version)

View file

@ -15,11 +15,10 @@
package engine
import (
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
)
@ -59,7 +58,7 @@ func getPwdMain(root, main string) (string, string, error) {
// of the main program's parent directory. How we do this depends on if the target is a dir or not.
maininfo, err := os.Stat(main)
if err != nil {
return "", "", errors.Wrapf(err, "project 'main' could not be read")
return "", "", fmt.Errorf("project 'main' could not be read: %w", err)
}
if maininfo.IsDir() {
pwd = main

View file

@ -17,6 +17,7 @@ package engine
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"sort"
@ -24,7 +25,7 @@ import (
"sync"
"github.com/blang/semver"
"github.com/pkg/errors"
resourceanalyzer "github.com/pulumi/pulumi/pkg/v3/resource/analyzer"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -293,11 +294,11 @@ func installAndLoadPolicyPlugins(plugctx *plugin.Context, d diag.Sink, policies
config, validationErrors, err := resourceanalyzer.ReconcilePolicyPackConfig(
analyzerInfo.Policies, analyzerInfo.InitialConfig, configFromAPI)
if err != nil {
return errors.Wrapf(err, "reconciling config for %q", analyzerInfo.Name)
return fmt.Errorf("reconciling config for %q: %w", analyzerInfo.Name, err)
}
appendValidationErrors(analyzerInfo.Name, analyzerInfo.Version, validationErrors)
if err = analyzer.Configure(config); err != nil {
return errors.Wrapf(err, "configuring policy pack %q", analyzerInfo.Name)
return fmt.Errorf("configuring policy pack %q: %w", analyzerInfo.Name, err)
}
}
@ -312,7 +313,7 @@ func installAndLoadPolicyPlugins(plugctx *plugin.Context, d diag.Sink, policies
if err != nil {
return err
} else if analyzer == nil {
return errors.Errorf("policy analyzer could not be loaded from path %q", pack.Path)
return fmt.Errorf("policy analyzer could not be loaded from path %q", pack.Path)
}
// Update the Policy Pack names now that we have loaded the plugins and can access the name.
@ -325,7 +326,7 @@ func installAndLoadPolicyPlugins(plugctx *plugin.Context, d diag.Sink, policies
// Load config, reconcile & validate it, and pass it to the policy pack.
if !analyzerInfo.SupportsConfig {
if pack.Config != "" {
return errors.Errorf("policy pack %q at %q does not support config", analyzerInfo.Name, pack.Path)
return fmt.Errorf("policy pack %q at %q does not support config", analyzerInfo.Name, pack.Path)
}
continue
}
@ -339,11 +340,11 @@ func installAndLoadPolicyPlugins(plugctx *plugin.Context, d diag.Sink, policies
config, validationErrors, err := resourceanalyzer.ReconcilePolicyPackConfig(
analyzerInfo.Policies, analyzerInfo.InitialConfig, configFromFile)
if err != nil {
return errors.Wrapf(err, "reconciling policy config for %q at %q", analyzerInfo.Name, pack.Path)
return fmt.Errorf("reconciling policy config for %q at %q: %w", analyzerInfo.Name, pack.Path, err)
}
appendValidationErrors(analyzerInfo.Name, analyzerInfo.Version, validationErrors)
if err = analyzer.Configure(config); err != nil {
return errors.Wrapf(err, "configuring policy pack %q at %q", analyzerInfo.Name, pack.Path)
return fmt.Errorf("configuring policy pack %q at %q: %w", analyzerInfo.Name, pack.Path, err)
}
}

View file

@ -34,7 +34,6 @@ require (
github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d
github.com/opentracing/opentracing-go v1.1.0
github.com/pgavlin/goldmark v1.1.33-0.20200616210433-b5eb04559386
github.com/pkg/errors v0.9.1
github.com/pulumi/pulumi/sdk/v3 v3.17.1
github.com/rjeczalik/notify v0.9.2
github.com/santhosh-tekuri/jsonschema/v5 v5.0.0
@ -130,6 +129,7 @@ require (
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/opentracing/basictracer-go v1.0.0 // indirect
github.com/pierrec/lz4 v2.6.0+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.6.1 // indirect

View file

@ -15,7 +15,7 @@
package graph
import (
"github.com/pkg/errors"
"errors"
)
// Topsort topologically sorts the graph, yielding an array of nodes that are in dependency order, using a simple

View file

@ -15,6 +15,8 @@
package operations
import (
"errors"
"fmt"
"sort"
"sync"
"time"
@ -23,7 +25,6 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
@ -140,7 +141,7 @@ func getAWSSession(awsRegion, awsAccessKey, awsSecretKey, token string) (*sessio
if awsDefaultSession == nil {
sess, err := session.NewSession()
if err != nil {
return nil, errors.Wrap(err, "failed to create AWS session")
return nil, fmt.Errorf("failed to create AWS session: %w", err)
}
awsDefaultSession = sess

View file

@ -27,7 +27,6 @@ import (
"google.golang.org/api/option"
loggingpb "google.golang.org/genproto/googleapis/logging/v2"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
@ -147,10 +146,10 @@ func getLogEntryMessage(e *loggingpb.LogEntry) (string, error) {
case *loggingpb.LogEntry_JsonPayload:
byts, err := json.Marshal(payload.JsonPayload)
if err != nil {
return "", errors.Wrap(err, "encoding to JSON")
return "", fmt.Errorf("encoding to JSON: %w", err)
}
return string(byts), nil
default:
return "", errors.Errorf("can't decode entry of type %s", reflect.TypeOf(e))
return "", fmt.Errorf("can't decode entry of type %s", reflect.TypeOf(e))
}
}

View file

@ -16,11 +16,11 @@ package analyzer
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
@ -54,7 +54,7 @@ func ParsePolicyPackConfigFromAPI(config map[string]*json.RawMessage) (map[strin
el, err := extractEnforcementLevel(props)
if err != nil {
return nil, errors.Wrapf(err, "parsing enforcement level for %q", k)
return nil, fmt.Errorf("parsing enforcement level for %q: %w", k, err)
}
enforcementLevel = el
if len(props) > 0 {
@ -93,21 +93,20 @@ func parsePolicyPackConfig(b []byte) (map[string]plugin.AnalyzerPolicyConfig, er
case string:
el := apitype.EnforcementLevel(val)
if !el.IsValid() {
return nil, errors.Errorf(
"parsing enforcement level for %q: %q is not a valid enforcement level", k, val)
return nil, fmt.Errorf("parsing enforcement level for %q: %q is not a valid enforcement level", k, val)
}
enforcementLevel = el
case map[string]interface{}:
el, err := extractEnforcementLevel(val)
if err != nil {
return nil, errors.Wrapf(err, "parsing enforcement level for %q", k)
return nil, fmt.Errorf("parsing enforcement level for %q: %w", k, err)
}
enforcementLevel = el
if len(val) > 0 {
properties = val
}
default:
return nil, errors.Errorf("parsing %q: %v is not a valid value; must be a string or object", k, v)
return nil, fmt.Errorf("parsing %q: %v is not a valid value; must be a string or object", k, v)
}
// Don't bother including empty configs.
@ -132,11 +131,11 @@ func extractEnforcementLevel(props map[string]interface{}) (apitype.EnforcementL
if unknown, ok := props["enforcementLevel"]; ok {
enforcementLevelStr, isStr := unknown.(string)
if !isStr {
return "", errors.Errorf("%v is not a valid enforcement level; must be a string", unknown)
return "", fmt.Errorf("%v is not a valid enforcement level; must be a string", unknown)
}
el := apitype.EnforcementLevel(enforcementLevelStr)
if !el.IsValid() {
return "", errors.Errorf("%q is not a valid enforcement level", enforcementLevelStr)
return "", fmt.Errorf("%q is not a valid enforcement level", enforcementLevelStr)
}
enforcementLevel = el
// Remove enforcementLevel from the map.
@ -208,7 +207,7 @@ func ValidatePolicyPackConfig(schemaMap map[string]apitype.PolicyConfigSchema,
configLoader := gojsonschema.NewBytesLoader(*propertyConfig)
result, err := gojsonschema.Validate(schemaLoader, configLoader)
if err != nil {
return errors.Wrap(err, "unable to validate schema")
return fmt.Errorf("unable to validate schema: %w", err)
}
// If the result is invalid, we need to gather the errors to return to the user.

View file

@ -2,11 +2,11 @@ package deploy
import (
"context"
"errors"
"fmt"
"sort"
uuid "github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
@ -70,7 +70,7 @@ func (p *builtinProvider) Check(urn resource.URN, state, inputs resource.Propert
typ := urn.Type()
if typ != stackReferenceType {
return nil, nil, errors.Errorf("unrecognized resource type '%v'", urn.Type())
return nil, nil, fmt.Errorf("unrecognized resource type '%v'", urn.Type())
}
var name resource.PropertyValue
@ -193,7 +193,7 @@ func (p *builtinProvider) Invoke(tok tokens.ModuleMember,
}
return outs, nil, nil
default:
return nil, nil, errors.Errorf("unrecognized function name: '%v'", tok)
return nil, nil, fmt.Errorf("unrecognized function name: '%v'", tok)
}
}
@ -280,7 +280,7 @@ func (p *builtinProvider) getResource(inputs resource.PropertyMap) (resource.Pro
state, ok := p.resources.get(resource.URN(urn.StringValue()))
if !ok {
return nil, errors.Errorf("unknown resource %v", urn.StringValue())
return nil, fmt.Errorf("unknown resource %v", urn.StringValue())
}
return resource.PropertyMap{

View file

@ -16,12 +16,12 @@ package deploy
import (
"context"
"fmt"
"math"
"sync"
"github.com/blang/semver"
uuid "github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
@ -198,7 +198,7 @@ func addDefaultProviders(target *Target, source Source, prev *Snapshot) error {
if !ok {
inputs, err := target.GetPackageConfig(pkg)
if err != nil {
return errors.Errorf("could not fetch configuration for default provider '%v'", pkg)
return fmt.Errorf("could not fetch configuration for default provider '%v'", pkg)
}
if version, ok := defaultProviderVersions[pkg]; ok {
inputs["version"] = resource.NewStringProperty(version.String())
@ -282,7 +282,7 @@ func buildResourceMap(prev *Snapshot, preview bool) ([]*resource.State, map[reso
urn := oldres.URN
if olds[urn] != nil {
return nil, nil, errors.Errorf("unexpected duplicate resource '%s'", urn)
return nil, nil, fmt.Errorf("unexpected duplicate resource '%s'", urn)
}
olds[urn] = oldres
}

View file

@ -16,10 +16,10 @@ package deploy
import (
"context"
"errors"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/pkg/v3/resource/graph"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"

View file

@ -16,13 +16,14 @@ package deploytest
import (
"context"
"errors"
"fmt"
"io"
"sync"
"github.com/blang/semver"
pbempty "github.com/golang/protobuf/ptypes/empty"
"github.com/pkg/errors"
"google.golang.org/grpc"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
@ -148,7 +149,7 @@ func (e *hostEngine) Log(_ context.Context, req *pulumirpc.LogRequest) (*pbempty
case pulumirpc.LogSeverity_ERROR:
sev = diag.Error
default:
return nil, errors.Errorf("Unrecognized logging severity: %v", req.Severity)
return nil, fmt.Errorf("Unrecognized logging severity: %v", req.Severity)
}
if req.Ephemeral {

View file

@ -18,7 +18,6 @@ import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
@ -44,7 +43,7 @@ func dialMonitor(ctx context.Context, endpoint string) (*ResourceMonitor, error)
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)
}
resmon := pulumirpc.NewResourceMonitorClient(conn)

View file

@ -15,10 +15,10 @@
package providers
import (
"errors"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
@ -59,11 +59,11 @@ func GetProviderPackage(typ tokens.Type) tokens.Package {
func validateURN(urn resource.URN) error {
if !urn.IsValid() {
return errors.Errorf("%s is not a valid URN", urn)
return fmt.Errorf("%s is not a valid URN", urn)
}
typ := urn.Type()
if typ.Module() != "pulumi:providers" {
return errors.Errorf("invalid module in type: expected 'pulumi:providers', got '%v'", typ.Module())
return fmt.Errorf("invalid module in type: expected 'pulumi:providers', got '%v'", typ.Module())
}
if typ.Name() == "" {
return errors.New("provider URNs must specify a type name")
@ -117,7 +117,7 @@ func ParseReference(s string) (Reference, error) {
// of the reference.
lastSep := strings.LastIndex(s, resource.URNNameDelimiter)
if lastSep == -1 {
return Reference{}, errors.Errorf("expected '%v' in provider reference '%v'", resource.URNNameDelimiter, s)
return Reference{}, fmt.Errorf("expected '%v' in provider reference '%v'", resource.URNNameDelimiter, s)
}
urn, id := resource.URN(s[:lastSep]), resource.ID(s[lastSep+len(resource.URNNameDelimiter):])
if err := validateURN(urn); err != nil {

View file

@ -15,12 +15,12 @@
package providers
import (
"errors"
"fmt"
"sync"
"github.com/blang/semver"
uuid "github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
@ -44,7 +44,7 @@ func GetProviderVersion(inputs resource.PropertyMap) (*semver.Version, error) {
sv, err := semver.ParseTolerant(versionProp.StringValue())
if err != nil {
return nil, errors.Errorf("could not parse provider version: %v", err)
return nil, fmt.Errorf("could not parse provider version: %v", err)
}
return &sv, nil
}
@ -104,13 +104,13 @@ func NewRegistry(host plugin.Host, prev []*resource.State, isPreview bool,
// Ensure that this provider has a known ID.
if res.ID == "" || res.ID == UnknownID {
return nil, errors.Errorf("provider '%v' has an unknown ID", urn)
return nil, fmt.Errorf("provider '%v' has an unknown ID", urn)
}
// Ensure that we have no duplicates.
ref := mustNewReference(urn, res.ID)
if _, ok := r.providers[ref]; ok {
return nil, errors.Errorf("duplicate provider found in old state: '%v'", ref)
return nil, fmt.Errorf("duplicate provider found in old state: '%v'", ref)
}
providerPkg := GetProviderPackage(urn.Type())
@ -118,19 +118,19 @@ func NewRegistry(host plugin.Host, prev []*resource.State, isPreview bool,
// Parse the provider version, then load, configure, and register the provider.
version, err := GetProviderVersion(res.Inputs)
if err != nil {
return nil, errors.Errorf("could not parse version for %v provider '%v': %v", providerPkg, urn, err)
return nil, fmt.Errorf("could not parse version for %v provider '%v': %v", providerPkg, urn, err)
}
provider, err := loadProvider(providerPkg, version, host, builtins)
if err != nil {
return nil, errors.Errorf("could not load plugin for %v provider '%v': %v", providerPkg, urn, err)
return nil, fmt.Errorf("could not load plugin for %v provider '%v': %v", providerPkg, urn, err)
}
if provider == nil {
return nil, errors.Errorf("could not find plugin for %v provider '%v' at version %v", providerPkg, urn, version)
return nil, fmt.Errorf("could not find plugin for %v provider '%v' at version %v", providerPkg, urn, version)
}
if err := provider.Configure(res.Inputs); err != nil {
closeErr := host.CloseProvider(provider)
contract.IgnoreError(closeErr)
return nil, errors.Errorf("could not configure provider '%v': %v", urn, err)
return nil, fmt.Errorf("could not configure provider '%v': %v", urn, err)
}
logging.V(7).Infof("loaded provider %v", ref)

View file

@ -15,11 +15,12 @@
package providers
import (
"errors"
"fmt"
"testing"
"github.com/blang/semver"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"

View file

@ -19,8 +19,6 @@ import (
"fmt"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy/providers"
"github.com/pulumi/pulumi/pkg/v3/secrets"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
@ -109,7 +107,7 @@ func (snap *Snapshot) NormalizeURNReferences() error {
// same resource multiple times. That's fine, only error if we see the same alias,
// but it maps to *different* resources.
if otherUrn, has := aliased[alias]; has && otherUrn != state.URN {
return errors.Errorf("Two resources ('%s' and '%s') aliased to the same: '%s'", otherUrn, state.URN, alias)
return fmt.Errorf("Two resources ('%s' and '%s') aliased to the same: '%s'", otherUrn, state.URN, alias)
}
aliased[alias] = state.URN
}
@ -133,7 +131,7 @@ func (snap *Snapshot) VerifyIntegrity() error {
if snap != nil {
// Ensure the magic cookie checks out.
if snap.Manifest.Magic != snap.Manifest.NewMagic() {
return errors.Errorf("magic cookie mismatch; possible tampering/corruption detected")
return fmt.Errorf("magic cookie mismatch; possible tampering/corruption detected")
}
// Now check the resources. For now, we just verify that parents come before children, and that there aren't
@ -146,17 +144,17 @@ func (snap *Snapshot) VerifyIntegrity() error {
if providers.IsProviderType(state.Type) {
ref, err := providers.NewReference(urn, state.ID)
if err != nil {
return errors.Errorf("provider %s is not referenceable: %v", urn, err)
return fmt.Errorf("provider %s is not referenceable: %v", urn, err)
}
provs[ref] = struct{}{}
}
if provider := state.Provider; provider != "" {
ref, err := providers.ParseReference(provider)
if err != nil {
return errors.Errorf("failed to parse provider reference for resource %s: %v", urn, err)
return fmt.Errorf("failed to parse provider reference for resource %s: %v", urn, err)
}
if _, has := provs[ref]; !has {
return errors.Errorf("resource %s refers to unknown provider %s", urn, ref)
return fmt.Errorf("resource %s refers to unknown provider %s", urn, ref)
}
}
@ -166,10 +164,10 @@ func (snap *Snapshot) VerifyIntegrity() error {
// whether it comes later in the snapshot (neither of which should ever happen).
for _, other := range snap.Resources[i+1:] {
if other.URN == par {
return errors.Errorf("child resource %s's parent %s comes after it", urn, par)
return fmt.Errorf("child resource %s's parent %s comes after it", urn, par)
}
}
return errors.Errorf("child resource %s refers to missing parent %s", urn, par)
return fmt.Errorf("child resource %s refers to missing parent %s", urn, par)
}
}
@ -178,17 +176,17 @@ func (snap *Snapshot) VerifyIntegrity() error {
// same as above - doing this for better error messages
for _, other := range snap.Resources[i+1:] {
if other.URN == dep {
return errors.Errorf("resource %s's dependency %s comes after it", urn, other.URN)
return fmt.Errorf("resource %s's dependency %s comes after it", urn, other.URN)
}
}
return errors.Errorf("resource %s dependency %s refers to missing resource", urn, dep)
return fmt.Errorf("resource %s dependency %s refers to missing resource", urn, dep)
}
}
if _, has := urns[urn]; has && !state.Delete {
// The only time we should have duplicate URNs is when all but one of them are marked for deletion.
return errors.Errorf("duplicate resource %s (not marked for deletion)", urn)
return fmt.Errorf("duplicate resource %s (not marked for deletion)", urn)
}
urns[urn] = state

View file

@ -16,6 +16,7 @@ package deploy
import (
"context"
"errors"
"fmt"
"time"
@ -23,7 +24,7 @@ import (
pbempty "github.com/golang/protobuf/ptypes/empty"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
@ -96,7 +97,7 @@ func (src *evalSource) Iterate(
// Decrypt the configuration.
config, err := src.runinfo.Target.Config.Decrypt(src.runinfo.Target.Decrypter)
if err != nil {
return nil, result.FromError(errors.Wrap(err, "failed to decrypt config"))
return nil, result.FromError(fmt.Errorf("failed to decrypt config: %w", err))
}
// Keep track of any config keys that have secure values.
@ -109,7 +110,7 @@ func (src *evalSource) Iterate(
mon, err := newResourceMonitor(
src, providers, regChan, regOutChan, regReadChan, opts, config, configSecretKeys, tracingSpan)
if err != nil {
return nil, result.FromError(errors.Wrap(err, "failed to start resource monitor"))
return nil, result.FromError(fmt.Errorf("failed to start resource monitor: %w", err))
}
// Create a new iterator with appropriate channels, and gear up to go!
@ -197,7 +198,7 @@ func (iter *evalSourceIterator) forkRun(opts Options, config map[config.Key]stri
rt := iter.src.runinfo.Proj.Runtime.Name()
langhost, err := iter.src.plugctx.Host.LanguageRuntime(rt)
if err != nil {
return result.FromError(errors.Wrapf(err, "failed to launch language host %s", rt))
return result.FromError(fmt.Errorf("failed to launch language host %s: %w", rt, err))
}
contract.Assertf(langhost != nil, "expected non-nil language host %s", rt)
@ -226,7 +227,7 @@ func (iter *evalSourceIterator) forkRun(opts Options, config map[config.Key]stri
if err == nil && progerr != "" {
// If the program had an unhandled error; propagate it to the caller.
err = errors.Errorf("an unhandled error occurred: %v", progerr)
err = fmt.Errorf("an unhandled error occurred: %v", progerr)
}
return result.WrapIfNonNil(err)
}
@ -486,7 +487,7 @@ func getProviderReference(defaultProviders *defaultProviders, req providers.Prov
if rawProviderRef != "" {
ref, err := providers.ParseReference(rawProviderRef)
if err != nil {
return providers.Reference{}, errors.Errorf("could not parse provider reference: %v", err)
return providers.Reference{}, fmt.Errorf("could not parse provider reference: %v", err)
}
return ref, nil
}
@ -511,7 +512,7 @@ func getProviderFromSource(
}
provider, ok := providers.GetProvider(providerRef)
if !ok {
return nil, errors.Errorf("unknown provider '%v'", rawProviderRef)
return nil, fmt.Errorf("unknown provider '%v'", rawProviderRef)
}
return provider, nil
}
@ -575,14 +576,14 @@ func (rm *resmon) Invoke(ctx context.Context, req *pulumirpc.InvokeRequest) (*pu
KeepResources: true,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal %v args", tok)
return nil, fmt.Errorf("failed to unmarshal %v args: %w", tok, err)
}
// Do the invoke and then return the arguments.
logging.V(5).Infof("ResourceMonitor.Invoke received: tok=%v #args=%v", tok, len(args))
ret, failures, err := prov.Invoke(tok, args)
if err != nil {
return nil, errors.Wrapf(err, "invocation of %v returned an error", tok)
return nil, fmt.Errorf("invocation of %v returned an error: %w", tok, err)
}
mret, err := plugin.MarshalProperties(ret, plugin.MarshalOptions{
Label: label,
@ -590,7 +591,7 @@ func (rm *resmon) Invoke(ctx context.Context, req *pulumirpc.InvokeRequest) (*pu
KeepResources: true,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal %v return", tok)
return nil, fmt.Errorf("failed to marshal %v return: %w", tok, err)
}
var chkfails []*pulumirpc.CheckFailure
for _, failure := range failures {
@ -628,7 +629,7 @@ func (rm *resmon) Call(ctx context.Context, req *pulumirpc.CallRequest) (*pulumi
KeepOutputValues: true,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal %v args", tok)
return nil, fmt.Errorf("failed to unmarshal %v args: %w", tok, err)
}
argDependencies := map[resource.PropertyKey][]resource.URN{}
@ -657,7 +658,7 @@ func (rm *resmon) Call(ctx context.Context, req *pulumirpc.CallRequest) (*pulumi
"ResourceMonitor.Call received: tok=%v #args=%v #info=%v #options=%v", tok, len(args), info, options)
ret, err := prov.Call(tok, args, info, options)
if err != nil {
return nil, errors.Wrapf(err, "call of %v returned an error", tok)
return nil, fmt.Errorf("call of %v returned an error: %w", tok, err)
}
mret, err := plugin.MarshalProperties(ret.Return, plugin.MarshalOptions{
Label: label,
@ -666,7 +667,7 @@ func (rm *resmon) Call(ctx context.Context, req *pulumirpc.CallRequest) (*pulumi
KeepResources: true,
})
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal %v return", tok)
return nil, fmt.Errorf("failed to marshal %v return: %w", tok, err)
}
returnDependencies := map[string]*pulumirpc.CallResponse_ReturnDependencies{}
@ -711,7 +712,7 @@ func (rm *resmon) StreamInvoke(
KeepResources: true,
})
if err != nil {
return errors.Wrapf(err, "failed to unmarshal %v args", tok)
return fmt.Errorf("failed to unmarshal %v args: %w", tok, err)
}
// Synchronously do the StreamInvoke and then return the arguments. This will block until the
@ -724,13 +725,13 @@ func (rm *resmon) StreamInvoke(
KeepResources: req.GetAcceptResources(),
})
if err != nil {
return errors.Wrapf(err, "failed to marshal return")
return fmt.Errorf("failed to marshal return: %w", err)
}
return stream.Send(&pulumirpc.InvokeResponse{Return: mret})
})
if err != nil {
return errors.Wrapf(err, "streaming invocation of %v returned an error", tok)
return fmt.Errorf("streaming invocation of %v returned an error: %w", tok, err)
}
var chkfails []*pulumirpc.CheckFailure
@ -829,7 +830,7 @@ func (rm *resmon) ReadResource(ctx context.Context,
KeepResources: req.GetAcceptResources(),
})
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal %s return state", result.State.URN)
return nil, fmt.Errorf("failed to marshal %s return state: %w", result.State.URN, err)
}
return &pulumirpc.ReadResourceResponse{
@ -988,7 +989,7 @@ func (rm *resmon) RegisterResource(ctx context.Context,
if remote {
provider, ok := rm.providers.GetProvider(providerRef)
if !ok {
return nil, errors.Errorf("unknown provider '%v'", providerRef)
return nil, fmt.Errorf("unknown provider '%v'", providerRef)
}
// Invoke the provider's Construct RPC method.
@ -1108,7 +1109,7 @@ func (rm *resmon) RegisterResourceOutputs(ctx context.Context,
KeepResources: true,
})
if err != nil {
return nil, errors.Wrapf(err, "cannot unmarshal output properties")
return nil, fmt.Errorf("cannot unmarshal output properties: %w", err)
}
logging.V(5).Infof("ResourceMonitor.RegisterResourceOutputs received: urn=%v, #outs=%v", urn, len(outs))
@ -1213,7 +1214,7 @@ func (g *readResourceEvent) Done(result *ReadResult) {
func generateTimeoutInSeconds(timeout string) (float64, error) {
duration, err := time.ParseDuration(timeout)
if err != nil {
return 0, errors.Errorf("unable to parse customTimeout Value %s", timeout)
return 0, fmt.Errorf("unable to parse customTimeout Value %s", timeout)
}
return duration.Seconds(), nil

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