From 730b03921b7a228eb5849a8a097d85d7fd893017 Mon Sep 17 00:00:00 2001 From: camille <7492974+epsxy@users.noreply.github.com> Date: Wed, 22 Jun 2022 22:33:47 +0200 Subject: [PATCH] refactor: replace `pkg/errors` by golang built-in errors (#2175) Signed-off-by: epsxy Co-authored-by: epsxy Co-authored-by: Carolyn Van Slyck --- CONTRIBUTORS.md | 3 +- cmd/porter/main.go | 3 +- docs/content/contribute/tutorial.md | 3 +- go.mod | 2 +- magefile.go | 17 +++-- pkg/agent/agent.go | 3 +- pkg/build/buildkit/buildx.go | 20 +++--- pkg/build/dockerfile-generator.go | 25 +++++--- pkg/cache/cache.go | 17 +++-- pkg/cache/cached_bundle.go | 16 ++--- pkg/cli/config.go | 5 +- pkg/cnab/cnab-to-oci/registry.go | 17 +++-- pkg/cnab/config-adapter/adapter_test.go | 3 +- pkg/cnab/config-adapter/stamp.go | 20 +++--- pkg/cnab/dependencies.go | 9 ++- pkg/cnab/docker.go | 14 ++-- pkg/cnab/drivers/drivers.go | 5 +- pkg/cnab/extended_bundle.go | 13 ++-- pkg/cnab/parameter_sources.go | 24 +++---- pkg/cnab/provider/action.go | 32 ++++++---- pkg/cnab/provider/bundle.go | 5 +- pkg/cnab/provider/docker_linux.go | 8 +-- pkg/cnab/provider/driver.go | 9 +-- pkg/cnab/provider/runtime.go | 5 +- pkg/cnab/reference.go | 6 +- pkg/cnab/required.go | 8 +-- pkg/cnab/solver.go | 12 ++-- pkg/config/config.go | 12 ++-- pkg/config/loader.go | 16 ++--- pkg/docs/generator.go | 11 ++-- pkg/encoding/encoding.go | 12 ++-- pkg/exec/builder/action.go | 11 ++-- pkg/exec/builder/execute.go | 8 +-- pkg/exec/builder/flags.go | 6 +- pkg/exec/builder/output_file.go | 5 +- pkg/exec/builder/output_jsonpath.go | 9 ++- pkg/exec/builder/output_regex.go | 5 +- pkg/exec/lint.go | 3 +- pkg/linter/linter.go | 3 +- pkg/manifest/manifest.go | 64 ++++++++++--------- pkg/mixin/query/manifest_generator.go | 9 ++- pkg/mixin/query/query.go | 5 +- pkg/pkgmgmt/client/delete.go | 5 +- pkg/pkgmgmt/client/filesystem.go | 5 +- pkg/pkgmgmt/client/runner.go | 8 +-- pkg/pkgmgmt/download_options.go | 5 +- pkg/pkgmgmt/feed/generate.go | 11 ++-- pkg/pkgmgmt/feed/load.go | 5 +- pkg/pkgmgmt/feed/template.go | 3 +- pkg/pkgmgmt/install.go | 14 ++-- pkg/pkgmgmt/search.go | 10 ++- pkg/pkgmgmt/uninstall.go | 8 +-- pkg/plugins/pluggable/connection.go | 8 +-- pkg/plugins/pluggable/loader.go | 3 +- pkg/plugins/plugins.go | 2 +- pkg/plugins/runner.go | 12 ++-- pkg/porter/apply.go | 10 +-- pkg/porter/archive.go | 8 +-- pkg/porter/build.go | 30 ++++++--- pkg/porter/build_integration_test.go | 2 +- pkg/porter/cnab.go | 19 +++--- pkg/porter/copy.go | 8 +-- pkg/porter/create.go | 3 +- pkg/porter/credentials.go | 46 +++++++------ pkg/porter/credentials_test.go | 6 +- pkg/porter/delete.go | 4 +- pkg/porter/dependencies.go | 20 +++--- pkg/porter/explain.go | 15 ++--- pkg/porter/generateManifest.go | 5 +- pkg/porter/inspect.go | 7 +- pkg/porter/install.go | 7 +- pkg/porter/internal_plugins.go | 4 +- pkg/porter/invoke.go | 4 +- pkg/porter/lifecycle.go | 16 ++--- pkg/porter/lint.go | 5 +- pkg/porter/lint_test.go | 2 +- pkg/porter/list.go | 3 +- pkg/porter/logs.go | 2 +- pkg/porter/mixins.go | 8 +-- pkg/porter/outputs.go | 8 +-- pkg/porter/packages.go | 3 +- pkg/porter/parameters.go | 56 +++++++++------- pkg/porter/parameters_test.go | 6 +- pkg/porter/plugins.go | 7 +- pkg/porter/porter.go | 2 +- pkg/porter/publish.go | 42 ++++++------ pkg/porter/publish_test.go | 2 +- pkg/porter/pull.go | 5 +- pkg/porter/reconcile.go | 8 +-- pkg/porter/resolver.go | 5 +- pkg/porter/run.go | 3 +- pkg/porter/schema.go | 41 ++++++------ pkg/porter/stamp.go | 10 +-- pkg/porter/storage.go | 10 +-- pkg/porter/uninstall.go | 6 +- pkg/porter/uninstall_test.go | 2 +- pkg/porter/upgrade.go | 4 +- pkg/porter/version.go | 3 +- pkg/portercontext/context.go | 28 +++++--- pkg/portercontext/helpers.go | 10 +-- pkg/portercontext/telemetry.go | 13 ++-- pkg/printer/json.go | 3 +- pkg/printer/printer.go | 7 +- pkg/printer/table.go | 4 +- pkg/printer/yaml.go | 3 +- pkg/runtime/dependencies.go | 7 +- pkg/runtime/outputs.go | 5 +- pkg/runtime/runtime-manifest.go | 51 ++++++++------- pkg/runtime/runtime.go | 21 +++--- pkg/schema/check-strategy.go | 15 ++--- pkg/schema/check-strategy_test.go | 12 ++-- pkg/secrets/plugins/filesystem/store.go | 2 +- pkg/secrets/plugins/in-memory/store.go | 2 +- pkg/secrets/pluginstore/store.go | 2 +- pkg/storage/credential_store.go | 3 +- pkg/storage/credentialset.go | 3 +- pkg/storage/credentialset_provider_helpers.go | 13 ++-- pkg/storage/installation.go | 20 +++--- pkg/storage/installation_store.go | 2 +- pkg/storage/migrations/manager.go | 18 ++++-- pkg/storage/parameter_store.go | 3 +- pkg/storage/parameterset.go | 3 +- pkg/storage/parameterset_provider_helpers.go | 13 ++-- pkg/storage/plugin_adapter.go | 26 ++++++-- pkg/storage/plugins/mongodb/mongodb.go | 2 +- pkg/storage/plugins/mongodb_docker/store.go | 2 +- pkg/storage/sanitizer.go | 6 +- pkg/tracing/traceLogger.go | 41 +----------- pkg/yaml/yq.go | 27 ++++++-- tests/tester/main.go | 8 +-- 130 files changed, 740 insertions(+), 674 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fe2a82e47..09c16fab5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -70,4 +70,5 @@ and we will add you. **All** contributors belong here. 💯 * [Chioma Onyekpere](https://github.com/Simpcyclassy) * [Hrittik Roy](https://github.com/hrittikhere) * [Tanmay Chaudhry](https://github.com/tchaudhry91) -* [Kevin Barbour](https://github.com/kevinbarbour) \ No newline at end of file +* [Kevin Barbour](https://github.com/kevinbarbour) +* [Epsxy](https://github.com/epsxy) \ No newline at end of file diff --git a/cmd/porter/main.go b/cmd/porter/main.go index 453a0e274..65c79381b 100644 --- a/cmd/porter/main.go +++ b/cmd/porter/main.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/cli" "get.porter.sh/porter/pkg/porter" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" "go.opentelemetry.io/otel/attribute" @@ -72,7 +71,7 @@ func main() { defer func() { // Capture panics and trace them if panicErr := recover(); panicErr != nil { - log.Error(errors.New(fmt.Sprintf("%s", panicErr)), + log.Error(fmt.Errorf("%s", panicErr), attribute.Bool("panic", true), attribute.String("stackTrace", string(debug.Stack()))) log.EndSpan() diff --git a/docs/content/contribute/tutorial.md b/docs/content/contribute/tutorial.md index 7f44b3e8c..af185344b 100644 --- a/docs/content/contribute/tutorial.md +++ b/docs/content/contribute/tutorial.md @@ -310,8 +310,7 @@ YOURNAME` that prints `Hello YOURNAME!`. import ( "fmt" - - "github.com/pkg/errors" + "errors" ) // Define flags and arguments for `porter hello`. diff --git a/go.mod b/go.mod index 3f4b2c3cf..b27a7e0bd 100644 --- a/go.mod +++ b/go.mod @@ -53,7 +53,6 @@ require ( github.com/osteele/liquid v1.3.0 github.com/pelletier/go-toml v1.9.4 github.com/pivotal/image-relocation v0.0.0-20191111101224-e94aff6df06c - github.com/pkg/errors v0.9.1 github.com/spf13/afero v1.5.1 github.com/spf13/cobra v1.2.1 github.com/spf13/pflag v1.0.5 @@ -174,6 +173,7 @@ require ( github.com/opencontainers/runc v1.1.2 // indirect github.com/osteele/tuesday v1.0.3 // indirect github.com/pierrec/lz4/v4 v4.0.3 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect diff --git a/magefile.go b/magefile.go index c1c575eef..0f56fc83b 100644 --- a/magefile.go +++ b/magefile.go @@ -35,7 +35,6 @@ import ( "github.com/carolynvs/magex/xplat" "github.com/magefile/mage/mg" "github.com/magefile/mage/sh" - "github.com/pkg/errors" "golang.org/x/sync/errgroup" ) @@ -411,7 +410,11 @@ func UseXBuildBinaries() error { // Run `chmod +x -R bin`. func SetBinExecutable() error { err := chmodRecursive("bin", pkg.FileModeExecutable) - return errors.Wrap(err, "could not set +x on the test bin") + if err != nil { + return fmt.Errorf("could not set +x on the test bin: %w", err) + } + + return nil } func chmodRecursive(name string, mode os.FileMode) error { @@ -456,7 +459,10 @@ func Install() { // Copy mixin binaries mixinsDir := filepath.Join("bin", "mixins") mixinsDirItems, err := ioutil.ReadDir(mixinsDir) - mgx.Must(errors.Wrap(err, "could not list mixins in bin")) + if err != nil { + mgx.Must(fmt.Errorf("could not list mixins in bin: %w", err)) + } + for _, fi := range mixinsDirItems { if !fi.IsDir() { continue @@ -490,7 +496,10 @@ func getPorterHome() string { porterHome := os.Getenv("PORTER_HOME") if porterHome == "" { home, err := os.UserHomeDir() - mgx.Must(errors.Wrap(err, "could not determine home directory")) + if err != nil { + mgx.Must(fmt.Errorf("could not determine home directory: %w", err)) + } + porterHome = filepath.Join(home, ".porter") } return porterHome diff --git a/pkg/agent/agent.go b/pkg/agent/agent.go index 03cb0d574..9283b8ff1 100644 --- a/pkg/agent/agent.go +++ b/pkg/agent/agent.go @@ -10,7 +10,6 @@ import ( "strings" "get.porter.sh/porter/pkg" - "github.com/pkg/errors" "golang.org/x/sync/errgroup" ) @@ -74,7 +73,7 @@ func Execute(porterCommand []string, porterHome string, porterConfig string) (er cmd.Stdout = stderr // send all non-bundle output to stderr cmd.Stderr = stderr if err = cmd.Run(); err != nil { - return errors.Wrap(err, "porter version check failed"), false + return fmt.Errorf("porter version check failed: %w", err), false } // Run the specified porter command diff --git a/pkg/build/buildkit/buildx.go b/pkg/build/buildkit/buildx.go index 202871f14..73b6a3cff 100644 --- a/pkg/build/buildkit/buildx.go +++ b/pkg/build/buildkit/buildx.go @@ -28,7 +28,6 @@ import ( dockerclient "github.com/docker/docker/client" "github.com/moby/buildkit/session" "github.com/moby/buildkit/session/auth/authprovider" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" ) @@ -80,7 +79,7 @@ func (b *Builder) BuildInvocationImage(ctx context.Context, manifest *manifest.M d, err := driver.GetDriver(ctx, "porter-driver", nil, cli.Client(), imageopt.Auth, nil, nil, nil, nil, nil, b.Getwd()) if err != nil { - return log.Error(errors.Wrapf(err, "error loading buildx driver")) + return log.Error(fmt.Errorf("error loading buildx driver: %w", err)) } drivers := []buildx.DriverInfo{ @@ -97,13 +96,13 @@ func (b *Builder) BuildInvocationImage(ctx context.Context, manifest *manifest.M session := []session.Attachable{authprovider.NewDockerAuthProvider(b.Err)} ssh, err := buildflags.ParseSSHSpecs(opts.SSH) if err != nil { - return errors.Wrap(err, "error parsing the --ssh flags") + return fmt.Errorf("error parsing the --ssh flags: %w", err) } session = append(session, ssh) secrets, err := buildflags.ParseSecretSpecs(opts.Secrets) if err != nil { - return errors.Wrap(err, "error parsing the --secret flags") + return fmt.Errorf("error parsing the --secret flags: %w", err) } session = append(session, secrets) @@ -148,10 +147,15 @@ func (b *Builder) BuildInvocationImage(ctx context.Context, manifest *manifest.M _, buildErr := buildx.Build(ctx, drivers, buildxOpts, dockerToBuildx{cli}, confutil.ConfigDir(cli), printer) printErr := printer.Wait() - if buildErr == nil { - return log.Error(errors.Wrapf(printErr, "error with docker printer")) + if buildErr == nil && printErr != nil { + return log.Error(fmt.Errorf("error with docker printer: %w", printErr)) } - return log.Error(errors.Wrapf(buildErr, "error building docker image")) + + if buildErr != nil { + return log.Error(fmt.Errorf("error building docker image: %w", buildErr)) + } + + return nil } func parseBuildArgs(unparsed []string, parsed map[string]string) { @@ -195,7 +199,7 @@ func (b *Builder) TagInvocationImage(ctx context.Context, origTag, newTag string } if err := cli.Client().ImageTag(ctx, origTag, newTag); err != nil { - return log.Error(errors.Wrapf(err, "could not tag image %s with value %s", origTag, newTag)) + return log.Error(fmt.Errorf("could not tag image %s with value %s: %w", origTag, newTag, err)) } return nil } diff --git a/pkg/build/dockerfile-generator.go b/pkg/build/dockerfile-generator.go index df131251d..5a4e1ff87 100644 --- a/pkg/build/dockerfile-generator.go +++ b/pkg/build/dockerfile-generator.go @@ -16,7 +16,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/templates" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) const ( @@ -45,7 +44,7 @@ func NewDockerfileGenerator(config *config.Config, m *manifest.Manifest, tmpl *t func (g *DockerfileGenerator) GenerateDockerFile(ctx context.Context) error { lines, err := g.buildDockerfile(ctx) if err != nil { - return errors.Wrap(err, "error generating the Dockerfile") + return fmt.Errorf("error generating the Dockerfile: %w", err) } fmt.Fprintf(g.Out, "\nWriting Dockerfile =======>\n") @@ -56,7 +55,11 @@ func (g *DockerfileGenerator) GenerateDockerFile(ctx context.Context) error { } err = g.FileSystem.WriteFile(DOCKER_FILE, []byte(contents), pkg.FileModeWritable) - return errors.Wrap(err, "couldn't write the Dockerfile") + if err != nil { + return fmt.Errorf("couldn't write the Dockerfile: %w", err) + } + + return nil } func (g *DockerfileGenerator) buildDockerfile(ctx context.Context) ([]string, error) { @@ -88,10 +91,10 @@ func (g *DockerfileGenerator) getBaseDockerfile(ctx context.Context) ([]string, if g.Manifest.Dockerfile != "" { exists, err := g.FileSystem.Exists(g.Manifest.Dockerfile) if err != nil { - return nil, errors.Wrapf(err, "error checking if Dockerfile exists: %q", g.Manifest.Dockerfile) + return nil, fmt.Errorf("error checking if Dockerfile exists: %q: %w", g.Manifest.Dockerfile, err) } if !exists { - return nil, errors.Errorf("the Dockerfile specified in the manifest doesn't exist: %q", g.Manifest.Dockerfile) + return nil, fmt.Errorf("the Dockerfile specified in the manifest doesn't exist: %q", g.Manifest.Dockerfile) } file, err := g.FileSystem.Open(g.Manifest.Dockerfile) @@ -103,7 +106,7 @@ func (g *DockerfileGenerator) getBaseDockerfile(ctx context.Context) ([]string, } else { contents, err := g.Templates.GetDockerfile() if err != nil { - return nil, errors.Wrap(err, "error loading default Dockerfile template") + return nil, fmt.Errorf("error loading default Dockerfile template: %w", err) } reader = bytes.NewReader(contents) } @@ -215,7 +218,7 @@ func (g *DockerfileGenerator) PrepareFilesystem() error { err = g.FileSystem.WriteFile(LOCAL_RUN, runTmpl, pkg.FileModeExecutable) if err != nil { - return errors.Wrapf(err, "failed to write %s", LOCAL_RUN) + return fmt.Errorf("failed to write %s: %w", LOCAL_RUN, err) } homeDir, err := g.GetHomeDir() @@ -246,7 +249,11 @@ func (g *DockerfileGenerator) copyMixin(mixin string) error { } err = g.Context.CopyDirectory(mixinDir, LOCAL_MIXINS, true) - return errors.Wrapf(err, "could not copy mixin directory contents for %s", mixin) + if err != nil { + return fmt.Errorf("could not copy mixin directory contents for %s: %w", mixin, err) + } + + return nil } func (g *DockerfileGenerator) getIndexOfToken(lines []string, token string) int { @@ -263,7 +270,7 @@ func (g *DockerfileGenerator) getIndexOfToken(lines []string, token string) int func (g *DockerfileGenerator) replaceTokens(ctx context.Context, lines []string) ([]string, error) { mixinLines, err := g.buildMixinsSection(ctx) if err != nil { - return nil, errors.Wrap(err, "error generating Dockerfile content for mixins") + return nil, fmt.Errorf("error generating Dockerfile content for mixins: %w", err) } fromToken := g.getIndexOfToken(lines, "FROM") diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index dd8b91be9..6532e7dde 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -12,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/encoding" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) type BundleCache interface { @@ -75,24 +74,24 @@ func (c *Cache) StoreBundle(bundleRef cnab.BundleReference) (CachedBundle, error // Remove any previously cached bundle files err = c.FileSystem.RemoveAll(cb.cacheDir) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "cannot remove existing cache directory %s", cb.BundlePath) + return CachedBundle{}, fmt.Errorf("cannot remove existing cache directory %s: %w", cb.BundlePath, err) } cb.BundlePath = cb.BuildBundlePath() err = c.FileSystem.MkdirAll(filepath.Dir(cb.BundlePath), pkg.FileModeDirectory) if err != nil { - return CachedBundle{}, errors.Wrap(err, "unable to create cache directory") + return CachedBundle{}, fmt.Errorf("unable to create cache directory: %w", err) } f, err := c.FileSystem.OpenFile(cb.BundlePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "error creating cnab/bundle.json for %s", cb.Reference) + return CachedBundle{}, fmt.Errorf("error creating cnab/bundle.json for %s: %w", cb.Reference, err) } defer f.Close() _, err = cb.Definition.WriteTo(f) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "error writing to cnab/bundle.json for %s", cb.Reference) + return CachedBundle{}, fmt.Errorf("error writing to cnab/bundle.json for %s: %w", cb.Reference, err) } err = c.cacheMetadata(&cb) @@ -110,18 +109,18 @@ func (c *Cache) StoreBundle(bundleRef cnab.BundleReference) (CachedBundle, error cb.RelocationFilePath = cb.BuildRelocationFilePath() f, err = c.FileSystem.OpenFile(cb.RelocationFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "error creating cnab/relocation-mapping.json for %s", cb.Reference) + return CachedBundle{}, fmt.Errorf("error creating cnab/relocation-mapping.json for %s: %w", cb.Reference, err) } defer f.Close() b, err := json.Marshal(cb.RelocationMap) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "couldn't marshall relocation mapping for %s", cb.Reference) + return CachedBundle{}, fmt.Errorf("couldn't marshall relocation mapping for %s: %w", cb.Reference, err) } _, err = f.Write(b) if err != nil { - return CachedBundle{}, errors.Wrapf(err, "couldn't write relocation mapping for %s", cb.Reference) + return CachedBundle{}, fmt.Errorf("couldn't write relocation mapping for %s: %w", cb.Reference, err) } } @@ -163,7 +162,7 @@ func (c *Cache) cacheManifest(cb *CachedBundle) error { cb.ManifestPath = cb.BuildManifestPath() err = stamp.WriteManifest(c.Context, cb.ManifestPath) if err != nil { - return errors.Wrapf(err, "error writing porter.yaml for %s", cb.Reference) + return fmt.Errorf("error writing porter.yaml for %s: %w", cb.Reference, err) } } diff --git a/pkg/cache/cached_bundle.go b/pkg/cache/cached_bundle.go index ff0e09828..88544e2f4 100644 --- a/pkg/cache/cached_bundle.go +++ b/pkg/cache/cached_bundle.go @@ -4,6 +4,7 @@ import ( "crypto/md5" "encoding/hex" "encoding/json" + "fmt" "path/filepath" "get.porter.sh/porter/pkg/cnab" @@ -11,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/encoding" "get.porter.sh/porter/pkg/portercontext" "github.com/cnabio/cnab-to-oci/relocation" - "github.com/pkg/errors" ) // CachedBundle represents a bundle pulled from a registry that has been cached to @@ -73,7 +73,7 @@ func (cb *CachedBundle) Load(cxt *portercontext.Context) (bool, error) { metaPath := cb.BuildMetadataPath() metaExists, err := cxt.FileSystem.Exists(metaPath) if err != nil { - return false, errors.Wrapf(err, "unable to access bundle metadata %s at %s", cb.Reference, metaPath) + return false, fmt.Errorf("unable to access bundle metadata %s at %s: %w", cb.Reference, metaPath, err) } if !metaExists { // consider this a miss, recache with the metadata @@ -82,7 +82,7 @@ func (cb *CachedBundle) Load(cxt *portercontext.Context) (bool, error) { var meta Metadata err = encoding.UnmarshalFile(cxt.FileSystem, metaPath, &meta) if err != nil { - return false, errors.Wrapf(err, "unable to parse cached bundle metadata %s at %s", cb.Reference, metaPath) + return false, fmt.Errorf("unable to parse cached bundle metadata %s at %s: %w", cb.Reference, metaPath, err) } cb.Digest = meta.Digest @@ -90,7 +90,7 @@ func (cb *CachedBundle) Load(cxt *portercontext.Context) (bool, error) { reloPath := cb.BuildRelocationFilePath() reloExists, err := cxt.FileSystem.Exists(reloPath) if err != nil { - return true, errors.Wrapf(err, "unable to read relocation mapping %s at %s", cb.Reference, reloPath) + return true, fmt.Errorf("unable to read relocation mapping %s at %s: %w", cb.Reference, reloPath, err) } if reloExists { cb.RelocationFilePath = reloPath @@ -100,7 +100,7 @@ func (cb *CachedBundle) Load(cxt *portercontext.Context) (bool, error) { manifestPath := cb.BuildManifestPath() manifestExists, err := cxt.FileSystem.Exists(manifestPath) if err != nil { - return true, errors.Wrapf(err, "unable to read manifest %s at %s", cb.Reference, manifestPath) + return true, fmt.Errorf("unable to read manifest %s at %s: %w", cb.Reference, manifestPath, err) } if manifestExists { cb.ManifestPath = manifestPath @@ -108,20 +108,20 @@ func (cb *CachedBundle) Load(cxt *portercontext.Context) (bool, error) { bun, err := cnab.LoadBundle(cxt, cb.BundlePath) if err != nil { - return true, errors.Wrapf(err, "unable to parse cached bundle file at %s", cb.BundlePath) + return true, fmt.Errorf("unable to parse cached bundle file at %s: %w", cb.BundlePath, err) } cb.Definition = bun if cb.RelocationFilePath != "" { data, err := cxt.FileSystem.ReadFile(cb.RelocationFilePath) if err != nil { - return true, errors.Wrapf(err, "unable to read cached relocation file at %s", cb.RelocationFilePath) + return true, fmt.Errorf("unable to read cached relocation file at %s: %w", cb.RelocationFilePath, err) } reloMap := relocation.ImageRelocationMap{} err = json.Unmarshal(data, &reloMap) if err != nil { - return true, errors.Wrapf(err, "unable to parse cached relocation file at %s", cb.RelocationFilePath) + return true, fmt.Errorf("unable to parse cached relocation file at %s: %w", cb.RelocationFilePath, err) } cb.RelocationMap = reloMap } diff --git a/pkg/cli/config.go b/pkg/cli/config.go index f7ce91413..dda1954a2 100644 --- a/pkg/cli/config.go +++ b/pkg/cli/config.go @@ -5,7 +5,6 @@ import ( "strings" "get.porter.sh/porter/pkg/config" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -82,11 +81,11 @@ func getViperValue(flags *pflag.FlagSet, f *pflag.Flag) interface{} { case "stringArray": out, err = flags.GetStringArray(f.Name) default: - panic(errors.Errorf("unsupported type for conversion between flag %s and viper configuration: %T", f.Name, flagType)) + panic(fmt.Errorf("unsupported type for conversion between flag %s and viper configuration: %T", f.Name, flagType)) } if err != nil { - panic(errors.Wrapf(err, "error parsing config key %s as %T", f.Name, flagType)) + panic(fmt.Errorf("error parsing config key %s as %T: %w", f.Name, flagType, err)) } return out diff --git a/pkg/cnab/cnab-to-oci/registry.go b/pkg/cnab/cnab-to-oci/registry.go index 2999124a4..b25f7bce5 100644 --- a/pkg/cnab/cnab-to-oci/registry.go +++ b/pkg/cnab/cnab-to-oci/registry.go @@ -20,7 +20,6 @@ import ( "github.com/docker/docker/pkg/term" "github.com/google/go-containerregistry/pkg/crane" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) // ErrNoContentDigest represents an error due to an image not having a @@ -65,7 +64,7 @@ func (r *Registry) PullBundle(ref cnab.OCIReference, insecureRegistry bool) (cna bun, reloMap, digest, err := remotes.Pull(context.Background(), ref.Named, r.createResolver(insecureRegistries)) if err != nil { - return cnab.BundleReference{}, errors.Wrap(err, "unable to pull bundle") + return cnab.BundleReference{}, fmt.Errorf("unable to pull bundle: %w", err) } invocationImage := bun.InvocationImages[0] @@ -101,13 +100,13 @@ func (r *Registry) PushBundle(ctx context.Context, bundleRef cnab.BundleReferenc } rm, err := remotes.FixupBundle(context.Background(), &bundleRef.Definition.Bundle, bundleRef.Reference.Named, resolver, remotes.WithEventCallback(r.displayEvent), remotes.WithAutoBundleUpdate(), remotes.WithRelocationMap(bundleRef.RelocationMap)) if err != nil { - return cnab.BundleReference{}, log.Error(errors.Wrap(err, "error preparing the bundle with cnab-to-oci before pushing")) + return cnab.BundleReference{}, log.Error(fmt.Errorf("error preparing the bundle with cnab-to-oci before pushing: %w", err)) } bundleRef.RelocationMap = rm d, err := remotes.Push(ctx, &bundleRef.Definition.Bundle, rm, bundleRef.Reference.Named, resolver, true) if err != nil { - return cnab.BundleReference{}, log.Error(errors.Wrapf(err, "error pushing the bundle to %s", bundleRef.Reference)) + return cnab.BundleReference{}, log.Error(fmt.Errorf("error pushing the bundle to %s: %w", bundleRef.Reference, err)) } bundleRef.Digest = d.Digest @@ -148,7 +147,7 @@ func (r *Registry) PushInvocationImage(ctx context.Context, invocationImage stri fmt.Fprintln(r.Out, "Pushing CNAB invocation image...") pushResponse, err := cli.Client().ImagePush(ctx, invocationImage, options) if err != nil { - return "", errors.Wrap(err, "docker push failed") + return "", fmt.Errorf("docker push failed: %w", err) } defer pushResponse.Close() @@ -159,13 +158,13 @@ func (r *Registry) PushInvocationImage(ctx context.Context, invocationImage stri err = jsonmessage.DisplayJSONMessagesStream(pushResponse, r.Out, termFd, isTerm, nil) if err != nil { if strings.HasPrefix(err.Error(), "denied") { - return "", errors.Wrap(err, "docker push authentication failed") + return "", fmt.Errorf("docker push authentication failed: %w", err) } - return "", errors.Wrap(err, "failed to stream docker push stdout") + return "", fmt.Errorf("failed to stream docker push stdout: %w", err) } dist, err := cli.Client().DistributionInspect(ctx, invocationImage, encodedAuth) if err != nil { - return "", errors.Wrap(err, "unable to inspect docker image") + return "", fmt.Errorf("unable to inspect docker image: %w", err) } return dist.Descriptor.Digest, nil } @@ -197,7 +196,7 @@ func (r *Registry) IsImageCached(ctx context.Context, invocationImage string) (b imageSummaries, err := cli.Client().ImageList(ctx, imageListOpts) if err != nil { - return false, errors.Wrapf(err, "could not list images") + return false, fmt.Errorf("could not list images: %w", err) } if len(imageSummaries) == 0 { diff --git a/pkg/cnab/config-adapter/adapter_test.go b/pkg/cnab/config-adapter/adapter_test.go index 13ee026a2..29f4de865 100644 --- a/pkg/cnab/config-adapter/adapter_test.go +++ b/pkg/cnab/config-adapter/adapter_test.go @@ -15,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "github.com/cnabio/cnab-go/bundle" "github.com/cnabio/cnab-go/bundle/definition" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -922,5 +921,5 @@ func getMaintainerByName(source []bundle.Maintainer, name string) (bundle.Mainta return m, nil } } - return bundle.Maintainer{}, errors.New(fmt.Sprintf("Could not find maintainer with name '%s'", name)) + return bundle.Maintainer{}, fmt.Errorf("Could not find maintainer with name '%s'", name) } diff --git a/pkg/cnab/config-adapter/stamp.go b/pkg/cnab/config-adapter/stamp.go index 7c5279332..d6f17c510 100644 --- a/pkg/cnab/config-adapter/stamp.go +++ b/pkg/cnab/config-adapter/stamp.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "get.porter.sh/porter/pkg" @@ -14,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/manifest" "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) // Stamp contains Porter specific metadata about a bundle that we can place @@ -46,7 +46,7 @@ func (s Stamp) DecodeManifest() ([]byte, error) { resultB, err := base64.StdEncoding.DecodeString(s.EncodedManifest) if err != nil { - return nil, errors.Wrapf(err, "could not base64 decode the manifest in the stamp\n%s", s.EncodedManifest) + return nil, fmt.Errorf("could not base64 decode the manifest in the stamp\n%s: %w", s.EncodedManifest, err) } return resultB, nil @@ -59,7 +59,11 @@ func (s Stamp) WriteManifest(cxt *portercontext.Context, path string) error { } err = cxt.FileSystem.WriteFile(path, manifestB, pkg.FileModeWritable) - return errors.Wrapf(err, "could not save decoded manifest to %s", path) + if err != nil { + return fmt.Errorf("could not save decoded manifest to %s: %w", path, err) + } + + return nil } // MixinRecord contains information about a mixin used in a bundle @@ -107,12 +111,12 @@ func (c *ManifestConverter) GenerateStamp(ctx context.Context) (Stamp, error) { func (c *ManifestConverter) DigestManifest() (string, error) { if exists, _ := c.config.FileSystem.Exists(c.Manifest.ManifestPath); !exists { - return "", errors.Errorf("the specified porter configuration file %s does not exist", c.Manifest.ManifestPath) + return "", fmt.Errorf("the specified porter configuration file %s does not exist", c.Manifest.ManifestPath) } data, err := c.config.FileSystem.ReadFile(c.Manifest.ManifestPath) if err != nil { - return "", errors.Wrapf(err, "could not read manifest at %q", c.Manifest.ManifestPath) + return "", fmt.Errorf("could not read manifest at %q: %w", c.Manifest.ManifestPath, err) } v := pkg.Version @@ -131,18 +135,18 @@ func LoadStamp(bun cnab.ExtendedBundle) (Stamp, error) { // TODO(carolynvs): can we simplify some of this by using the extended bundle? data, ok := bun.Custom[config.CustomPorterKey] if !ok { - return Stamp{}, errors.Errorf("porter stamp (custom.%s) was not present on the bundle", config.CustomPorterKey) + return Stamp{}, fmt.Errorf("porter stamp (custom.%s) was not present on the bundle", config.CustomPorterKey) } dataB, err := json.Marshal(data) if err != nil { - return Stamp{}, errors.Wrapf(err, "could not marshal the porter stamp %q", string(dataB)) + return Stamp{}, fmt.Errorf("could not marshal the porter stamp %q: %w", string(dataB), err) } stamp := Stamp{} err = json.Unmarshal(dataB, &stamp) if err != nil { - return Stamp{}, errors.Wrapf(err, "could not unmarshal the porter stamp %q", string(dataB)) + return Stamp{}, fmt.Errorf("could not unmarshal the porter stamp %q: %w", string(dataB), err) } return stamp, nil diff --git a/pkg/cnab/dependencies.go b/pkg/cnab/dependencies.go index 6fc0373fe..e1fbe6925 100644 --- a/pkg/cnab/dependencies.go +++ b/pkg/cnab/dependencies.go @@ -2,9 +2,8 @@ package cnab import ( "encoding/json" + "errors" "fmt" - - "github.com/pkg/errors" ) const ( @@ -88,18 +87,18 @@ func DependencyReader(bun ExtendedBundle) (interface{}, error) { func (b ExtendedBundle) DependencyReader() (interface{}, error) { data, ok := b.Custom[DependenciesExtensionKey] if !ok { - return nil, errors.Errorf("attempted to read dependencies from bundle but none are defined") + return nil, errors.New("attempted to read dependencies from bundle but none are defined") } dataB, err := json.Marshal(data) if err != nil { - return nil, errors.Wrapf(err, "could not marshal the untyped dependencies extension data %q", string(dataB)) + return nil, fmt.Errorf("could not marshal the untyped dependencies extension data %q: %w", string(dataB), err) } deps := Dependencies{} err = json.Unmarshal(dataB, &deps) if err != nil { - return nil, errors.Wrapf(err, "could not unmarshal the dependencies extension %q", string(dataB)) + return nil, fmt.Errorf("could not unmarshal the dependencies extension %q: %w", string(dataB), err) } return deps, nil diff --git a/pkg/cnab/docker.go b/pkg/cnab/docker.go index 68aba1f74..8b4a67b49 100644 --- a/pkg/cnab/docker.go +++ b/pkg/cnab/docker.go @@ -2,8 +2,8 @@ package cnab import ( "encoding/json" - - "github.com/pkg/errors" + "errors" + "fmt" ) const ( @@ -49,15 +49,15 @@ func (b ExtendedBundle) DockerExtensionReader() (interface{}, error) { dataB, err := json.Marshal(data) if err != nil { - return nil, errors.Wrapf(err, "could not marshal the untyped %q extension data %q", - DockerExtensionKey, string(dataB)) + return nil, fmt.Errorf("could not marshal the untyped %q extension data %q: %w", + DockerExtensionKey, string(dataB), err) } dha := Docker{} err = json.Unmarshal(dataB, &dha) if err != nil { - return nil, errors.Wrapf(err, "could not unmarshal the %q extension %q", - DockerExtensionKey, string(dataB)) + return nil, fmt.Errorf("could not unmarshal the %q extension %q: %w", + DockerExtensionKey, string(dataB), err) } return dha, nil @@ -70,7 +70,7 @@ func (e ProcessedExtensions) GetDocker() (dockerExt Docker, dockerRequired bool, dockerExt, ok := ext.(Docker) if !ok && extensionRequired { - return Docker{}, extensionRequired, errors.Errorf("unable to parse Docker extension config: %+v", dockerExt) + return Docker{}, extensionRequired, fmt.Errorf("unable to parse Docker extension config: %+v", dockerExt) } return dockerExt, extensionRequired, nil diff --git a/pkg/cnab/drivers/drivers.go b/pkg/cnab/drivers/drivers.go index 71b64a9a3..5ad99c00d 100644 --- a/pkg/cnab/drivers/drivers.go +++ b/pkg/cnab/drivers/drivers.go @@ -1,13 +1,14 @@ package drivers import ( + "fmt" + "get.porter.sh/porter/pkg/portercontext" "github.com/cnabio/cnab-go/driver" "github.com/cnabio/cnab-go/driver/command" "github.com/cnabio/cnab-go/driver/debug" "github.com/cnabio/cnab-go/driver/docker" "github.com/cnabio/cnab-go/driver/kubernetes" - "github.com/pkg/errors" ) // LookupDriver creates a driver by name. @@ -30,6 +31,6 @@ func LookupDriver(cxt *portercontext.Context, name string) (driver.Driver, error return d, nil } - return nil, errors.Errorf("unsupported driver or driver not found in PATH: %s", name) + return nil, fmt.Errorf("unsupported driver or driver not found in PATH: %s", name) } } diff --git a/pkg/cnab/extended_bundle.go b/pkg/cnab/extended_bundle.go index 04d3a13b1..a72069527 100644 --- a/pkg/cnab/extended_bundle.go +++ b/pkg/cnab/extended_bundle.go @@ -8,7 +8,6 @@ import ( "github.com/cnabio/cnab-go/bundle" "github.com/cnabio/cnab-go/bundle/definition" "github.com/cnabio/cnab-go/claim" - "github.com/pkg/errors" ) // ExtendedBundle is a bundle that has typed access to extensions declared in the bundle, @@ -26,12 +25,12 @@ func NewBundle(bundle bundle.Bundle) ExtendedBundle { func LoadBundle(c *portercontext.Context, bundleFile string) (ExtendedBundle, error) { bunD, err := c.FileSystem.ReadFile(bundleFile) if err != nil { - return ExtendedBundle{}, errors.Wrapf(err, "cannot read bundle at %s", bundleFile) + return ExtendedBundle{}, fmt.Errorf("cannot read bundle at %s: %w", bundleFile, err) } bun, err := bundle.Unmarshal(bunD) if err != nil { - return ExtendedBundle{}, errors.Wrapf(err, "cannot load bundle from\n%s at %s", string(bunD), bundleFile) + return ExtendedBundle{}, fmt.Errorf("cannot load bundle from\n%s at %s: %w", string(bunD), bundleFile, err) } return NewBundle(*bun), nil @@ -114,7 +113,7 @@ func (b ExtendedBundle) ConvertParameterValue(key string, value interface{}) (in case string: typedValue, err := def.ConvertValue(t) if err != nil { - return nil, errors.Wrapf(err, "unable to convert parameter's %s value %s to the destination parameter type %s", key, value, def.Type) + return nil, fmt.Errorf("unable to convert parameter's %s value %s to the destination parameter type %s: %w", key, value, def.Type, err) } return typedValue, nil case json.Number: @@ -152,5 +151,9 @@ func WriteParameterToString(paramName string, value interface{}) (string, error) } contents, err := json.Marshal(value) - return string(contents), errors.Wrapf(err, "could not marshal the value for parameter %s to a json string: %#v", paramName, value) + if err != nil { + return "", fmt.Errorf("could not marshal the value for parameter %s to a json string %#v: %w", paramName, value, err) + } + + return string(contents), nil } diff --git a/pkg/cnab/parameter_sources.go b/pkg/cnab/parameter_sources.go index cf50d5db3..10f589920 100644 --- a/pkg/cnab/parameter_sources.go +++ b/pkg/cnab/parameter_sources.go @@ -2,8 +2,8 @@ package cnab import ( "encoding/json" - - "github.com/pkg/errors" + "errors" + "fmt" ) const ( @@ -109,7 +109,7 @@ func (m *ParameterSourceMap) UnmarshalJSON(data []byte) error { for sourceKey, sourceDef := range rawMap { rawDef, err := json.Marshal(sourceDef) if err != nil { - return errors.Wrapf(err, "error re-marshaling parameter source definition") + return fmt.Errorf("error re-marshaling parameter source definition: %w", err) } switch sourceKey { @@ -117,18 +117,18 @@ func (m *ParameterSourceMap) UnmarshalJSON(data []byte) error { var output OutputParameterSource err := json.Unmarshal(rawDef, &output) if err != nil { - return errors.Wrapf(err, "invalid parameter source definition for key %s", sourceKey) + return fmt.Errorf("invalid parameter source definition for key %s: %w", sourceKey, err) } (*m)[ParameterSourceTypeOutput] = output case ParameterSourceTypeDependencyOutput: var depOutput DependencyOutputParameterSource err := json.Unmarshal(rawDef, &depOutput) if err != nil { - return errors.Wrapf(err, "invalid parameter source definition for key %s", sourceKey) + return fmt.Errorf("invalid parameter source definition for key %s: %w", sourceKey, err) } (*m)[ParameterSourceTypeDependencyOutput] = depOutput default: - return errors.Errorf("unsupported parameter source key %s", sourceKey) + return fmt.Errorf("unsupported parameter source key %s", sourceKey) } } @@ -181,20 +181,20 @@ func ParameterSourcesReader(bun ExtendedBundle) (interface{}, error) { func (b ExtendedBundle) ParameterSourcesReader() (interface{}, error) { data, ok := b.Custom[ParameterSourcesExtensionKey] if !ok { - return nil, errors.Errorf("attempted to read parameter sources from bundle but none are defined") + return nil, errors.New("attempted to read parameter sources from bundle but none are defined") } dataB, err := json.Marshal(data) if err != nil { - return nil, errors.Wrapf(err, "could not marshal the untyped %q extension data %q", - ParameterSourcesExtensionKey, string(dataB)) + return nil, fmt.Errorf("could not marshal the untyped %q extension data %q: %w", + ParameterSourcesExtensionKey, string(dataB), err) } ps := ParameterSources{} err = json.Unmarshal(dataB, &ps) if err != nil { - return nil, errors.Wrapf(err, "could not unmarshal the %q extension %q", - ParameterSourcesExtensionKey, string(dataB)) + return nil, fmt.Errorf("could not unmarshal the %q extension %q: %w", + ParameterSourcesExtensionKey, string(dataB), err) } return ps, nil @@ -212,7 +212,7 @@ func (e ProcessedExtensions) GetParameterSources() (ParameterSources, bool, erro ext, ok := rawExt.(ParameterSources) if !ok && required { - return ParameterSources{}, required, errors.Errorf("unable to parse Parameter Sources extension config: %+v", rawExt) + return ParameterSources{}, required, fmt.Errorf("unable to parse Parameter Sources extension config: %+v", rawExt) } return ext, required, nil diff --git a/pkg/cnab/provider/action.go b/pkg/cnab/provider/action.go index dce41167b..9e3c603e4 100644 --- a/pkg/cnab/provider/action.go +++ b/pkg/cnab/provider/action.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "sort" @@ -15,7 +16,6 @@ import ( cnabaction "github.com/cnabio/cnab-go/action" "github.com/cnabio/cnab-go/driver" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" ) @@ -75,7 +75,7 @@ func (r *Runtime) AddFiles(ctx context.Context, args ActionArguments) cnabaction if err == nil { claimBytes, err := json.Marshal(claim) if err != nil { - return errors.Wrapf(err, "could not marshal claim %s for installation %s", claim.ID, args.Installation) + return fmt.Errorf("could not marshal claim %s for installation %s: %w", claim.ID, args.Installation, err) } op.Files[config.ClaimFilepath] = string(claimBytes) } @@ -99,7 +99,7 @@ func (r *Runtime) AddRelocation(args ActionArguments) cnabaction.OperationConfig if len(args.BundleReference.RelocationMap) > 0 { b, err := json.MarshalIndent(args.BundleReference.RelocationMap, "", " ") if err != nil { - return errors.Wrapf(err, "error marshaling relocation mapping file") + return fmt.Errorf("error marshaling relocation mapping file: %w", err) } op.Files["/cnab/app/relocation-mapping.json"] = string(b) @@ -146,18 +146,18 @@ func (r *Runtime) Execute(ctx context.Context, args ActionArguments) error { // Validate the action if _, err := b.GetAction(currentRun.Action); err != nil { - return log.Error(errors.Wrapf(err, "invalid action '%s' specified for bundle %s", currentRun.Action, b.Name)) + return log.Error(fmt.Errorf("invalid action '%s' specified for bundle %s: %w", currentRun.Action, b.Name, err)) } creds, err := r.loadCredentials(ctx, b, args) if err != nil { - return log.Error(errors.Wrap(err, "could not load credentials")) + return log.Error(fmt.Errorf("not load credentials: %w", err)) } log.Debugf("Using runtime driver %s\n", args.Driver) driver, err := r.newDriver(args.Driver, args) if err != nil { - return log.Error(errors.Wrap(err, "unable to instantiate driver")) + return log.Error(fmt.Errorf("unable to instantiate driver: %w", err)) } a := cnabaction.New(driver) @@ -166,7 +166,7 @@ func (r *Runtime) Execute(ctx context.Context, args ActionArguments) error { if currentRun.ShouldRecord() { err = r.SaveRun(ctx, args.Installation, currentRun, cnab.StatusRunning) if err != nil { - return log.Error(errors.Wrap(err, "could not save the pending action's status, the bundle was not executed")) + return log.Error(fmt.Errorf("could not save the pending action's status, the bundle was not executed: %w", err)) } } @@ -177,12 +177,16 @@ func (r *Runtime) Execute(ctx context.Context, args ActionArguments) error { if currentRun.ShouldRecord() { if err != nil { err = r.appendFailedResult(ctx, err, currentRun) - return log.Error(errors.Wrapf(err, "failed to record that %s for installation %s failed", args.Action, args.Installation.Name)) + return log.Error(fmt.Errorf("failed to record that %s for installation %s failed: %w", args.Action, args.Installation.Name, err)) } return r.SaveOperationResult(ctx, opResult, args.Installation, currentRun, currentRun.NewResultFrom(result)) - } else { - return log.Error(errors.Wrapf(err, "execution of %s for installation %s failed", args.Action, args.Installation.Name)) } + + if err != nil { + return log.Error(fmt.Errorf("execution of %s for installation %s failed: %w", args.Action, args.Installation.Name, err)) + } + + return nil } } @@ -259,24 +263,24 @@ func (r *Runtime) SaveOperationResult(ctx context.Context, opResult driver.Opera err := r.installations.InsertResult(ctx, result) if err != nil { - bigerr = multierror.Append(bigerr, errors.Wrapf(err, "error adding %s result for %s run of installation %s\n%#v", result.Status, run.Action, installation, result)) + bigerr = multierror.Append(bigerr, fmt.Errorf("error adding %s result for %s run of installation %s\n%#v: %w", result.Status, run.Action, installation, result, err)) } installation.ApplyResult(run, result) err = r.installations.UpdateInstallation(ctx, installation) if err != nil { - bigerr = multierror.Append(bigerr, errors.Wrapf(err, "error updating installation record for %s\n%#v", installation, installation)) + bigerr = multierror.Append(bigerr, fmt.Errorf("error updating installation record for %s\n%#v: %w", installation, installation, err)) } for outputName, outputValue := range opResult.Outputs { output := result.NewOutput(outputName, []byte(outputValue)) output, err = r.sanitizer.CleanOutput(ctx, output, cnab.ExtendedBundle{Bundle: run.Bundle}) if err != nil { - bigerr = multierror.Append(bigerr, errors.Wrapf(err, "error sanitizing sensitive %s output for %s run of installation %s\n%#v", output.Name, run.Action, installation, output)) + bigerr = multierror.Append(bigerr, fmt.Errorf("error sanitizing sensitive %s output for %s run of installation %s\n%#v: %w", output.Name, run.Action, installation, output, err)) } err = r.installations.InsertOutput(ctx, output) if err != nil { - bigerr = multierror.Append(bigerr, errors.Wrapf(err, "error adding %s output for %s run of installation %s\n%#v", output.Name, run.Action, installation, output)) + bigerr = multierror.Append(bigerr, fmt.Errorf("error adding %s output for %s run of installation %s\n%#v: %w", output.Name, run.Action, installation, output, err)) } } diff --git a/pkg/cnab/provider/bundle.go b/pkg/cnab/provider/bundle.go index a89db023b..44e7ac656 100644 --- a/pkg/cnab/provider/bundle.go +++ b/pkg/cnab/provider/bundle.go @@ -1,8 +1,9 @@ package cnabprovider import ( + "fmt" + "get.porter.sh/porter/pkg/cnab" - "github.com/pkg/errors" ) func (r *Runtime) LoadBundle(bundleFile string) (cnab.ExtendedBundle, error) { @@ -21,7 +22,7 @@ func (r *Runtime) ProcessBundleFromFile(bundleFile string) (cnab.ExtendedBundle, func (r *Runtime) ProcessBundle(b cnab.ExtendedBundle) (cnab.ExtendedBundle, error) { err := b.Validate() if err != nil { - return b, errors.Wrap(err, "invalid bundle") + return b, fmt.Errorf("invalid bundle: %w", err) } return b, r.ProcessRequiredExtensions(b) diff --git a/pkg/cnab/provider/docker_linux.go b/pkg/cnab/provider/docker_linux.go index b6eb3cb20..73934e3a8 100644 --- a/pkg/cnab/provider/docker_linux.go +++ b/pkg/cnab/provider/docker_linux.go @@ -2,26 +2,26 @@ package cnabprovider import ( "context" + "fmt" "os/exec" "strings" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/mount" - "github.com/pkg/errors" ) func (r *Runtime) getDockerGroupId() (string, error) { resp, err := r.NewCommand(context.Background(), "getent", "group", "docker").Output() if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { - return "", errors.Errorf("error querying for the docker group id: %s", string(exitErr.Stderr)) + return "", fmt.Errorf("error querying for the docker group id: %s", string(exitErr.Stderr)) } - return "", errors.Wrapf(err, "error querying for the docker group id") + return "", fmt.Errorf("error querying for the docker group id: %w", err) } output := strings.TrimSpace(string(resp)) parts := strings.Split(output, ":") if len(parts) < 3 { - return "", errors.Errorf("could not determine the id of the docker group, unexpected output returned from 'getent group docker': '%s'", output) + return "", fmt.Errorf("could not determine the id of the docker group, unexpected output returned from 'getent group docker': '%s'", output) } // The command should return GROUP:x:GID diff --git a/pkg/cnab/provider/driver.go b/pkg/cnab/provider/driver.go index 5d9a2f14e..71a03a5fe 100644 --- a/pkg/cnab/provider/driver.go +++ b/pkg/cnab/provider/driver.go @@ -1,12 +1,13 @@ package cnabprovider import ( + "fmt" + "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/cnab/drivers" "github.com/cnabio/cnab-go/driver" "github.com/cnabio/cnab-go/driver/docker" "github.com/docker/docker/api/types/container" - "github.com/pkg/errors" ) const ( @@ -29,13 +30,13 @@ func (r *Runtime) newDriver(driverName string, args ActionArguments) (driver.Dri if args.AllowDockerHostAccess { if driverName != DriverNameDocker { - return nil, errors.Errorf("allow-docker-host-access was enabled, but the driver is %s", driverName) + return nil, fmt.Errorf("allow-docker-host-access was enabled, but the driver is %s", driverName) } driverImpl, err = r.dockerDriverWithHostAccess(dockerExt) } else { if dockerRequired { - return nil, errors.Errorf("extension %q is required but allow-docker-host-access was not enabled", + return nil, fmt.Errorf("extension %q is required but allow-docker-host-access was not enabled", cnab.DockerExtensionKey) } driverImpl, err = drivers.LookupDriver(r.Context, driverName) @@ -63,7 +64,7 @@ func (r *Runtime) dockerDriverWithHostAccess(config cnab.Docker) (driver.Driver, const dockerSock = "/var/run/docker.sock" if exists, _ := r.FileSystem.Exists(dockerSock); !exists { - return nil, errors.Errorf("allow-docker-host-access was specified but could not detect a local docker daemon running by checking for %s", dockerSock) + return nil, fmt.Errorf("allow-docker-host-access was specified but could not detect a local docker daemon running by checking for %s", dockerSock) } d := &docker.Driver{} diff --git a/pkg/cnab/provider/runtime.go b/pkg/cnab/provider/runtime.go index 095382d59..e26a5f993 100644 --- a/pkg/cnab/provider/runtime.go +++ b/pkg/cnab/provider/runtime.go @@ -1,11 +1,12 @@ package cnabprovider import ( + "fmt" + "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/secrets" "get.porter.sh/porter/pkg/storage" - "github.com/pkg/errors" ) var _ CNABProvider = &Runtime{} @@ -34,7 +35,7 @@ func NewRuntime(c *config.Config, installations storage.InstallationProvider, cr func (r *Runtime) ProcessRequiredExtensions(b cnab.ExtendedBundle) error { exts, err := b.ProcessRequiredExtensions() if err != nil { - return errors.Wrap(err, "unable to process required extensions") + return fmt.Errorf("unable to process required extensions: %w", err) } r.Extensions = exts return nil diff --git a/pkg/cnab/reference.go b/pkg/cnab/reference.go index 4a1e3f8a6..dff7d77d7 100644 --- a/pkg/cnab/reference.go +++ b/pkg/cnab/reference.go @@ -2,6 +2,7 @@ package cnab import ( "encoding/json" + "errors" "fmt" "strings" @@ -9,7 +10,6 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/registry" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) // ParseOCIReference parses the specified value as an OCIReference. @@ -17,7 +17,7 @@ import ( func ParseOCIReference(value string) (OCIReference, error) { named, err := reference.ParseNormalizedNamed(value) if err != nil { - return OCIReference{}, errors.Wrapf(err, "invalid reference format %s", value) + return OCIReference{}, fmt.Errorf("invalid reference format %s: %w", value, err) } ref := OCIReference{Named: named} @@ -192,7 +192,7 @@ func (r OCIReference) WithVersion(version string) (OCIReference, error) { v, err := semver.NewVersion(version) if err != nil { - return OCIReference{}, errors.Wrapf(err, "invalid bundle version specified %s", version) + return OCIReference{}, fmt.Errorf("invalid bundle version specified %s: %w", version, err) } newRef, err := reference.WithTag(r.Named, "v"+v.String()) diff --git a/pkg/cnab/required.go b/pkg/cnab/required.go index b9a15bac9..196727097 100644 --- a/pkg/cnab/required.go +++ b/pkg/cnab/required.go @@ -1,8 +1,6 @@ package cnab -import ( - "github.com/pkg/errors" -) +import "fmt" // RequiredExtension represents a required extension that is known and supported by Porter type RequiredExtension struct { @@ -43,7 +41,7 @@ func (b ExtendedBundle) ProcessRequiredExtensions() (ProcessedExtensions, error) raw, err := supportedExtension.Reader(b) if err != nil { - return processed, errors.Wrapf(err, "unable to process extension: %s", reqExt) + return processed, fmt.Errorf("unable to process extension: %s: %w", reqExt, err) } processed[supportedExtension.Key] = raw @@ -63,5 +61,5 @@ func GetSupportedExtension(e string) (*RequiredExtension, error) { return &ext, nil } } - return nil, errors.Errorf("unsupported required extension: %s", e) + return nil, fmt.Errorf("unsupported required extension: %s", e) } diff --git a/pkg/cnab/solver.go b/pkg/cnab/solver.go index 4ef78775e..6b6f9952e 100644 --- a/pkg/cnab/solver.go +++ b/pkg/cnab/solver.go @@ -1,11 +1,11 @@ package cnab import ( + "fmt" "sort" "github.com/Masterminds/semver/v3" "github.com/google/go-containerregistry/pkg/crane" - "github.com/pkg/errors" ) type DependencyLock struct { @@ -27,7 +27,7 @@ func (s *DependencySolver) ResolveDependencies(bun ExtendedBundle) ([]Dependency orderedDeps := rawDeps.ListBySequence() if err != nil { - return nil, errors.Wrapf(err, "error executing dependencies for %s", bun.Name) + return nil, fmt.Errorf("error executing dependencies for %s: %w", bun.Name, err) } q := make([]DependencyLock, 0, len(orderedDeps)) @@ -51,7 +51,7 @@ func (s *DependencySolver) ResolveDependencies(bun ExtendedBundle) ([]Dependency func (s *DependencySolver) ResolveVersion(name string, dep Dependency) (OCIReference, error) { ref, err := ParseOCIReference(dep.Bundle) if err != nil { - return OCIReference{}, errors.Wrapf(err, "error parsing dependency (%s) bundle %q as OCI reference", name, dep.Bundle) + return OCIReference{}, fmt.Errorf("error parsing dependency (%s) bundle %q as OCI reference: %w", name, dep.Bundle, err) } // Here is where we could split out this logic into multiple strategy funcs / structs if necessary @@ -69,13 +69,13 @@ func (s *DependencySolver) ResolveVersion(name string, dep Dependency) (OCIRefer return ref.WithTag(tag) } - return OCIReference{}, errors.Errorf("not implemented: dependency version range specified for %s", name) + return OCIReference{}, fmt.Errorf("not implemented: dependency version range specified for %s: %w", name, err) } func (s *DependencySolver) determineDefaultTag(dep Dependency) (string, error) { tags, err := crane.ListTags(dep.Bundle) if err != nil { - return "", errors.Wrapf(err, "error listing tags for %s", dep.Bundle) + return "", fmt.Errorf("error listing tags for %s: %w", dep.Bundle, err) } allowPrereleases := false @@ -104,7 +104,7 @@ func (s *DependencySolver) determineDefaultTag(dep Dependency) (string, error) { if hasLatest { return "latest", nil } else { - return "", errors.Errorf("no tag was specified for %s and none of the tags defined in the registry meet the criteria: semver formatted or 'latest'", dep.Bundle) + return "", fmt.Errorf("no tag was specified for %s and none of the tags defined in the registry meet the criteria: semver formatted or 'latest'", dep.Bundle) } } diff --git a/pkg/config/config.go b/pkg/config/config.go index 5b53b4935..a4f7be94c 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -2,6 +2,7 @@ package config import ( "context" + "errors" "fmt" "os" "path/filepath" @@ -12,7 +13,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/schema" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "github.com/spf13/viper" "go.opentelemetry.io/otel/attribute" ) @@ -163,7 +163,7 @@ func (c *Config) GetStorage(name string) (StoragePlugin, error) { } } - return StoragePlugin{}, errors.Errorf("store '%s' not defined", name) + return StoragePlugin{}, fmt.Errorf("store '%s' not defined", name) } func (c *Config) GetSecretsPlugin(name string) (SecretsPlugin, error) { @@ -191,7 +191,7 @@ func (c *Config) GetHomeDir() (string, error) { if home == "" { userHome, err := os.UserHomeDir() if err != nil { - return "", errors.Wrap(err, "could not get user home directory") + return "", fmt.Errorf("could not get user home directory: %w", err) } home = filepath.Join(userHome, ".porter") } @@ -227,13 +227,13 @@ func (c *Config) GetPorterPath() (string, error) { porterPath, err := getExecutable() if err != nil { - return "", errors.Wrap(err, "could not get path to the executing porter binary") + return "", fmt.Errorf("could not get path to the executing porter binary: %w", err) } // We try to resolve back to the original location hardPath, err := evalSymlinks(porterPath) if err != nil { // if we have trouble resolving symlinks, skip trying to help people who used symlinks - fmt.Fprintln(c.Err, errors.Wrapf(err, "WARNING could not resolve %s for symbolic links\n", porterPath)) + fmt.Fprintln(c.Err, fmt.Errorf("WARNING could not resolve %s for symbolic links\n: %w", porterPath, err)) } else if hardPath != porterPath { if c.Debug { fmt.Fprintf(c.Err, "Resolved porter binary from %s to %s\n", porterPath, hardPath) @@ -371,7 +371,7 @@ func (c *Config) loadFinalPass(ctx context.Context, resolveSecret func(ctx conte defer childLog.EndSpan() secretValue, err := resolveSecret(ctx, secretKey) if err != nil { - return childLog.Error(errors.Wrapf(err, "could not render config file because ${secret.%s} could not be resolved", secretKey)) + return childLog.Error(fmt.Errorf("could not render config file because ${secret.%s} could not be resolved: %w", secretKey, err)) } secrets[secretKey] = secretValue diff --git a/pkg/config/loader.go b/pkg/config/loader.go index f8e551dca..90200713e 100644 --- a/pkg/config/loader.go +++ b/pkg/config/loader.go @@ -3,13 +3,13 @@ package config import ( "bytes" "context" + "fmt" "sort" "strings" "get.porter.sh/porter/pkg/tracing" "github.com/osteele/liquid" "github.com/osteele/liquid/render" - "github.com/pkg/errors" "github.com/spf13/viper" "go.opentelemetry.io/otel/attribute" ) @@ -61,7 +61,7 @@ func LoadFromViper(viperCfg func(v *viper.Viper)) DataStoreLoaderFunc { // Initialize empty config err := v.SetDefaultsFrom(cfg.Data) if err != nil { - return log.Error(errors.Wrap(err, "error initializing configuration data")) + return log.Error(fmt.Errorf("error initializing configuration data: %w", err)) } if viperCfg != nil { @@ -78,7 +78,7 @@ func LoadFromViper(viperCfg func(v *viper.Viper)) DataStoreLoaderFunc { err = v.ReadInConfig() if err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); !ok { - return log.Error(errors.Wrap(err, "error reading config file")) + return log.Error(fmt.Errorf("error reading config file: %w", err)) } } } @@ -89,7 +89,7 @@ func LoadFromViper(viperCfg func(v *viper.Viper)) DataStoreLoaderFunc { cfgContents, err := cfg.FileSystem.ReadFile(cfgFile) if err != nil { - return log.Error(errors.Wrap(err, "error reading config file template")) + return log.Error(fmt.Errorf("error reading config file template: %w", err)) } // Render any template variables used in the config file @@ -97,12 +97,12 @@ func LoadFromViper(viperCfg func(v *viper.Viper)) DataStoreLoaderFunc { engine.Delims("${", "}", "${%", "%}") tmpl, err := engine.ParseTemplate(cfgContents) if err != nil { - return log.Error(errors.Wrapf(err, "error parsing config file as a liquid template:\n%s\n\n", cfgContents)) + return log.Error(fmt.Errorf("error parsing config file as a liquid template:\n%s\n\n: %w", cfgContents, err)) } finalCfg, err := tmpl.Render(templateData) if err != nil { - return log.Error(errors.Wrapf(err, "error rendering config file as a liquid template:\n%s\n\n", cfgContents)) + return log.Error(fmt.Errorf("error rendering config file as a liquid template:\n%s\n\n: %w", cfgContents, err)) } // Remember what variables are used in the template @@ -112,12 +112,12 @@ func LoadFromViper(viperCfg func(v *viper.Viper)) DataStoreLoaderFunc { } if err := v.ReadConfig(bytes.NewReader(finalCfg)); err != nil { - return log.Error(errors.Wrapf(err, "error loading configuration file")) + return log.Error(fmt.Errorf("error loading configuration file: %w", err)) } } if err = v.Unmarshal(&cfg.Data); err != nil { - log.Error(errors.Wrap(err, "error unmarshaling viper config as porter config")) + log.Error(fmt.Errorf("error unmarshaling viper config as porter config: %w", err)) } cfg.viper = v diff --git a/pkg/docs/generator.go b/pkg/docs/generator.go index 38a92520b..3d4d7d102 100644 --- a/pkg/docs/generator.go +++ b/pkg/docs/generator.go @@ -8,7 +8,6 @@ import ( "strings" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" ) @@ -27,10 +26,10 @@ func (o *DocsOptions) Validate(cxt *portercontext.Context) error { exists, err := cxt.FileSystem.Exists(o.Destination) if err != nil { - return errors.Wrapf(err, "error checking if --destination exists: %q", o.Destination) + return fmt.Errorf("error checking if --destination exists: %q: %w", o.Destination, err) } if !exists { - return errors.Errorf("--destination %q doesn't exist", o.Destination) + return fmt.Errorf("--destination %q doesn't exist", o.Destination) } return nil @@ -41,20 +40,20 @@ func GenerateCliDocs(opts *DocsOptions) error { err := doc.GenMarkdownTreeCustom(opts.RootCommand, opts.Destination, docfileHandler(), doclinkHandler()) if err != nil { - return errors.Wrap(err, "error generating the markdown documentation from the cli") + return fmt.Errorf("error generating the markdown documentation from the cli: %w", err) } // Strip off the leading porter_ from every file items, err := filepath.Glob(filepath.Join(opts.Destination, "porter_*.md")) if err != nil { - return errors.Wrapf(err, "unable to list generated cli docs directory %q", opts.Destination) + return fmt.Errorf("unable to list generated cli docs directory %q: %w", opts.Destination, err) } for _, i := range items { inew := strings.Replace(i, "porter_", "", -1) err := os.Rename(i, inew) if err != nil { - return errors.Wrapf(err, "unable to rename markdown file") + return fmt.Errorf("unable to rename markdown file: %w", err) } } return nil diff --git a/pkg/encoding/encoding.go b/pkg/encoding/encoding.go index 57b8e2c44..ac83175d9 100644 --- a/pkg/encoding/encoding.go +++ b/pkg/encoding/encoding.go @@ -3,13 +3,13 @@ package encoding import ( "bytes" "encoding/json" + "fmt" "path/filepath" "strings" "get.porter.sh/porter/pkg" "github.com/carolynvs/aferox" "github.com/pelletier/go-toml" - "github.com/pkg/errors" "gopkg.in/yaml.v3" ) @@ -63,7 +63,11 @@ func Marshal(format string, in interface{}) (data []byte, err error) { return nil, newUnsupportedFormatError(format) } - return data, errors.Wrapf(err, "error marshaling to %s", format) + if err != nil { + return nil, fmt.Errorf("error marshaling to %s: %w", format, err) + } + + return data, nil } // Unmarshal from the specified file into a struct. @@ -71,7 +75,7 @@ func Marshal(format string, in interface{}) (data []byte, err error) { func UnmarshalFile(fs aferox.Aferox, path string, out interface{}) error { data, err := fs.ReadFile(path) if err != nil { - return errors.Wrapf(err, "error reading file %s", path) + return fmt.Errorf("error reading file %s: %w", path, err) } format := strings.TrimPrefix(filepath.Ext(path), ".") return Unmarshal(format, data, out) @@ -108,5 +112,5 @@ func Unmarshal(format string, data []byte, out interface{}) error { } func newUnsupportedFormatError(format string) error { - return errors.Errorf("unsupported format %s. Supported formats are: yaml, json and toml.", format) + return fmt.Errorf("unsupported format %s. Supported formats are: yaml, json and toml", format) } diff --git a/pkg/exec/builder/action.go b/pkg/exec/builder/action.go index fede9b69f..830a95dc8 100644 --- a/pkg/exec/builder/action.go +++ b/pkg/exec/builder/action.go @@ -7,7 +7,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/yaml" - "github.com/pkg/errors" ) // UnmarshalAction handles unmarshaling any action, given a pointer to a slice of Steps. @@ -26,7 +25,7 @@ func UnmarshalAction(unmarshal func(interface{}) error, builder BuildableAction) actionMap := map[string][]interface{}{} err := unmarshal(&actionMap) if err != nil { - return nil, errors.Wrap(err, "could not unmarshal yaml into an action map of exec steps") + return nil, fmt.Errorf("could not unmarshal yaml into an action map of exec steps: %w", err) } return unmarshalActionMap(actionMap, builder) @@ -84,7 +83,11 @@ func LoadAction(cxt *portercontext.Context, commandFile string, unmarshal func([ if cxt.Debug { fmt.Fprintf(cxt.Err, "DEBUG Parsed Input:\n%#v\n", result) } - return errors.Wrapf(err, "could not unmarshal input:\n %s", string(contents)) + if err != nil { + return fmt.Errorf("could not unmarshal input:\n %s: %w", string(contents), err) + } + + return nil } func readInputFromStdinOrFile(cxt *portercontext.Context, commandFile string) ([]byte, error) { @@ -102,7 +105,7 @@ func readInputFromStdinOrFile(cxt *portercontext.Context, commandFile string) ([ if commandFile == "" { source = commandFile } - return nil, errors.Wrapf(err, "could not load input from %s", source) + return nil, fmt.Errorf("could not load input from %s: %w", source, err) } return b, nil } diff --git a/pkg/exec/builder/execute.go b/pkg/exec/builder/execute.go index 8315c6c96..5a7ef1db3 100644 --- a/pkg/exec/builder/execute.go +++ b/pkg/exec/builder/execute.go @@ -3,13 +3,13 @@ package builder import ( "bytes" "context" + "errors" "fmt" "io" "os/exec" "strings" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) var DefaultFlagDashes = Dashes{ @@ -69,7 +69,7 @@ type ExitError interface { func ExecuteSingleStepAction(cxt *portercontext.Context, action ExecutableAction) (string, error) { steps := action.GetSteps() if len(steps) != 1 { - return "", errors.Errorf("expected a single step, but got %d", len(steps)) + return "", fmt.Errorf("expected a single step, but got %d", len(steps)) } step := steps[0] @@ -176,7 +176,7 @@ func ExecuteStep(pctx *portercontext.Context, step ExecutableStep) (string, erro err := cmd.Start() if err != nil { - return "", errors.Wrap(err, fmt.Sprintf("couldn't run command %s", prettyCmd)) + return "", fmt.Errorf("couldn't run command %s: %w", prettyCmd, err) } err = cmd.Wait() @@ -192,7 +192,7 @@ func ExecuteStep(pctx *portercontext.Context, step ExecutableStep) (string, erro // Ok, now check if we still have a problem if err != nil { - return "", errors.Wrap(err, fmt.Sprintf("error running command %s", prettyCmd)) + return "", fmt.Errorf("error running command %s: %w", prettyCmd, err) } return stdout.String(), nil diff --git a/pkg/exec/builder/flags.go b/pkg/exec/builder/flags.go index 55ad0bf5b..61a21651a 100644 --- a/pkg/exec/builder/flags.go +++ b/pkg/exec/builder/flags.go @@ -3,8 +3,6 @@ package builder import ( "fmt" "sort" - - "github.com/pkg/errors" ) // Flag represents a flag passed to a mixin command. @@ -80,7 +78,7 @@ func (flags *Flags) UnmarshalYAML(unmarshal func(interface{}) error) error { flagMap := map[string]interface{}{} err := unmarshal(&flagMap) if err != nil { - return errors.Wrap(err, "could not unmarshal yaml into Step.Flags") + return fmt.Errorf("could not unmarshal yaml into Step.Flags: %w", err) } *flags = make(Flags, 0, len(flagMap)) @@ -94,7 +92,7 @@ func (flags *Flags) UnmarshalYAML(unmarshal func(interface{}) error) error { for i := range t { iv, ok := t[i].(string) if !ok { - return errors.Errorf("invalid yaml type for flag %s: %T", f.Name, t[i]) + return fmt.Errorf("invalid yaml type for flag %s: %T", f.Name, t[i]) } f.Values[i] = iv } diff --git a/pkg/exec/builder/output_file.go b/pkg/exec/builder/output_file.go index 4c4bdb947..c129d756b 100644 --- a/pkg/exec/builder/output_file.go +++ b/pkg/exec/builder/output_file.go @@ -4,7 +4,6 @@ import ( "fmt" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) type OutputFile interface { @@ -38,12 +37,12 @@ func ProcessFileOutputs(cxt *portercontext.Context, step StepWithOutputs) error valueB, err := cxt.FileSystem.ReadFile(outputPath) if err != nil { - return errors.Wrapf(err, "error evaluating filepath %q for output %q", outputPath, outputName) + return fmt.Errorf("error evaluating filepath %q for output %q: %w", outputPath, outputName, err) } err = cxt.WriteMixinOutputToFile(outputName, valueB) if err != nil { - return errors.Wrapf(err, "error writing mixin output for %q", outputName) + return fmt.Errorf("error writing mixin output for %q: %w", outputName, err) } } diff --git a/pkg/exec/builder/output_jsonpath.go b/pkg/exec/builder/output_jsonpath.go index 1145c356e..803faa214 100644 --- a/pkg/exec/builder/output_jsonpath.go +++ b/pkg/exec/builder/output_jsonpath.go @@ -7,7 +7,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "github.com/PaesslerAG/jsonpath" - "github.com/pkg/errors" ) type OutputJsonPath interface { @@ -50,7 +49,7 @@ func ProcessJsonPathOutputs(cxt *portercontext.Context, step StepWithOutputs, st d.UseNumber() err := d.Decode(&outputJson) if err != nil { - return errors.Wrapf(err, "error unmarshaling stdout as json %s", stdout) + return fmt.Errorf("error unmarshaling stdout as json %s: %w", stdout, err) } } } @@ -59,7 +58,7 @@ func ProcessJsonPathOutputs(cxt *portercontext.Context, step StepWithOutputs, st if outputJson != nil { value, err := jsonpath.Get(outputPath, outputJson) if err != nil { - return errors.Wrapf(err, "error evaluating jsonpath %q for output %q against %s", outputPath, outputName, stdout) + return fmt.Errorf("error evaluating jsonpath %q for output %q against %s: %w", outputPath, outputName, stdout, err) } // Only marshal complex types to json, leave strings, numbers and booleans alone @@ -67,7 +66,7 @@ func ProcessJsonPathOutputs(cxt *portercontext.Context, step StepWithOutputs, st case map[string]interface{}, []interface{}: valueB, err = json.Marshal(value) if err != nil { - return errors.Wrapf(err, "error marshaling jsonpath result %v for output %q", valueB, outputName) + return fmt.Errorf("error marshaling jsonpath result %v for output %q: %w", valueB, outputName, err) } default: valueB = []byte(fmt.Sprintf("%v", t)) @@ -76,7 +75,7 @@ func ProcessJsonPathOutputs(cxt *portercontext.Context, step StepWithOutputs, st err := cxt.WriteMixinOutputToFile(outputName, valueB) if err != nil { - return errors.Wrapf(err, "error writing mixin output for %q", outputName) + return fmt.Errorf("error writing mixin output for %q: %w", outputName, err) } } diff --git a/pkg/exec/builder/output_regex.go b/pkg/exec/builder/output_regex.go index 66d44cc88..48333a88f 100644 --- a/pkg/exec/builder/output_regex.go +++ b/pkg/exec/builder/output_regex.go @@ -6,7 +6,6 @@ import ( "strings" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) type OutputRegex interface { @@ -41,7 +40,7 @@ func ProcessRegexOutputs(cxt *portercontext.Context, step StepWithOutputs, stdou r, err := regexp.Compile(outputRegex) if err != nil { - return errors.Wrapf(err, "invalid regular expression %q for output %q", outputRegex, outputName) + return fmt.Errorf("invalid regular expression %q for output %q: %w", outputRegex, outputName, err) } // Find every submatch / capture and put it on its own line in the output file @@ -55,7 +54,7 @@ func ProcessRegexOutputs(cxt *portercontext.Context, step StepWithOutputs, stdou value := strings.Join(matches, "\n") err = cxt.WriteMixinOutputToFile(outputName, []byte(value)) if err != nil { - return errors.Wrapf(err, "error writing mixin output for %q", outputName) + return fmt.Errorf("error writing mixin output for %q: %w", outputName, err) } } diff --git a/pkg/exec/lint.go b/pkg/exec/lint.go index e7e5f6022..32b269a5a 100644 --- a/pkg/exec/lint.go +++ b/pkg/exec/lint.go @@ -8,7 +8,6 @@ import ( "get.porter.sh/porter/pkg/exec/builder" "get.porter.sh/porter/pkg/linter" "get.porter.sh/porter/pkg/yaml" - "github.com/pkg/errors" ) // BuildInput represents stdin sent by porter to the build and lint commands @@ -120,7 +119,7 @@ func (m *Mixin) PrintLintResults() error { b, err := encoding.MarshalJson(results) if err != nil { - return errors.Wrapf(err, "could not marshal lint results %#v", results) + return fmt.Errorf("could not marshal lint results %#v: %w", results, err) } // Print the results as json to stdout for Porter to read diff --git a/pkg/linter/linter.go b/pkg/linter/linter.go index 44b0a7830..c9ac92e49 100644 --- a/pkg/linter/linter.go +++ b/pkg/linter/linter.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/portercontext" "github.com/dustin/go-humanize" - "github.com/pkg/errors" ) // Level of severity for a lint result. @@ -171,7 +170,7 @@ func (l *Linter) Lint(ctx context.Context, m *manifest.Manifest) (Results, error var r Results err = json.Unmarshal([]byte(response), &r) if err != nil { - return nil, errors.Wrapf(err, "unable to parse lint response from mixin %q", mixin) + return nil, fmt.Errorf("unable to parse lint response from mixin %q: %w", mixin, err) } results = append(results, r...) diff --git a/pkg/manifest/manifest.go b/pkg/manifest/manifest.go index d47b25a43..4d8e8c9ca 100644 --- a/pkg/manifest/manifest.go +++ b/pkg/manifest/manifest.go @@ -4,6 +4,7 @@ import ( "context" "crypto/md5" "encoding/hex" + "errors" "fmt" "io/ioutil" "net/http" @@ -25,11 +26,10 @@ import ( "github.com/cnabio/cnab-go/bundle/definition" multierror "github.com/hashicorp/go-multierror" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) const ( - invalidStepErrorFormat = "validation of action \"%s\" failed" + invalidStepErrorFormat = "validation of action \"%s\" failed: %w" // SupportedSchemaVersion is the Porter manifest (porter.yaml) schema // version supported by this version of Porter. @@ -120,7 +120,7 @@ func (m *Manifest) Validate(cxt *portercontext.Context, strategy schema.CheckStr } err = m.Install.Validate(m) if err != nil { - result = multierror.Append(result, errors.Wrapf(err, fmt.Sprintf(invalidStepErrorFormat, "install"))) + result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, "install", err)) } if m.Uninstall == nil { @@ -128,13 +128,13 @@ func (m *Manifest) Validate(cxt *portercontext.Context, strategy schema.CheckStr } err = m.Uninstall.Validate(m) if err != nil { - result = multierror.Append(result, errors.Wrapf(err, fmt.Sprintf(invalidStepErrorFormat, "uninstall"))) + result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, "uninstall", err)) } for actionName, steps := range m.CustomActions { err := steps.Validate(m) if err != nil { - result = multierror.Append(result, errors.Wrapf(err, fmt.Sprintf(invalidStepErrorFormat, actionName))) + result = multierror.Append(result, fmt.Errorf(invalidStepErrorFormat, actionName, err)) } } @@ -196,7 +196,7 @@ func (m *Manifest) validateMetadata(cxt *portercontext.Context, strategy schema. if m.Version != "" { v, err := semver.NewVersion(m.Version) if err != nil { - return errors.Wrapf(err, "version %q is not a valid semver value", m.Version) + return fmt.Errorf("version %q is not a valid semver value: %w", m.Version, err) } m.Version = v.String() } @@ -362,13 +362,13 @@ func (pd *ParameterDefinition) Validate() error { // Validate the Parameter Definition schema itself if _, err := pdCopy.Schema.ValidateSchema(); err != nil { - return multierror.Append(result, errors.Wrapf(err, "encountered an error while validating definition for parameter %q", pdCopy.Name)) + return multierror.Append(result, fmt.Errorf("encountered an error while validating definition for parameter %q: %w", pdCopy.Name, err)) } if pdCopy.Default != nil { schemaValidationErrs, err := pdCopy.Schema.Validate(pdCopy.Default) if err != nil { - result = multierror.Append(result, errors.Wrapf(err, "encountered error while validating parameter %s", pdCopy.Name)) + result = multierror.Append(result, fmt.Errorf("encountered error while validating parameter %s: %w", pdCopy.Name, err)) } for _, schemaValidationErr := range schemaValidationErrs { result = multierror.Append(result, fmt.Errorf("encountered an error validating the default value %v for parameter %q: %s", pdCopy.Default, pdCopy.Name, schemaValidationErr.Error)) @@ -526,7 +526,7 @@ func (m *MixinDeclaration) UnmarshalYAML(unmarshal func(interface{}) error) erro mixinWithConfig := map[string]interface{}{} err = unmarshal(&mixinWithConfig) if err != nil { - return errors.Wrap(err, "could not unmarshal raw yaml of mixin declarations") + return fmt.Errorf("could not unmarshal raw yaml of mixin declarations: %w", err) } if len(mixinWithConfig) == 0 { @@ -711,13 +711,13 @@ func (od *OutputDefinition) Validate() error { // Validate the Output Definition schema itself if _, err := odCopy.Schema.ValidateSchema(); err != nil { - return multierror.Append(result, errors.Wrapf(err, "encountered an error while validating definition for output %q", odCopy.Name)) + return multierror.Append(result, fmt.Errorf("encountered an error while validating definition for output %q: %w", odCopy.Name, err)) } if odCopy.Default != nil { schemaValidationErrs, err := odCopy.Schema.Validate(odCopy.Default) if err != nil { - result = multierror.Append(result, errors.Wrapf(err, "encountered error while validating output %s", odCopy.Name)) + result = multierror.Append(result, fmt.Errorf("encountered error while validating output %s: %w", odCopy.Name, err)) } for _, schemaValidationErr := range schemaValidationErrs { result = multierror.Append(result, fmt.Errorf("encountered an error validating the default value %v for output %q: %s", odCopy.Default, odCopy.Name, schemaValidationErr.Error)) @@ -769,7 +769,7 @@ func (s *Step) Validate(m *Manifest) error { } } if !mixinDeclared { - return errors.Errorf("mixin (%s) was not declared", mixinType) + return fmt.Errorf("mixin (%s) was not declared", mixinType) } if _, err := s.GetDescription(); err != nil { @@ -794,7 +794,7 @@ func (s *Step) GetDescription() (string, error) { } desc, ok := d.(string) if !ok { - return "", errors.Errorf("invalid description type (%T) for mixin step (%s)", desc, mixinName) + return "", fmt.Errorf("invalid description type (%T) for mixin step (%s)", desc, mixinName) } return desc, nil @@ -813,7 +813,7 @@ func UnmarshalManifest(cxt *portercontext.Context, manifestData []byte) (*Manife manifest := &Manifest{} err := yaml.Unmarshal(manifestData, &manifest) if err != nil { - return nil, errors.Wrap(err, "error unmarshaling the typed manifest") + return nil, fmt.Errorf("error unmarshaling the typed manifest: %w", err) } // Do a second pass to identify custom actions, which don't have yaml tags since they are dynamic @@ -825,7 +825,7 @@ func UnmarshalManifest(cxt *portercontext.Context, manifestData []byte) (*Manife unmappedData := make(map[string]interface{}) err = yaml.Unmarshal(manifestData, &unmappedData) if err != nil { - return nil, errors.Wrap(err, "error unmarshaling the untyped manifest") + return nil, fmt.Errorf("error unmarshaling the untyped manifest: %w", err) } // Use reflection to figure out which fields are on the manifest and have yaml tags @@ -853,13 +853,13 @@ func UnmarshalManifest(cxt *portercontext.Context, manifestData []byte) (*Manife for key, chunk := range unmappedData { chunkData, err := yaml.Marshal(chunk) if err != nil { - return nil, errors.Wrapf(err, "error remarshaling custom action %s", key) + return nil, fmt.Errorf("error remarshaling custom action %s: %w", key, err) } steps := Steps{} err = yaml.Unmarshal(chunkData, &steps) if err != nil { - return nil, errors.Wrapf(err, "error unmarshaling custom action %s", key) + return nil, fmt.Errorf("error unmarshaling custom action %s: %w", key, err) } manifest.CustomActions[key] = steps @@ -884,19 +884,19 @@ func (m *Manifest) SetInvocationImageAndReference(ref string) error { if m.Reference == "" && m.Registry != "" { repo, err := cnab.ParseOCIReference(path.Join(m.Registry, m.Name)) if err != nil { - return errors.Wrapf(err, "invalid bundle reference %s", path.Join(m.Registry, m.Name)) + return fmt.Errorf("invalid bundle reference %s: %w", path.Join(m.Registry, m.Name), err) } m.Reference = repo.Repository() } bundleRef, err := cnab.ParseOCIReference(m.Reference) if err != nil { - return errors.Wrapf(err, "invalid bundle reference %s", m.Reference) + return fmt.Errorf("invalid bundle reference %s: %w", m.Reference, err) } dockerTag, err := m.getDockerTagFromBundleRef(bundleRef) if err != nil { - return errors.Wrapf(err, "unable to derive docker tag from bundle reference %q", m.Reference) + return fmt.Errorf("unable to derive docker tag from bundle reference %q: %w", m.Reference, err) } // If the docker tag is initially missing from bundleTag, update with @@ -904,20 +904,20 @@ func (m *Manifest) SetInvocationImageAndReference(ref string) error { if !bundleRef.HasTag() { bundleRef, err = bundleRef.WithTag(dockerTag) if err != nil { - return errors.Wrapf(err, "could not set bundle tag to %q", dockerTag) + return fmt.Errorf("could not set bundle tag to %q: %w", dockerTag, err) } m.Reference = bundleRef.String() } imageName, err := cnab.ParseOCIReference(bundleRef.Repository()) if err != nil { - return errors.Wrapf(err, "could not set invocation image to %q", bundleRef.Repository()) + return fmt.Errorf("could not set invocation image to %q: %w", bundleRef.Repository(), err) } referenceHash := md5.Sum([]byte(bundleRef.String())) imgTag := hex.EncodeToString(referenceHash[:]) imageRef, err := imageName.WithTag(imgTag) if err != nil { - return errors.Wrapf(err, "could not set invocation image tag to %q", dockerTag) + return fmt.Errorf("could not set invocation image tag to %q: %w", dockerTag, err) } m.Image = imageRef.String() @@ -964,22 +964,28 @@ func ResolvePath(value string) string { func readFromFile(cxt *portercontext.Context, path string) ([]byte, error) { if exists, _ := cxt.FileSystem.Exists(path); !exists { - return nil, errors.Errorf("the specified porter configuration file %s does not exist", path) + return nil, fmt.Errorf("the specified porter configuration file %s does not exist", path) } data, err := cxt.FileSystem.ReadFile(path) - return data, errors.Wrapf(err, "could not read manifest at %q", path) + if err != nil { + return nil, fmt.Errorf("could not read manifest at %q: %w", path, err) + } + return data, nil } func readFromURL(path string) ([]byte, error) { resp, err := http.Get(path) if err != nil { - return nil, errors.Wrapf(err, "could not reach url %s", path) + return nil, fmt.Errorf("could not reach url %s: %w", path, err) } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) - return data, errors.Wrapf(err, "could not read from url %s", path) + if err != nil { + return nil, fmt.Errorf("could not read from url %s: %w", path, err) + } + return data, nil } func ReadManifestData(cxt *portercontext.Context, path string) ([]byte, error) { @@ -1024,7 +1030,7 @@ func scanManifestTemplating(data []byte) (templateScanResult, error) { const disableHtmlEscaping = true tmpl, err := mustache.ParseStringRaw(string(data), disableHtmlEscaping) if err != nil { - return templateScanResult{}, errors.Wrap(err, "error parsing the templating used in the manifest") + return templateScanResult{}, fmt.Errorf("error parsing the templating used in the manifest: %w", err) } tags := tmpl.Tags() @@ -1094,7 +1100,7 @@ func (r *RequiredExtension) UnmarshalYAML(unmarshal func(interface{}) error) err extWithConfig := map[string]map[string]interface{}{} err = unmarshal(&extWithConfig) if err != nil { - return errors.Wrap(err, "could not unmarshal raw yaml of required extensions") + return fmt.Errorf("could not unmarshal raw yaml of required extensions: %w", err) } if len(extWithConfig) == 0 { diff --git a/pkg/mixin/query/manifest_generator.go b/pkg/mixin/query/manifest_generator.go index 95b07320a..e30be3bcd 100644 --- a/pkg/mixin/query/manifest_generator.go +++ b/pkg/mixin/query/manifest_generator.go @@ -1,10 +1,11 @@ package query import ( + "fmt" + "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/manifest" "get.porter.sh/porter/pkg/yaml" - "github.com/pkg/errors" ) // ManifestGenerator generates mixin input from the manifest contents associated with each mixin. @@ -31,7 +32,11 @@ func (g ManifestGenerator) ListMixins() []string { func (g ManifestGenerator) BuildInput(mixinName string) ([]byte, error) { input := g.buildInputForMixin(mixinName) inputB, err := yaml.Marshal(input) - return inputB, errors.Wrapf(err, "could not marshal mixin build input for %s", mixinName) + if err != nil { + return nil, fmt.Errorf("could not marshal mixin build input for %s: %w", mixinName, err) + } + + return inputB, nil } func (g ManifestGenerator) buildInputForMixin(mixinName string) BuildInput { diff --git a/pkg/mixin/query/query.go b/pkg/mixin/query/query.go index 77a71c609..118498795 100644 --- a/pkg/mixin/query/query.go +++ b/pkg/mixin/query/query.go @@ -9,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/portercontext" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" "golang.org/x/sync/errgroup" ) @@ -111,7 +110,7 @@ func (q *MixinQuery) Execute(ctx context.Context, cmd string, inputGenerator Mix results[response.mixinName] = response.output } else { runErr = multierror.Append(runErr, - errors.Wrapf(response.runErr, "error encountered from mixin %q", response.mixinName)) + fmt.Errorf("error encountered from mixin %q: %w", response.mixinName, response.runErr)) } } @@ -124,7 +123,7 @@ func (q *MixinQuery) Execute(ctx context.Context, cmd string, inputGenerator Mix // optional commands, like lint and don't want to print their error // message when we query them with a command they don't support. if q.Debug { - fmt.Fprintln(q.Err, errors.Wrap(runErr, "not all mixins responded successfully")) + fmt.Fprintln(q.Err, fmt.Errorf("not all mixins responded successfully: %w", runErr)) } } diff --git a/pkg/pkgmgmt/client/delete.go b/pkg/pkgmgmt/client/delete.go index 423ee51bc..849770b20 100644 --- a/pkg/pkgmgmt/client/delete.go +++ b/pkg/pkgmgmt/client/delete.go @@ -5,7 +5,6 @@ import ( "path/filepath" "get.porter.sh/porter/pkg/pkgmgmt" - "github.com/pkg/errors" ) func (fs *FileSystem) Uninstall(opts pkgmgmt.UninstallOptions) error { @@ -13,7 +12,7 @@ func (fs *FileSystem) Uninstall(opts pkgmgmt.UninstallOptions) error { return fs.uninstallByName(opts.Name) } - return errors.Errorf("No %s name was provided to uninstall", fs.PackageType) + return fmt.Errorf("No %s name was provided to uninstall", fs.PackageType) } func (fs *FileSystem) uninstallByName(name string) error { @@ -26,7 +25,7 @@ func (fs *FileSystem) uninstallByName(name string) error { if exists { err = fs.FileSystem.RemoveAll(pkgDir) if err != nil { - return errors.Wrapf(err, "could not remove %s directory %q", fs.PackageType, pkgDir) + return fmt.Errorf("could not remove %s directory %q: %w", fs.PackageType, pkgDir, err) } return nil diff --git a/pkg/pkgmgmt/client/filesystem.go b/pkg/pkgmgmt/client/filesystem.go index 9b1b12ef0..8febc73e3 100644 --- a/pkg/pkgmgmt/client/filesystem.go +++ b/pkg/pkgmgmt/client/filesystem.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) var _ pkgmgmt.PackageManager = &FileSystem{} @@ -51,7 +50,7 @@ func (fs *FileSystem) List() ([]string, error) { files, err := fs.FileSystem.ReadDir(parentDir) if err != nil { - return nil, errors.Wrapf(err, "could not list the contents of the %s directory %q", fs.PackageType, parentDir) + return nil, fmt.Errorf("could not list the contents of the %s directory %q: %w", fs.PackageType, parentDir, err) } names := make([]string, 0, len(files)) @@ -133,7 +132,7 @@ func (fs *FileSystem) GetPackageDir(name string) (string, error) { pkgDir := filepath.Join(parentDir, name) dirExists, err := fs.FileSystem.DirExists(pkgDir) if err != nil { - return "", errors.Wrapf(err, "%s %s not accessible at %s", fs.PackageType, name, pkgDir) + return "", fmt.Errorf("%s %s not accessible at %s: %w", fs.PackageType, name, pkgDir, err) } if !dirExists { return "", fmt.Errorf("%s %s not installed in %s", fs.PackageType, name, pkgDir) diff --git a/pkg/pkgmgmt/client/runner.go b/pkg/pkgmgmt/client/runner.go index 5345e63a5..5ea508d28 100644 --- a/pkg/pkgmgmt/client/runner.go +++ b/pkg/pkgmgmt/client/runner.go @@ -2,6 +2,7 @@ package client import ( "context" + "errors" "fmt" "io" "path/filepath" @@ -9,7 +10,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) type Runner struct { @@ -38,10 +38,10 @@ func (r *Runner) Validate() error { pkgPath := r.getExecutablePath() exists, err := r.FileSystem.Exists(pkgPath) if err != nil { - return errors.Wrapf(err, "failed to stat package (%s)", pkgPath) + return fmt.Errorf("failed to stat package (%s: %w)", pkgPath, err) } if !exists { - return errors.Errorf("package not found (%s)", pkgPath) + return fmt.Errorf("package not found (%s)", pkgPath) } return nil @@ -94,7 +94,7 @@ func (r *Runner) Run(ctx context.Context, commandOpts pkgmgmt.CommandOptions) er err := cmd.Start() if err != nil { - return errors.Wrapf(err, "could not run package command %s", prettyCmd) + return fmt.Errorf("could not run package command %s: %w", prettyCmd, err) } return cmd.Wait() diff --git a/pkg/pkgmgmt/download_options.go b/pkg/pkgmgmt/download_options.go index 49f1a82be..5e9d69f6f 100644 --- a/pkg/pkgmgmt/download_options.go +++ b/pkg/pkgmgmt/download_options.go @@ -1,9 +1,8 @@ package pkgmgmt import ( + "fmt" "net/url" - - "github.com/pkg/errors" ) // DefaultPackageMirror is the default location from which to download Porter assets, such as binaries, atom feeds and package indexes. @@ -28,7 +27,7 @@ func (o *PackageDownloadOptions) Validate() error { mirrorURL, err := url.Parse(o.Mirror) if err != nil { - return errors.Wrapf(err, "Invalid --mirror %s", o.Mirror) + return fmt.Errorf("invalid --mirror %s: %w", o.Mirror, err) } o.parsedMirror = mirrorURL diff --git a/pkg/pkgmgmt/feed/generate.go b/pkg/pkgmgmt/feed/generate.go index 107486717..5040fe673 100644 --- a/pkg/pkgmgmt/feed/generate.go +++ b/pkg/pkgmgmt/feed/generate.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "github.com/Masterminds/semver/v3" "github.com/cbroglie/mustache" - "github.com/pkg/errors" ) type GenerateOptions struct { @@ -35,7 +34,7 @@ func (o *GenerateOptions) ValidateSearchDirectory(cxt *portercontext.Context) er } if _, err := cxt.FileSystem.Stat(o.SearchDirectory); err != nil { - return errors.Wrapf(err, "invalid --dir %s", o.SearchDirectory) + return fmt.Errorf("invalid --dir %s: %w", o.SearchDirectory, err) } return nil @@ -43,7 +42,7 @@ func (o *GenerateOptions) ValidateSearchDirectory(cxt *portercontext.Context) er func (o *GenerateOptions) ValidateTemplateFile(cxt *portercontext.Context) error { if _, err := cxt.FileSystem.Stat(o.TemplateFile); err != nil { - return errors.Wrapf(err, "invalid --template %s", o.TemplateFile) + return fmt.Errorf("invalid --template %s: %w", o.TemplateFile, err) } return nil @@ -113,7 +112,7 @@ func (feed *MixinFeed) Generate(opts GenerateOptions) error { }) if err != nil { - return errors.Wrapf(err, "failed to traverse the %s directory", opts.SearchDirectory) + return fmt.Errorf("failed to traverse the %s directory: %w", opts.SearchDirectory, err) } if len(feed.Index) == 0 { @@ -146,7 +145,7 @@ func shouldPublishVersion(version string) bool { func (feed *MixinFeed) Save(opts GenerateOptions) error { feedTmpl, err := feed.FileSystem.ReadFile(opts.TemplateFile) if err != nil { - return errors.Wrapf(err, "error reading template file at %s", opts.TemplateFile) + return fmt.Errorf("error reading template file at %s: %w", opts.TemplateFile, err) } tmplData := map[string]interface{}{} @@ -172,7 +171,7 @@ func (feed *MixinFeed) Save(opts GenerateOptions) error { } err = feed.FileSystem.WriteFile(opts.AtomFile, []byte(atomXml), pkg.FileModeWritable) if err != nil { - return errors.Wrapf(err, "could not write feed to %s", opts.AtomFile) + return fmt.Errorf("could not write feed to %s: %w", opts.AtomFile, err) } fmt.Fprintf(feed.Out, "wrote feed to %s\n", opts.AtomFile) diff --git a/pkg/pkgmgmt/feed/load.go b/pkg/pkgmgmt/feed/load.go index b4cdb1d16..35e93e22f 100644 --- a/pkg/pkgmgmt/feed/load.go +++ b/pkg/pkgmgmt/feed/load.go @@ -7,13 +7,12 @@ import ( "path" "github.com/mmcdole/gofeed/atom" - "github.com/pkg/errors" ) func (feed *MixinFeed) Load(file string) error { contents, err := feed.FileSystem.ReadFile(file) if err != nil { - return errors.Wrapf(err, "error reading mixin feed at %s", file) + return fmt.Errorf("error reading mixin feed at %s: %w", file, err) } p := atom.Parser{} @@ -22,7 +21,7 @@ func (feed *MixinFeed) Load(file string) error { if feed.Debug { fmt.Fprintln(feed.Err, string(contents)) } - return errors.Wrap(err, "error parsing the mixin feed as an atom xml file") + return fmt.Errorf("error parsing the mixin feed as an atom xml file: %w", err) } feed.Updated = atomFeed.UpdatedParsed diff --git a/pkg/pkgmgmt/feed/template.go b/pkg/pkgmgmt/feed/template.go index bb1332847..9843e5961 100644 --- a/pkg/pkgmgmt/feed/template.go +++ b/pkg/pkgmgmt/feed/template.go @@ -5,7 +5,6 @@ import ( "fmt" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) //go:embed templates/atom-template.xml @@ -15,7 +14,7 @@ func CreateTemplate(cxt *portercontext.Context) error { templateFile := "atom-template.xml" err := cxt.FileSystem.WriteFile(templateFile, feedTemplate, 0644) if err != nil { - return errors.Wrapf(err, "error writing mixin feed template to %s", templateFile) + return fmt.Errorf("error writing mixin feed template to %s: %w", templateFile, err) } fmt.Fprintf(cxt.Out, "wrote mixin feed template to %s\n", templateFile) diff --git a/pkg/pkgmgmt/install.go b/pkg/pkgmgmt/install.go index f5fd5d51b..ebaaab26a 100644 --- a/pkg/pkgmgmt/install.go +++ b/pkg/pkgmgmt/install.go @@ -1,11 +1,11 @@ package pkgmgmt import ( + "errors" + "fmt" "net/url" "path" "strings" - - "github.com/pkg/errors" ) type InstallOptions struct { @@ -46,7 +46,7 @@ func (o *InstallOptions) defaultFeedURL() url.URL { func (o *InstallOptions) Validate(args []string) error { if o.PackageType != "mixin" && o.PackageType != "plugin" { - return errors.Errorf("invalid package type %q. Please report this as a bug to Porter!", o.PackageType) + return fmt.Errorf("invalid package type %q. Please report this as a bug to Porter!", o.PackageType) } err := o.validateName(args) @@ -81,7 +81,7 @@ func (o *InstallOptions) validateURL() error { parsedURL, err := url.Parse(o.URL) if err != nil { - return errors.Wrapf(err, "invalid --url %s", o.URL) + return fmt.Errorf("invalid --url %s: %w", o.URL, err) } o.parsedURL = parsedURL @@ -97,7 +97,7 @@ func (o *InstallOptions) validateFeedURL() error { if o.FeedURL != "" { parsedFeedURL, err := url.Parse(o.FeedURL) if err != nil { - return errors.Wrapf(err, "invalid --feed-url %s", o.FeedURL) + return fmt.Errorf("invalid --feed-url %s: %w", o.FeedURL, err) } o.parsedFeedURL = parsedFeedURL @@ -116,12 +116,12 @@ func (o *InstallOptions) defaultVersion() { func (o *InstallOptions) validateName(args []string) error { switch len(args) { case 0: - return errors.Errorf("no name was specified") + return errors.New("no name was specified") case 1: o.Name = strings.ToLower(args[0]) return nil default: - return errors.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) } } diff --git a/pkg/pkgmgmt/search.go b/pkg/pkgmgmt/search.go index ce33711c1..fce0d4ab7 100644 --- a/pkg/pkgmgmt/search.go +++ b/pkg/pkgmgmt/search.go @@ -7,8 +7,6 @@ import ( "net/http" "sort" "strings" - - "github.com/pkg/errors" ) // Searcher can locate a mixin or plugin from the community feeds. @@ -40,7 +38,7 @@ func (s *Searcher) Search(name, pkgType string) (PackageList, error) { } if results.Len() == 0 { - return PackageList{}, errors.Errorf("no %ss found for %s", pkgType, name) + return PackageList{}, fmt.Errorf("no %ss found for %s", pkgType, name) } sort.Sort(results) @@ -51,7 +49,7 @@ func (s *Searcher) Search(name, pkgType string) (PackageList, error) { func GetPackageListings(url string) (PackageList, error) { resp, err := http.Get(url) if err != nil { - return PackageList{}, errors.Wrapf(err, "unable to fetch package list via %s", url) + return PackageList{}, fmt.Errorf("unable to fetch package list via %s: %w", url, err) } if resp.StatusCode != http.StatusOK { return PackageList{}, fmt.Errorf("unable to fetch package list via %s: %s", url, http.StatusText(resp.StatusCode)) @@ -60,13 +58,13 @@ func GetPackageListings(url string) (PackageList, error) { defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { - return PackageList{}, errors.Wrapf(err, "unable to read package list via %s", url) + return PackageList{}, fmt.Errorf("unable to read package list via %s: %w", url, err) } list := PackageList{} err = json.Unmarshal(data, &list) if err != nil { - return PackageList{}, errors.Wrap(err, "unable to unmarshal package list") + return PackageList{}, fmt.Errorf("unable to unmarshal package list: %w", err) } return list, nil diff --git a/pkg/pkgmgmt/uninstall.go b/pkg/pkgmgmt/uninstall.go index 8d80219df..c5f0365c3 100644 --- a/pkg/pkgmgmt/uninstall.go +++ b/pkg/pkgmgmt/uninstall.go @@ -1,9 +1,9 @@ package pkgmgmt import ( + "errors" + "fmt" "strings" - - "github.com/pkg/errors" ) type UninstallOptions struct { @@ -13,12 +13,12 @@ type UninstallOptions struct { func (o *UninstallOptions) Validate(args []string) error { switch len(args) { case 0: - return errors.Errorf("no name was specified") + return errors.New("no name was specified") case 1: o.Name = strings.ToLower(args[0]) return nil default: - return errors.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) } } diff --git a/pkg/plugins/pluggable/connection.go b/pkg/plugins/pluggable/connection.go index 7b3ea1bc0..36b53a07e 100644 --- a/pkg/plugins/pluggable/connection.go +++ b/pkg/plugins/pluggable/connection.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -20,7 +21,6 @@ import ( "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-plugin" - "github.com/pkg/errors" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.opentelemetry.io/otel/attribute" "google.golang.org/grpc" @@ -91,7 +91,7 @@ func (c *PluginConnection) Start(ctx context.Context, pluginCfg io.Reader) error if c.key.IsInternal { porterPath, err := c.config.GetPorterPath() if err != nil { - return errors.Wrap(err, "could not determine the path to the porter pluginProtocol") + return fmt.Errorf("could not determine the path to the porter pluginProtocol: %w", err) } c.pluginCmd = c.config.NewCommand(ctx, porterPath, "plugin", "run", c.key.String()) @@ -269,12 +269,12 @@ func (c *PluginConnection) setUpDebugger(ctx context.Context, client *plugin.Cli } if !isDelveInstalled() { - return log.Error(errors.New("Delve needs to be installed to debug plugins")) + return log.Error(errors.New("delve needs to be installed to debug plugins")) } listen := fmt.Sprintf("--listen=127.0.0.1:%s", debugContext.DebuggerPort) if len(debugContext.PlugInWorkingDirectory) == 0 { - return log.Error(errors.New("Plugin Working Directory is required for debugging")) + return log.Error(errors.New("plugin Working Directory is required for debugging")) } wd := fmt.Sprintf("--wd=%s", debugContext.PlugInWorkingDirectory) pid := client.ReattachConfig().Pid diff --git a/pkg/plugins/pluggable/loader.go b/pkg/plugins/pluggable/loader.go index f9ed94d70..5d5950d60 100644 --- a/pkg/plugins/pluggable/loader.go +++ b/pkg/plugins/pluggable/loader.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/plugins" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" ) @@ -138,7 +137,7 @@ func (l *PluginLoader) readPluginConfig() (io.Reader, error) { b, err := json.Marshal(l.selectedPluginConfig) if err != nil { - return nil, errors.Wrapf(err, "could not marshal plugin config for %s", l.selectedPluginKey) + return nil, fmt.Errorf("could not marshal plugin config for %s: %w", l.selectedPluginKey, err) } return bytes.NewBuffer(b), nil diff --git a/pkg/plugins/plugins.go b/pkg/plugins/plugins.go index 7cd2a5093..153c9c999 100644 --- a/pkg/plugins/plugins.go +++ b/pkg/plugins/plugins.go @@ -1,11 +1,11 @@ package plugins import ( + "errors" "fmt" "strings" "github.com/hashicorp/go-plugin" - "github.com/pkg/errors" ) // HandshakeConfig is common handshake config between Porter and its plugins. diff --git a/pkg/plugins/runner.go b/pkg/plugins/runner.go index 54a5a9ab7..472f423c3 100644 --- a/pkg/plugins/runner.go +++ b/pkg/plugins/runner.go @@ -2,12 +2,12 @@ package plugins import ( "context" + "errors" "fmt" "strings" "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) type CommandOptions struct { @@ -33,15 +33,15 @@ func (r *PluginRunner) Validate() error { pluginPath, err := config.New().GetPluginPath(r.pluginName) if err != nil { - return errors.Wrapf(err, "Failed to get plugin path for %s", r.pluginName) + return fmt.Errorf("Failed to get plugin path for %s: %w", r.pluginName, err) } exists, err := r.FileSystem.Exists(pluginPath) if err != nil { - return errors.Wrapf(err, "Failed to stat path %s", pluginPath) + return fmt.Errorf("Failed to stat path %s: %w", pluginPath, err) } if !exists { - return errors.Errorf("Plugin %s doesn't exist in filesystem with path %s", r.pluginName, pluginPath) + return fmt.Errorf("Plugin %s doesn't exist in filesystem with path %s", r.pluginName, pluginPath) } return nil @@ -58,7 +58,7 @@ func (r *PluginRunner) Run(ctx context.Context, commandOpts CommandOptions) erro fmt.Fprintln(r.Err, "DEBUG Plugin Path: ", pluginPath) } if err != nil { - return errors.Wrapf(err, "Failed to get plugin path for %s", r.pluginName) + return fmt.Errorf("Failed to get plugin path for %s: %w", r.pluginName, err) } cmdArgs := strings.Split(commandOpts.Command, " ") @@ -75,7 +75,7 @@ func (r *PluginRunner) Run(ctx context.Context, commandOpts CommandOptions) erro err = cmd.Start() if err != nil { - return errors.Wrapf(err, "could not run plugin command %s", prettyCmd) + return fmt.Errorf("could not run plugin command %s: %w", prettyCmd, err) } return cmd.Wait() diff --git a/pkg/porter/apply.go b/pkg/porter/apply.go index 88a12e255..a1da09e32 100644 --- a/pkg/porter/apply.go +++ b/pkg/porter/apply.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "get.porter.sh/porter/pkg/encoding" @@ -9,7 +10,6 @@ import ( "get.porter.sh/porter/pkg/printer" "get.porter.sh/porter/pkg/storage" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" ) @@ -40,10 +40,10 @@ func (o *ApplyOptions) Validate(cxt *portercontext.Context, args []string) error info, err := cxt.FileSystem.Stat(o.File) if err != nil { - return errors.Wrapf(err, "invalid file argument %s", o.File) + return fmt.Errorf("invalid file argument %s: %w", o.File, err) } if info.IsDir() { - return errors.Errorf("invalid file argument %s, must be a file not a directory", o.File) + return fmt.Errorf("invalid file argument %s, must be a file not a directory", o.File) } return nil @@ -68,7 +68,7 @@ func (p *Porter) InstallationApply(ctx context.Context, opts ApplyOptions) error var input DisplayInstallation if err := encoding.UnmarshalFile(p.FileSystem, opts.File, &input); err != nil { - return errors.Wrapf(err, "unable to parse %s as an installation document", opts.File) + return fmt.Errorf("unable to parse %s as an installation document: %w", opts.File, err) } input.Namespace = namespace inputInstallation, err := input.ConvertToInstallation() @@ -79,7 +79,7 @@ func (p *Porter) InstallationApply(ctx context.Context, opts ApplyOptions) error installation, err := p.Installations.GetInstallation(ctx, inputInstallation.Namespace, inputInstallation.Name) if err != nil { if !errors.Is(err, storage.ErrNotFound{}) { - return errors.Wrapf(err, "could not query for an existing installation document for %s", inputInstallation) + return fmt.Errorf("could not query for an existing installation document for %s: %w", inputInstallation, err) } // Create a new installation diff --git a/pkg/porter/archive.go b/pkg/porter/archive.go index e598bd097..bb97086e8 100644 --- a/pkg/porter/archive.go +++ b/pkg/porter/archive.go @@ -3,6 +3,7 @@ package porter import ( "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -19,7 +20,6 @@ import ( "github.com/cnabio/cnab-go/imagestore/construction" "github.com/cnabio/cnab-to-oci/relocation" "github.com/docker/docker/pkg/archive" - "github.com/pkg/errors" "github.com/spf13/afero" ) @@ -35,7 +35,7 @@ func (o *ArchiveOptions) Validate(ctx context.Context, args []string, p *Porter) return errors.New("destination file is required") } if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, the archive file name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the archive file name, but multiple were received: %s", args) } o.ArchiveFile = args[0] @@ -115,7 +115,7 @@ func (ex *exporter) export() error { defer bundleFile.Close() _, err = ex.bundle.WriteTo(bundleFile) if err != nil { - return errors.Wrap(err, "unable to write bundle.json in archive") + return fmt.Errorf("unable to write bundle.json in archive: %w", err) } reloData, err := json.Marshal(ex.relocationMap) @@ -124,7 +124,7 @@ func (ex *exporter) export() error { } err = ex.fs.WriteFile(filepath.Join(archiveDir, "relocation-mapping.json"), reloData, pkg.FileModeWritable) if err != nil { - return errors.Wrap(err, "unable to write relocation-mapping.json in archive") + return fmt.Errorf("unable to write relocation-mapping.json in archive: %w", err) } ex.imageStore, err = ex.imageStoreConstructor(imagestore.WithArchiveDir(archiveDir), imagestore.WithLogs(ex.logs)) diff --git a/pkg/porter/build.go b/pkg/porter/build.go index b033b43d1..c9900a496 100644 --- a/pkg/porter/build.go +++ b/pkg/porter/build.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "os" @@ -17,7 +18,6 @@ import ( "get.porter.sh/porter/pkg/tracing" "github.com/Masterminds/semver/v3" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) type BuildOptions struct { @@ -56,7 +56,7 @@ func (o *BuildOptions) Validate(p *Porter) error { o.Driver = p.GetBuildDriver() } if !stringSliceContains(BuildDriverAllowedValues, o.Driver) { - return errors.Errorf("invalid --driver value %s", o.Driver) + return fmt.Errorf("invalid --driver value %s", o.Driver) } // Syncing value back to the config and we will always use the config @@ -105,12 +105,12 @@ func (p *Porter) Build(ctx context.Context, opts BuildOptions) error { // Start with a fresh .cnab directory before building err := p.FileSystem.RemoveAll(build.LOCAL_CNAB) if err != nil { - return errors.Wrap(err, "could not cleanup generated .cnab directory before building") + return fmt.Errorf("could not cleanup generated .cnab directory before building: %w", err) } // Generate Porter's canonical version of the user-provided manifest if err := p.generateInternalManifest(opts); err != nil { - return errors.Wrap(err, "unable to generate manifest") + return fmt.Errorf("unable to generate manifest: %w", err) } m, err := manifest.LoadManifestFrom(ctx, p.Config, build.LOCAL_MANIFEST) @@ -136,7 +136,7 @@ func (p *Porter) Build(ctx context.Context, opts BuildOptions) error { // to a registry. The bundle.json will need to be updated after publishing // and provided just-in-time during bundle execution. if err := p.buildBundle(ctx, m, ""); err != nil { - return errors.Wrap(err, "unable to build bundle") + return fmt.Errorf("unable to build bundle: %w", err) } generator := build.NewDockerfileGenerator(p.Config, m, p.Templates, p.Mixins) @@ -149,7 +149,13 @@ func (p *Porter) Build(ctx context.Context, opts BuildOptions) error { } builder := p.GetBuilder(ctx) - return errors.Wrap(builder.BuildInvocationImage(ctx, m, opts.BuildImageOptions), "unable to build CNAB invocation image") + + err = builder.BuildInvocationImage(ctx, m, opts.BuildImageOptions) + if err != nil { + return fmt.Errorf("unable to build CNAB invocation image: %w", err) + } + + return nil } func (p *Porter) preLint(ctx context.Context, file string) error { @@ -175,7 +181,7 @@ func (p *Porter) preLint(ctx context.Context, file string) error { if results.HasError() { // An error was found during linting, stop and let the user correct it - return errors.New("Lint errors were detected. Rerun with --no-lint ignore the errors.") + return errors.New("lint errors were detected. Rerun with --no-lint ignore the errors") } return nil @@ -185,7 +191,7 @@ func (p *Porter) getUsedMixins(ctx context.Context, m *manifest.Manifest) ([]mix installedMixins, err := p.ListMixins(ctx) if err != nil { - return nil, errors.Wrapf(err, "error while listing mixins") + return nil, fmt.Errorf("error while listing mixins: %w", err) } var usedMixins []mixin.Metadata @@ -221,9 +227,13 @@ func (p *Porter) buildBundle(ctx context.Context, m *manifest.Manifest, digest d func (p Porter) writeBundle(b cnab.ExtendedBundle) error { f, err := p.Config.FileSystem.OpenFile(build.LOCAL_BUNDLE, os.O_RDWR|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable) if err != nil { - return errors.Wrapf(err, "error creating %s", build.LOCAL_BUNDLE) + return fmt.Errorf("error creating %s: %w", build.LOCAL_BUNDLE, err) } defer f.Close() _, err = b.WriteTo(f) - return errors.Wrapf(err, "error writing to %s", build.LOCAL_BUNDLE) + if err != nil { + return fmt.Errorf("error writing to %s: %w", build.LOCAL_BUNDLE, err) + } + + return nil } diff --git a/pkg/porter/build_integration_test.go b/pkg/porter/build_integration_test.go index 84f53bf2c..59f6b6cd7 100644 --- a/pkg/porter/build_integration_test.go +++ b/pkg/porter/build_integration_test.go @@ -152,7 +152,7 @@ func TestPorter_LintDuringBuild(t *testing.T) { err = p.Build(context.Background(), opts) require.Errorf(t, err, "Build should have been aborted with lint errors") - assert.Contains(t, err.Error(), "Lint errors were detected") + assert.Contains(t, err.Error(), "lint errors were detected") }) t.Run("ignores lint error with --no-lint", func(t *testing.T) { diff --git a/pkg/porter/cnab.go b/pkg/porter/cnab.go index 5cf2bfec5..cc7f9e0ec 100644 --- a/pkg/porter/cnab.go +++ b/pkg/porter/cnab.go @@ -2,6 +2,8 @@ package porter import ( "context" + "errors" + "fmt" "path/filepath" "get.porter.sh/porter/pkg/build" @@ -12,7 +14,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/secrets" "get.porter.sh/porter/pkg/storage" - "github.com/pkg/errors" ) const ( @@ -54,7 +55,7 @@ func (o *bundleFileOptions) Validate(cxt *portercontext.Context) error { if o.Dir != "" { _, err = cxt.FileSystem.IsDir(o.Dir) if err != nil { - return errors.Wrapf(err, "%q is not a valid directory", o.Dir) + return fmt.Errorf("%q is not a valid directory: %w", o.Dir, err) } o.Dir = cxt.FileSystem.Abs(o.Dir) } else { @@ -158,7 +159,7 @@ func (o *sharedOptions) validateInstallationName(args []string) error { if len(args) == 1 { o.Name = args[0] } else if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, the installation name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the installation name, but multiple were received: %s", args) } return nil @@ -173,8 +174,10 @@ func (o *bundleFileOptions) defaultBundleFiles(cxt *portercontext.Context) error } else { defaultPath := filepath.Join(o.Dir, config.Name) manifestExists, err := cxt.FileSystem.Exists(defaultPath) - if err != nil || !manifestExists { - return errors.Wrapf(err, "could not find a porter manifest at %s", defaultPath) + if err != nil { + return fmt.Errorf("could not find a porter manifest at %s: %w", defaultPath, err) + } else if !manifestExists { + return nil } o.File = defaultPath @@ -213,7 +216,7 @@ func (o *bundleFileOptions) validateFile(cxt *portercontext.Context) error { // Verify the file can be accessed if _, err := cxt.FileSystem.Stat(o.File); err != nil { - return errors.Wrapf(err, "unable to access --file %s", o.File) + return fmt.Errorf("unable to access --file %s: %w", o.File, err) } return nil @@ -234,7 +237,7 @@ func (o *bundleFileOptions) validateCNABFile(cxt *portercontext.Context) error { // Verify the file can be accessed if _, err := cxt.FileSystem.Stat(o.CNABFile); err != nil { // warn about the original relative path - return errors.Wrapf(err, "unable to access --cnab-file %s", originalPath) + return fmt.Errorf("unable to access --cnab-file %s: %w", originalPath, err) } return nil @@ -303,7 +306,7 @@ func (o *sharedOptions) parseParamSets(ctx context.Context, p *Porter, bun cnab. if len(o.ParameterSets) > 0 { parsed, err := p.loadParameterSets(ctx, bun, o.Namespace, o.ParameterSets) if err != nil { - return errors.Wrap(err, "unable to process provided parameter sets") + return fmt.Errorf("unable to process provided parameter sets: %w", err) } o.parsedParamSets = parsed } diff --git a/pkg/porter/copy.go b/pkg/porter/copy.go index 46ef38ed4..cd5f8bc03 100644 --- a/pkg/porter/copy.go +++ b/pkg/porter/copy.go @@ -2,11 +2,11 @@ package porter import ( "context" + "errors" "fmt" "strings" "get.porter.sh/porter/pkg/cnab" - "github.com/pkg/errors" ) type CopyOpts struct { @@ -25,7 +25,7 @@ func (c *CopyOpts) Validate() error { c.sourceRef, err = cnab.ParseOCIReference(c.Source) if err != nil { - return errors.Wrap(err, "invalid value for --source, specified value should be of the form REGISTRY/bundle:tag or REGISTRY/bundle@sha") + return fmt.Errorf("invalid value for --source, specified value should be of the form REGISTRY/bundle:tag or REGISTRY/bundle@sha: %w", err) } if c.sourceRef.HasDigest() && isCopyReferenceOnly(c.Destination) { return errors.New("--destination must be tagged reference when --source is digested reference") @@ -60,13 +60,13 @@ func (p *Porter) CopyBundle(c *CopyOpts) error { fmt.Fprintf(p.Out, "Beginning bundle copy to %s. This may take some time.\n", destinationRef) bunRef, err := p.Registry.PullBundle(c.sourceRef, c.InsecureRegistry) if err != nil { - return errors.Wrap(err, "unable to pull bundle before copying") + return fmt.Errorf("unable to pull bundle before copying: %w", err) } bunRef.Reference = destinationRef _, err = p.Registry.PushBundle(context.Background(), bunRef, c.InsecureRegistry) if err != nil { - return errors.Wrap(err, "unable to copy bundle to new location") + return fmt.Errorf("unable to copy bundle to new location: %w", err) } return nil } diff --git a/pkg/porter/create.go b/pkg/porter/create.go index 0d4bf5f0e..ef0a88d0f 100644 --- a/pkg/porter/create.go +++ b/pkg/porter/create.go @@ -7,7 +7,6 @@ import ( "get.porter.sh/porter/pkg" "get.porter.sh/porter/pkg/config" - "github.com/pkg/errors" ) func (p *Porter) Create() error { @@ -54,7 +53,7 @@ func (p *Porter) CopyTemplate(getTemplate func() ([]byte, error), dest string) e err = p.FileSystem.WriteFile(dest, tmpl, mode) if err != nil { - return errors.Wrapf(err, "failed to write template to %s", dest) + return fmt.Errorf("failed to write template to %s: %w", dest, err) } return nil } diff --git a/pkg/porter/credentials.go b/pkg/porter/credentials.go index 05e83720d..1f97c1db7 100644 --- a/pkg/porter/credentials.go +++ b/pkg/porter/credentials.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "path/filepath" "strings" @@ -14,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/storage" dtprinter "github.com/carolynvs/datetime-printer" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" ) // CredentialShowOptions represent options for Porter's credential show command @@ -101,7 +101,7 @@ func (o *CredentialOptions) validateCredName(args []string) error { if len(args) == 1 { o.Name = args[0] } else if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, the credential name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the credential name, but multiple were received: %s", args) } return nil } @@ -133,14 +133,18 @@ func (p *Porter) GenerateCredentials(ctx context.Context, opts CredentialOptions cs, err := generator.GenerateCredentials(genOpts) if err != nil { - return errors.Wrap(err, "unable to generate credentials") + return fmt.Errorf("unable to generate credentials: %w", err) } cs.Status.Created = time.Now() cs.Status.Modified = cs.Status.Created err = p.Credentials.UpsertCredentialSet(ctx, cs) - return errors.Wrapf(err, "unable to save credentials") + if err != nil { + return fmt.Errorf("unable to save credentials: %w", err) + } + + return nil } // Validate validates the args provided to Porter's credential show command @@ -171,29 +175,29 @@ func (p *Porter) EditCredential(ctx context.Context, opts CredentialEditOptions) // TODO(carolynvs): support editing in yaml, json or toml contents, err := encoding.MarshalYaml(credSet) if err != nil { - return errors.Wrap(err, "unable to load credentials") + return fmt.Errorf("unable to load credentials: %w", err) } editor := editor.New(p.Context, fmt.Sprintf("porter-%s.yaml", credSet.Name), contents) output, err := editor.Run(ctx) if err != nil { - return errors.Wrap(err, "unable to open editor to edit credentials") + return fmt.Errorf("unable to open editor to edit credentials: %w", err) } err = encoding.UnmarshalYaml(output, &credSet) if err != nil { - return errors.Wrap(err, "unable to process credentials") + return fmt.Errorf("unable to process credentials: %w", err) } err = p.Credentials.Validate(ctx, credSet) if err != nil { - return errors.Wrap(err, "credentials are invalid") + return fmt.Errorf("credentials are invalid: %w", err) } credSet.Status.Modified = time.Now() err = p.Credentials.UpdateCredentialSet(ctx, credSet) if err != nil { - return errors.Wrap(err, "unable to save credentials") + return fmt.Errorf("unable to save credentials: %w", err) } return nil @@ -296,7 +300,11 @@ func (p *Porter) DeleteCredential(ctx context.Context, opts CredentialDeleteOpti } return nil } - return errors.Wrapf(err, "unable to delete credential set") + if err != nil { + return fmt.Errorf("unable to delete credential set: %w", err) + } + + return nil } // Validate validates the args provided Porter's credential delete command @@ -311,11 +319,11 @@ func (o *CredentialDeleteOptions) Validate(args []string) error { func validateCredentialName(args []string) error { switch len(args) { case 0: - return errors.Errorf("no credential name was specified") + return fmt.Errorf("no credential name was specified") case 1: return nil default: - return errors.Errorf("only one positional argument may be specified, the credential name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the credential name, but multiple were received: %s", args) } } @@ -338,11 +346,11 @@ func (p *Porter) CredentialsApply(ctx context.Context, o ApplyOptions) error { var creds storage.CredentialSet err = encoding.UnmarshalFile(p.FileSystem, o.File, &creds) if err != nil { - return errors.Wrapf(err, "could not load %s as a credential set", o.File) + return fmt.Errorf("could not load %s as a credential set: %w", o.File, err) } if err = creds.Validate(); err != nil { - return errors.Wrap(err, "invalid credential set") + return fmt.Errorf("invalid credential set: %w", err) } creds.Namespace = namespace @@ -350,7 +358,7 @@ func (p *Porter) CredentialsApply(ctx context.Context, o ApplyOptions) error { err = p.Credentials.Validate(ctx, creds) if err != nil { - return errors.Wrap(err, "credential set is invalid") + return fmt.Errorf("credential set is invalid: %w", err) } err = p.Credentials.UpsertCredentialSet(ctx, creds) @@ -367,7 +375,7 @@ func (p *Porter) getNamespaceFromFile(o ApplyOptions) (string, error) { var raw map[string]interface{} err := encoding.UnmarshalFile(p.FileSystem, o.File, &raw) if err != nil { - return "", errors.Wrapf(err, "invalid file '%s'", o.File) + return "", fmt.Errorf("invalid file '%s': %w", o.File, err) } if rawNamespace, ok := raw["namespace"]; ok { @@ -389,7 +397,7 @@ type CredentialCreateOptions struct { func (o *CredentialCreateOptions) Validate(args []string) error { if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, fileName, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, fileName, but multiple were received: %s", args) } if len(args) > 0 { @@ -397,7 +405,7 @@ func (o *CredentialCreateOptions) Validate(args []string) error { } if o.OutputType == "" && o.FileName != "" && strings.Trim(filepath.Ext(o.FileName), ".") == "" { - return errors.New("could not detect the file format from the file extension (.txt). Specify the format with --output.") + return errors.New("could not detect the file format from the file extension (.txt). Specify the format with --output") } return nil @@ -449,5 +457,5 @@ func (p *Porter) CreateCredential(opts CredentialCreateOptions) error { } func newUnsupportedFormatError(format string) error { - return errors.Errorf("unsupported format %s. Supported formats are: yaml and json.", format) + return fmt.Errorf("unsupported format %s. Supported formats are: yaml and json", format) } diff --git a/pkg/porter/credentials_test.go b/pkg/porter/credentials_test.go index e46b0bb08..7955845ae 100644 --- a/pkg/porter/credentials_test.go +++ b/pkg/porter/credentials_test.go @@ -412,7 +412,7 @@ func TestCredentialsCreateOptions_Validate(t *testing.T) { name: "no file format defined from file extension or output flag", args: []string{"credential-set"}, outputType: "", - wantErr: "could not detect the file format from the file extension (.txt). Specify the format with --output.", + wantErr: "could not detect the file format from the file extension (.txt). Specify the format with --output", }, { name: "different file format", @@ -494,13 +494,13 @@ func TestCredentialsCreate(t *testing.T) { name: "invalid input: invalid file format from fileName", fileName: "fileName.txt", outputType: "", - wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json.", "txt"), + wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json", "txt"), }, { name: "invalid input: invalid file format from outputType", fileName: "fileName", outputType: "txt", - wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json.", "txt"), + wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json", "txt"), }, } diff --git a/pkg/porter/delete.go b/pkg/porter/delete.go index 1f7edae51..6e639ed8c 100644 --- a/pkg/porter/delete.go +++ b/pkg/porter/delete.go @@ -2,11 +2,11 @@ package porter import ( "context" + "errors" "fmt" "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) const installationDeleteTmpl = "deleting installation records for %s...\n" @@ -45,7 +45,7 @@ func (p *Porter) DeleteInstallation(ctx context.Context, opts DeleteOptions) err installation, err := p.Installations.GetInstallation(ctx, opts.Namespace, opts.Name) if err != nil { - return errors.Wrapf(err, "unable to read status for installation %s", opts.Name) + return fmt.Errorf("unable to read status for installation %s: %w", opts.Name, err) } if (installation.Status.Action != cnab.ActionUninstall || installation.Status.ResultStatus != cnab.StatusSucceeded) && !opts.Force { diff --git a/pkg/porter/dependencies.go b/pkg/porter/dependencies.go index abf5682ba..8a02e3a76 100644 --- a/pkg/porter/dependencies.go +++ b/pkg/porter/dependencies.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "strings" @@ -12,7 +13,6 @@ import ( "get.porter.sh/porter/pkg/runtime" "get.porter.sh/porter/pkg/storage" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) type dependencyExecutioner struct { @@ -131,7 +131,7 @@ func (e *dependencyExecutioner) identifyDependencies(ctx context.Context) error } else if e.parentOpts.Reference != "" { cachedBundle, err := e.Resolver.Resolve(e.parentOpts.BundlePullOptions) if err != nil { - return errors.Wrapf(err, "could not resolve bundle") + return fmt.Errorf("could not resolve bundle: %w", err) } bun = cachedBundle.Definition @@ -175,23 +175,23 @@ func (e *dependencyExecutioner) prepareDependency(ctx context.Context, dep *queu Force: e.parentOpts.Force, } if err := pullOpts.Validate(); err != nil { - return errors.Wrapf(err, "error preparing dependency %s", dep.Alias) + return fmt.Errorf("error preparing dependency %s: %w", dep.Alias, err) } cachedDep, err := e.Resolver.Resolve(pullOpts) if err != nil { - return errors.Wrapf(err, "error pulling dependency %s", dep.Alias) + return fmt.Errorf("error pulling dependency %s: %w", dep.Alias, err) } dep.BundleReference = cachedDep.BundleReference err = cachedDep.Definition.Validate() if err != nil { - return errors.Wrapf(err, "invalid bundle %s", dep.Alias) + return fmt.Errorf("invalid bundle %s: %w", dep.Alias, err) } // Cache the bundle.json for later dep.cnabFileContents, err = e.FileSystem.ReadFile(cachedDep.BundlePath) if err != nil { - return errors.Wrapf(err, "error reading %s", cachedDep.BundlePath) + return fmt.Errorf("error reading %s: %w", cachedDep.BundlePath, err) } // Make a lookup of which parameters are defined in the dependent bundle @@ -222,7 +222,7 @@ func (e *dependencyExecutioner) prepareDependency(ctx context.Context, dep *queu for paramName, value := range manifestDep.Parameters { // Make sure the parameter is defined in the bundle if _, ok := depParams[paramName]; !ok { - return errors.Errorf("invalid dependencies.%s.parameters entry, %s is not a parameter defined in that bundle", dep.Alias, paramName) + return fmt.Errorf("invalid dependencies.%s.parameters entry, %s is not a parameter defined in that bundle", dep.Alias, paramName) } if dep.Parameters == nil { @@ -242,7 +242,7 @@ func (e *dependencyExecutioner) prepareDependency(ctx context.Context, dep *queu // Make sure the parameter is defined in the bundle if _, ok := depParams[paramName]; !ok { - return errors.Errorf("invalid --param %s, %s is not a parameter defined in the bundle %s", key, paramName, dep.Alias) + return fmt.Errorf("invalid --param %s, %s is not a parameter defined in the bundle %s", key, paramName, dep.Alias) } if dep.Parameters == nil { @@ -279,7 +279,7 @@ func (e *dependencyExecutioner) executeDependency(ctx context.Context, dep *queu resolvedParameters, err := e.porter.resolveParameters(ctx, depInstallation, dep.BundleReference.Definition, e.parentArgs.Action, dep.Parameters) if err != nil { - return errors.Wrapf(err, "error resolving parameters for dependency %s", dep.Alias) + return fmt.Errorf("error resolving parameters for dependency %s: %w", dep.Alias, err) } depArgs := cnabprovider.ActionArguments{ @@ -303,7 +303,7 @@ func (e *dependencyExecutioner) executeDependency(ctx context.Context, dep *queu fmt.Fprintf(e.Out, "Executing dependency %s...\n", dep.Alias) err = e.CNAB.Execute(ctx, depArgs) if err != nil { - executeErrs = multierror.Append(executeErrs, errors.Wrapf(err, "error executing dependency %s", dep.Alias)) + executeErrs = multierror.Append(executeErrs, fmt.Errorf("error executing dependency %s: %w", dep.Alias, err)) // Handle errors when/if the action is uninstall // If uninstallOpts is an empty struct, executeErrs will pass through diff --git a/pkg/porter/explain.go b/pkg/porter/explain.go index 9eabae0ea..54c947227 100644 --- a/pkg/porter/explain.go +++ b/pkg/porter/explain.go @@ -12,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/printer" "github.com/cnabio/cnab-go/bundle" - "github.com/pkg/errors" ) type ExplainOpts struct { @@ -162,7 +161,7 @@ func (p *Porter) Explain(ctx context.Context, o ExplainOpts) error { pb, err := generatePrintable(bundleRef.Definition, o.Action) if err != nil { - return errors.Wrap(err, "unable to print bundle") + return fmt.Errorf("unable to print bundle: %w", err) } return p.printBundleExplain(o, pb, bundleRef.Definition) } @@ -191,7 +190,7 @@ func generatePrintable(bun cnab.ExtendedBundle, action string) (*PrintableBundle solver := &cnab.DependencySolver{} deps, err := solver.ResolveDependencies(bun) if err != nil { - return nil, errors.Wrapf(err, "error resolving bundle dependencies") + return nil, fmt.Errorf("error resolving bundle dependencies: %w", err) } pb := PrintableBundle{ @@ -353,7 +352,7 @@ func (p *Porter) printCredentialsExplainBlock(bun *PrintableBundle) error { fmt.Fprintln(p.Out, "Credentials:") err := p.printCredentialsExplainTable(bun) if err != nil { - return errors.Wrap(err, "unable to print credentials table") + return fmt.Errorf("unable to print credentials table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block @@ -379,7 +378,7 @@ func (p *Porter) printParametersExplainBlock(bun *PrintableBundle) error { fmt.Fprintln(p.Out, "Parameters:") err := p.printParametersExplainTable(bun) if err != nil { - return errors.Wrap(err, "unable to print parameters table") + return fmt.Errorf("unable to print parameters table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block @@ -405,7 +404,7 @@ func (p *Porter) printOutputsExplainBlock(bun *PrintableBundle) error { fmt.Fprintln(p.Out, "Outputs:") err := p.printOutputsExplainTable(bun) if err != nil { - return errors.Wrap(err, "unable to print outputs table") + return fmt.Errorf("unable to print outputs table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block @@ -432,7 +431,7 @@ func (p *Porter) printActionsExplainBlock(bun *PrintableBundle) error { fmt.Fprintln(p.Out, "Actions:") err := p.printActionsExplainTable(bun) if err != nil { - return errors.Wrap(err, "unable to print actions block") + return fmt.Errorf("unable to print actions block: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block @@ -460,7 +459,7 @@ func (p *Porter) printDependenciesExplainBlock(bun *PrintableBundle) error { fmt.Fprintln(p.Out, "Dependencies:") err := p.printDependenciesExplainTable(bun) if err != nil { - return errors.Wrap(err, "unable to print dependencies table") + return fmt.Errorf("unable to print dependencies table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block diff --git a/pkg/porter/generateManifest.go b/pkg/porter/generateManifest.go index c9aa4fdd8..58f463df9 100644 --- a/pkg/porter/generateManifest.go +++ b/pkg/porter/generateManifest.go @@ -1,10 +1,11 @@ package porter import ( + "fmt" + "get.porter.sh/porter/pkg" "get.porter.sh/porter/pkg/build" "get.porter.sh/porter/pkg/yaml" - "github.com/pkg/errors" ) // metadataOpts contain manifest fields eligible for dynamic @@ -21,7 +22,7 @@ func (p *Porter) generateInternalManifest(opts BuildOptions) error { // Create the local app dir if it does not already exist err := p.FileSystem.MkdirAll(build.LOCAL_APP, pkg.FileModeDirectory) if err != nil { - return errors.Wrapf(err, "unable to create directory %s", build.LOCAL_APP) + return fmt.Errorf("unable to create directory %s: %w", build.LOCAL_APP, err) } e := yaml.NewEditor(p.Context) diff --git a/pkg/porter/inspect.go b/pkg/porter/inspect.go index 584816764..476622c32 100644 --- a/pkg/porter/inspect.go +++ b/pkg/porter/inspect.go @@ -7,7 +7,6 @@ import ( "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/printer" "github.com/cnabio/cnab-go/bundle" - "github.com/pkg/errors" ) type InspectableBundle struct { @@ -37,7 +36,7 @@ func (p *Porter) Inspect(ctx context.Context, o ExplainOpts) error { ib, err := generateInspectableBundle(bundleRef) if err != nil { - return errors.Wrap(err, "unable to inspect bundle") + return fmt.Errorf("unable to inspect bundle: %w", err) } return p.printBundleInspect(o, ib) } @@ -107,7 +106,7 @@ func (p *Porter) printInvocationImageInspectBlock(bun *InspectableBundle) error fmt.Fprintln(p.Out, "Invocation Images:") err := p.printInvocationImageInspectTable(bun) if err != nil { - return errors.Wrap(err, "unable to print invocation images table") + return fmt.Errorf("unable to print invocation images table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block return nil @@ -133,7 +132,7 @@ func (p *Porter) printImagesInspectBlock(bun *InspectableBundle) error { fmt.Fprintln(p.Out, "Images:") err := p.printImagesInspectTable(bun) if err != nil { - return errors.Wrap(err, "unable to print images table") + return fmt.Errorf("unable to print images table: %w", err) } fmt.Fprintln(p.Out, "") // force a blank line after this block diff --git a/pkg/porter/install.go b/pkg/porter/install.go index d8a37abf9..0a14d0913 100644 --- a/pkg/porter/install.go +++ b/pkg/porter/install.go @@ -2,11 +2,12 @@ package porter import ( "context" + "errors" + "fmt" "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/storage" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) var _ BundleAction = NewInstallOptions() @@ -74,7 +75,7 @@ func (p *Porter) InstallBundle(ctx context.Context, opts InstallOptions) error { // Create the installation record i = storage.NewInstallation(opts.Namespace, opts.Name) } else { - err = errors.Wrapf(err, "could not retrieve the installation record") + err = fmt.Errorf("could not retrieve the installation record: %w", err) return log.Error(err) } @@ -86,7 +87,7 @@ func (p *Porter) InstallBundle(ctx context.Context, opts InstallOptions) error { i.Labels = opts.ParseLabels() err = p.Installations.UpsertInstallation(ctx, i) if err != nil { - return errors.Wrap(err, "error saving installation record") + return fmt.Errorf("error saving installation record: %w", err) } // Run install using the updated installation record diff --git a/pkg/porter/internal_plugins.go b/pkg/porter/internal_plugins.go index 4f2229e71..57f45328e 100644 --- a/pkg/porter/internal_plugins.go +++ b/pkg/porter/internal_plugins.go @@ -3,6 +3,7 @@ package porter import ( "context" "encoding/json" + "errors" "fmt" "io" @@ -17,7 +18,6 @@ import ( "get.porter.sh/porter/pkg/storage/plugins/mongodb_docker" "get.porter.sh/porter/pkg/tracing" "github.com/hashicorp/go-plugin" - "github.com/pkg/errors" ) type RunInternalPluginOpts struct { @@ -42,7 +42,7 @@ func (o *RunInternalPluginOpts) Validate() error { } if _, ok := internalPlugins[o.Key]; !ok { - return errors.Errorf("invalid plugin key specified: %s", o.Key) + return fmt.Errorf("invalid plugin key specified: %s", o.Key) } return nil diff --git a/pkg/porter/invoke.go b/pkg/porter/invoke.go index 24795fa30..c40622b4d 100644 --- a/pkg/porter/invoke.go +++ b/pkg/porter/invoke.go @@ -2,10 +2,10 @@ package porter import ( "context" + "errors" "fmt" "get.porter.sh/porter/pkg/storage" - "github.com/pkg/errors" ) var _ BundleAction = NewInvokeOptions() @@ -56,7 +56,7 @@ func (p *Porter) InvokeBundle(ctx context.Context, opts InvokeOptions) error { // Only allow actions on a non-existing installation when it won't change anything if action.Modifies || !action.Stateless { - return errors.Wrapf(err, "could not find installation %s/%s", opts.Namespace, opts.Name) + return fmt.Errorf("could not find installation %s/%s: %w", opts.Namespace, opts.Name, err) } // Create an ephemeral installation just for this run diff --git a/pkg/porter/lifecycle.go b/pkg/porter/lifecycle.go index 7a61816f6..54fbd2ad7 100644 --- a/pkg/porter/lifecycle.go +++ b/pkg/porter/lifecycle.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "strings" @@ -11,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/encoding" "get.porter.sh/porter/pkg/storage" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" ) // BundleAction is an interface that defines a method for supplying @@ -73,7 +73,7 @@ func (o *BundleActionOptions) Validate(ctx context.Context, args []string, porte } if o.Name == "" && o.File == "" && o.CNABFile == "" && o.Reference == "" { - return errors.New("No bundle specified. Either an installation name, --reference, --file or --cnab-file must be specified or the current directory must contain a porter.yaml file.") + return errors.New("no bundle specified. Either an installation name, --reference, --file or --cnab-file must be specified or the current directory must contain a porter.yaml file") } return nil @@ -123,12 +123,12 @@ func (p *Porter) resolveBundleReference(ctx context.Context, opts *BundleActionO } else if opts.Name != "" { // Return the bundle associated with the installation i, err := p.Installations.GetInstallation(ctx, opts.Namespace, opts.Name) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "installation %s/%s not found", opts.Namespace, opts.Name) + return cnab.BundleReference{}, fmt.Errorf("installation %s/%s not found: %w", opts.Namespace, opts.Name, err) } if i.Status.BundleReference != "" { ref, err := cnab.ParseOCIReference(i.Status.BundleReference) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "installation.Status.BundleReference is invalid") + return cnab.BundleReference{}, fmt.Errorf("installation.Status.BundleReference is invalid: %w", err) } if err := useReference(ref); err != nil { return cnab.BundleReference{}, err @@ -136,7 +136,7 @@ func (p *Porter) resolveBundleReference(ctx context.Context, opts *BundleActionO } else { // The bundle was installed from source lastRun, err := p.Installations.GetLastRun(ctx, opts.Namespace, opts.Name) if err != nil { - return cnab.BundleReference{}, errors.Wrap(err, "could not load the bundle definition from the installation's last run") + return cnab.BundleReference{}, fmt.Errorf("could not load the bundle definition from the installation's last run: %w", err) } bundleRef = cnab.BundleReference{ @@ -146,12 +146,12 @@ func (p *Porter) resolveBundleReference(ctx context.Context, opts *BundleActionO if lastRun.BundleReference != "" { bundleRef.Reference, err = cnab.ParseOCIReference(lastRun.BundleReference) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "invalid bundle reference, %s, found on the last bundle run record %s", lastRun.BundleReference, lastRun.ID) + return cnab.BundleReference{}, fmt.Errorf("invalid bundle reference, %s, found on the last bundle run record %s: %w", lastRun.BundleReference, lastRun.ID, err) } } } } else { // Nothing was referenced - return cnab.BundleReference{}, errors.New("No bundle specified") + return cnab.BundleReference{}, errors.New("no bundle specified") } if opts.Name == "" { @@ -174,7 +174,7 @@ func (p *Porter) BuildActionArgs(ctx context.Context, installation storage.Insta if opts.RelocationMapping != "" { err := encoding.UnmarshalFile(p.FileSystem, opts.RelocationMapping, &bundleRef.RelocationMap) if err != nil { - return cnabprovider.ActionArguments{}, errors.Wrapf(err, "could not parse the relocation mapping file at %s", opts.RelocationMapping) + return cnabprovider.ActionArguments{}, fmt.Errorf("could not parse the relocation mapping file at %s: %w", opts.RelocationMapping, err) } } diff --git a/pkg/porter/lint.go b/pkg/porter/lint.go index 854cfd4d7..0112104f8 100644 --- a/pkg/porter/lint.go +++ b/pkg/porter/lint.go @@ -9,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/manifest" "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/printer" - "github.com/pkg/errors" ) type LintOptions struct { @@ -38,7 +37,7 @@ func (o *LintOptions) validateFile(cxt *portercontext.Context) error { if o.File == "" { manifestExists, err := cxt.FileSystem.Exists(config.Name) if err != nil { - return errors.Wrap(err, "could not check if porter manifest exists in current directory") + return fmt.Errorf("could not check if porter manifest exists in current directory: %w", err) } if manifestExists { @@ -48,7 +47,7 @@ func (o *LintOptions) validateFile(cxt *portercontext.Context) error { // Verify the file can be accessed if _, err := cxt.FileSystem.Stat(o.File); err != nil { - return errors.Wrapf(err, "unable to access --file %s", o.File) + return fmt.Errorf("unable to access --file %s: %w", o.File, err) } return nil diff --git a/pkg/porter/lint_test.go b/pkg/porter/lint_test.go index 1887bf016..182750927 100644 --- a/pkg/porter/lint_test.go +++ b/pkg/porter/lint_test.go @@ -21,7 +21,7 @@ func TestPorter_Lint_ChecksManifestSchemaVersion(t *testing.T) { wantErr string }{ {name: "valid version", schemaVersion: manifest.SupportedSchemaVersion}, - {name: "invalid version", schemaVersion: "", wantErr: "Invalid schema version"}, + {name: "invalid version", schemaVersion: "", wantErr: "invalid schema version"}, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/porter/list.go b/pkg/porter/list.go index 0fbd76bbf..cd9ebe4b4 100644 --- a/pkg/porter/list.go +++ b/pkg/porter/list.go @@ -14,7 +14,6 @@ import ( "get.porter.sh/porter/pkg/tracing" dtprinter "github.com/carolynvs/datetime-printer" "github.com/cnabio/cnab-go/schema" - "github.com/pkg/errors" ) // ListOptions represent generic options for use by Porter's list commands @@ -152,7 +151,7 @@ func (d DisplayInstallation) ConvertToInstallation() (storage.Installation, erro } if err := i.Validate(); err != nil { - return storage.Installation{}, errors.Wrap(err, "invalid installation") + return storage.Installation{}, fmt.Errorf("invalid installation: %w", err) } return i, nil diff --git a/pkg/porter/logs.go b/pkg/porter/logs.go index cb87165fc..fbfd72f62 100644 --- a/pkg/porter/logs.go +++ b/pkg/porter/logs.go @@ -2,10 +2,10 @@ package porter import ( "context" + "errors" "fmt" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) // LogsShowOptions represent options for an installation logs show command diff --git a/pkg/porter/mixins.go b/pkg/porter/mixins.go index ee799a52b..20daed594 100644 --- a/pkg/porter/mixins.go +++ b/pkg/porter/mixins.go @@ -3,6 +3,7 @@ package porter import ( "bytes" "context" + "errors" "fmt" "io/ioutil" "os" @@ -14,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt/feed" "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/printer" - "github.com/pkg/errors" ) const ( @@ -132,7 +132,7 @@ func (o *MixinsCreateOptions) Validate(args []string, cxt *portercontext.Context } if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, the mixin name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the mixin name, but multiple were received: %s", args) } o.MixinName = args[0] @@ -150,7 +150,7 @@ func (o *MixinsCreateOptions) Validate(args []string, cxt *portercontext.Context } if _, err := cxt.FileSystem.Stat(o.DirPath); err != nil { - return errors.Wrapf(err, "invalid --dir: %s", o.DirPath) + return fmt.Errorf("invalid --dir: %s: %w", o.DirPath, err) } return nil @@ -160,7 +160,7 @@ func (p *Porter) CreateMixin(opts MixinsCreateOptions) error { skeletorDestPath := opts.DirPath + "/" + opts.MixinName if err := exec.Command("git", "clone", SkeletorRepo, skeletorDestPath).Run(); err != nil { - return errors.Wrapf(err, "failed cloning skeletor repo") + return fmt.Errorf("failed cloning skeletor repo: %w", err) } err := os.Rename(skeletorDestPath+"/cmd/skeletor", skeletorDestPath+"/cmd/"+opts.MixinName) diff --git a/pkg/porter/outputs.go b/pkg/porter/outputs.go index 1570748fa..b34175d33 100644 --- a/pkg/porter/outputs.go +++ b/pkg/porter/outputs.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "sort" @@ -9,7 +10,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/printer" "get.porter.sh/porter/pkg/storage" - "github.com/pkg/errors" ) // OutputShowOptions represent options for a bundle output show command @@ -33,7 +33,7 @@ func (o *OutputShowOptions) Validate(args []string, cxt *portercontext.Context) case 1: o.Output = args[0] default: - return errors.Errorf("only one positional argument may be specified, the output name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the output name, but multiple were received: %s", args) } // If not provided, attempt to derive installation name from context @@ -59,7 +59,7 @@ func (o *OutputListOptions) Validate(args []string, cxt *portercontext.Context) // Attempt to derive installation name from context err = o.sharedOptions.defaultBundleFiles(cxt) if err != nil { - return errors.Wrap(err, "installation name must be provided") + return fmt.Errorf("installation name must be provided: %w", err) } return o.ParseFormat() @@ -74,7 +74,7 @@ func (p *Porter) ShowBundleOutput(ctx context.Context, opts *OutputShowOptions) output, err := p.ReadBundleOutput(ctx, opts.Output, opts.Name, opts.Namespace) if err != nil { - return errors.Wrapf(err, "unable to read output '%s' for installation '%s/%s'", opts.Output, opts.Namespace, opts.Name) + return fmt.Errorf("unable to read output '%s' for installation '%s/%s': %w", opts.Output, opts.Namespace, opts.Name, err) } fmt.Fprintln(p.Out, output) diff --git a/pkg/porter/packages.go b/pkg/porter/packages.go index 9b32edf07..f7933a9d7 100644 --- a/pkg/porter/packages.go +++ b/pkg/porter/packages.go @@ -6,7 +6,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/printer" - "github.com/pkg/errors" ) // SearchOptions are options for searching packages @@ -45,7 +44,7 @@ func (o *SearchOptions) validatePackageName(args []string) error { o.Name = strings.ToLower(args[0]) return nil default: - return errors.Errorf("only one positional argument may be specified, the package name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the package name, but multiple were received: %s", args) } } diff --git a/pkg/porter/parameters.go b/pkg/porter/parameters.go index 53d697791..c3309f529 100644 --- a/pkg/porter/parameters.go +++ b/pkg/porter/parameters.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "path/filepath" "sort" @@ -21,7 +22,6 @@ import ( "github.com/cnabio/cnab-go/bundle" "github.com/cnabio/cnab-go/bundle/definition" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" ) @@ -110,7 +110,7 @@ func (o *ParameterOptions) validateParamName(args []string) error { if len(args) == 1 { o.Name = args[0] } else if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, the parameter set name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the parameter set name, but multiple were received: %s", args) } return nil } @@ -150,14 +150,18 @@ func (p *Porter) GenerateParameters(ctx context.Context, opts ParameterOptions) pset, err := genOpts.GenerateParameters() if err != nil { - return errors.Wrap(err, "unable to generate parameter set") + return fmt.Errorf("unable to generate parameter set: %w", err) } pset.Status.Created = time.Now() pset.Status.Modified = pset.Status.Created err = p.Parameters.UpsertParameterSet(ctx, pset) - return errors.Wrapf(err, "unable to save parameter set") + if err != nil { + return fmt.Errorf("unable to save parameter set: %w", err) + } + + return nil } // Validate validates the args provided to Porter's parameter show command @@ -187,29 +191,29 @@ func (p *Porter) EditParameter(ctx context.Context, opts ParameterEditOptions) e contents, err := encoding.MarshalYaml(paramSet) if err != nil { - return errors.Wrap(err, "unable to load parameter set") + return fmt.Errorf("unable to load parameter set: %w", err) } editor := editor.New(p.Context, fmt.Sprintf("porter-%s.yaml", paramSet.Name), contents) output, err := editor.Run(ctx) if err != nil { - return errors.Wrap(err, "unable to open editor to edit parameter set") + return fmt.Errorf("unable to open editor to edit parameter set: %w", err) } err = encoding.UnmarshalYaml(output, ¶mSet) if err != nil { - return errors.Wrap(err, "unable to process parameter set") + return fmt.Errorf("unable to process parameter set: %w", err) } err = p.Parameters.Validate(ctx, paramSet) if err != nil { - return errors.Wrap(err, "parameter set is invalid") + return fmt.Errorf("parameter set is invalid: %w", err) } paramSet.Status.Modified = time.Now() err = p.Parameters.UpdateParameterSet(ctx, paramSet) if err != nil { - return errors.Wrap(err, "unable to save parameter set") + return fmt.Errorf("unable to save parameter set: %w", err) } return nil @@ -307,7 +311,11 @@ func (p *Porter) DeleteParameter(ctx context.Context, opts ParameterDeleteOption } return nil } - return errors.Wrapf(err, "unable to delete parameter set") + if err != nil { + return fmt.Errorf("unable to delete parameter set: %w", err) + } + + return nil } // Validate the args provided to the delete parameter command @@ -322,11 +330,11 @@ func (o *ParameterDeleteOptions) Validate(args []string) error { func validateParameterName(args []string) error { switch len(args) { case 0: - return errors.Errorf("no parameter set name was specified") + return fmt.Errorf("no parameter set name was specified") case 1: return nil default: - return errors.Errorf("only one positional argument may be specified, the parameter set name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the parameter set name, but multiple were received: %s", args) } } @@ -392,7 +400,11 @@ func (p *Porter) loadParameterSets(ctx context.Context, bun cnab.ExtendedBundle, func (p *Porter) loadParameterFromFile(path string) (storage.ParameterSet, error) { var cs storage.ParameterSet err := encoding.UnmarshalFile(p.FileSystem, path, &cs) - return cs, errors.Wrapf(err, "error loading parameter set in %s", path) + if err != nil { + return cs, fmt.Errorf("error loading parameter set in %s: %w", path, err) + } + + return cs, nil } type DisplayValue struct { @@ -512,11 +524,11 @@ func (p *Porter) ParametersApply(ctx context.Context, o ApplyOptions) error { var params storage.ParameterSet err = encoding.UnmarshalFile(p.FileSystem, o.File, ¶ms) if err != nil { - return errors.Wrapf(err, "could not load %s as a parameter set", o.File) + return fmt.Errorf("could not load %s as a parameter set: %w", o.File, err) } if err = params.Validate(); err != nil { - return errors.Wrap(err, "invalid parameter set") + return fmt.Errorf("invalid parameter set: %w", err) } params.Namespace = namespace @@ -524,7 +536,7 @@ func (p *Porter) ParametersApply(ctx context.Context, o ApplyOptions) error { err = p.Parameters.Validate(ctx, params) if err != nil { - return errors.Wrap(err, "parameter set is invalid") + return fmt.Errorf("parameter set is invalid: %w", err) } err = p.Parameters.UpsertParameterSet(ctx, params) @@ -588,7 +600,7 @@ func (p *Porter) resolveParameters(ctx context.Context, installation storage.Ins if def.Type != nil { value, err := def.ConvertValue(unconverted) if err != nil { - return nil, errors.Wrapf(err, "unable to convert parameter's %s value %s to the destination parameter type %s", key, unconverted, def.Type) + return nil, fmt.Errorf("unable to convert parameter's %s value %s to the destination parameter type %s: %w", key, unconverted, def.Type, err) } typedParams[key] = value } else { @@ -607,7 +619,7 @@ func (p *Porter) getUnconvertedValueFromRaw(b cnab.ExtendedBundle, def *definiti if _, err := p.FileSystem.Stat(rawValue); err == nil { bytes, err := p.FileSystem.ReadFile(rawValue) if err != nil { - return "", errors.Wrapf(err, "unable to read file parameter %s", key) + return "", fmt.Errorf("unable to read file parameter %s: %w", key, err) } return base64.StdEncoding.EncodeToString(bytes), nil } @@ -660,14 +672,14 @@ func (p *Porter) resolveParameterSources(ctx context.Context, bun cnab.ExtendedB continue } // Otherwise, something else has happened, perhaps bad data or connectivity problems, we can't ignore it - return nil, errors.Wrapf(err, "could not set parameter %s from output %s of %s", parameterName, outputName, installation) + return nil, fmt.Errorf("could not set parameter %s from output %s of %s: %w", parameterName, outputName, installation, err) } if output.Key != "" { resolved, err := p.Sanitizer.RestoreOutput(ctx, output) if err != nil { - return nil, errors.Wrapf(err, "could not resolve %s's output %s", installation, outputName) + return nil, fmt.Errorf("could not resolve %s's output %s: %w", installation, outputName, err) } output = resolved } @@ -705,7 +717,7 @@ type ParameterCreateOptions struct { func (o *ParameterCreateOptions) Validate(args []string) error { if len(args) > 1 { - return errors.Errorf("only one positional argument may be specified, fileName, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, fileName, but multiple were received: %s", args) } if len(args) > 0 { @@ -713,7 +725,7 @@ func (o *ParameterCreateOptions) Validate(args []string) error { } if o.OutputType == "" && o.FileName != "" && strings.Trim(filepath.Ext(o.FileName), ".") == "" { - return errors.New("could not detect the file format from the file extension (.txt). Specify the format with --output.") + return errors.New("could not detect the file format from the file extension (.txt). Specify the format with --output") } return nil diff --git a/pkg/porter/parameters_test.go b/pkg/porter/parameters_test.go index af232c8e7..e9cfe9ed7 100644 --- a/pkg/porter/parameters_test.go +++ b/pkg/porter/parameters_test.go @@ -707,7 +707,7 @@ func TestParametersCreateOptions_Validate(t *testing.T) { name: "no file format defined from file extension or output flag", args: []string{"parameter-set"}, outputType: "", - wantErr: "could not detect the file format from the file extension (.txt). Specify the format with --output.", + wantErr: "could not detect the file format from the file extension (.txt). Specify the format with --output", }, { name: "different file format", @@ -789,13 +789,13 @@ func TestParametersCreate(t *testing.T) { name: "invalid input: invalid file format from fileName", fileName: "fileName.txt", outputType: "", - wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json.", "txt"), + wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json", "txt"), }, { name: "invalid input: invalid file format from outputType", fileName: "fileName", outputType: "txt", - wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json.", "txt"), + wantErr: fmt.Sprintf("unsupported format %s. Supported formats are: yaml and json", "txt"), }, } diff --git a/pkg/porter/plugins.go b/pkg/porter/plugins.go index 22072520c..83895a8e7 100644 --- a/pkg/porter/plugins.go +++ b/pkg/porter/plugins.go @@ -10,7 +10,6 @@ import ( "get.porter.sh/porter/pkg/plugins" "get.porter.sh/porter/pkg/printer" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" ) // PrintPluginsOptions represent options for the PrintPlugins function @@ -37,12 +36,12 @@ func (o *ShowPluginOptions) Validate(args []string) error { func (o *ShowPluginOptions) validateName(args []string) error { switch len(args) { case 0: - return errors.Errorf("no name was specified") + return fmt.Errorf("no name was specified") case 1: o.Name = strings.ToLower(args[0]) return nil default: - return errors.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) + return fmt.Errorf("only one positional argument may be specified, the name, but multiple were received: %s", args) } } @@ -145,7 +144,7 @@ func (p *Porter) GetPlugin(ctx context.Context, name string) (*plugins.Metadata, plugin, ok := meta.(*plugins.Metadata) if !ok { - return nil, errors.Errorf("could not cast plugin %s to plugins.Metadata", name) + return nil, fmt.Errorf("could not cast plugin %s to plugins.Metadata", name) } return plugin, nil diff --git a/pkg/porter/porter.go b/pkg/porter/porter.go index aa6b6bc7c..af524dced 100644 --- a/pkg/porter/porter.go +++ b/pkg/porter/porter.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "strings" @@ -21,7 +22,6 @@ import ( "get.porter.sh/porter/pkg/templates" "get.porter.sh/porter/pkg/tracing" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) // Porter is the logic behind the porter client. diff --git a/pkg/porter/publish.go b/pkg/porter/publish.go index 77e867759..280febf72 100644 --- a/pkg/porter/publish.go +++ b/pkg/porter/publish.go @@ -5,6 +5,7 @@ import ( "crypto/md5" "encoding/hex" "encoding/json" + "errors" "fmt" "path" "path/filepath" @@ -22,7 +23,6 @@ import ( "github.com/pivotal/image-relocation/pkg/image" "github.com/pivotal/image-relocation/pkg/registry" "github.com/pivotal/image-relocation/pkg/registry/ggcr" - "github.com/pkg/errors" ) // PublishOptions are options that may be specified when publishing a bundle. @@ -40,7 +40,7 @@ func (o *PublishOptions) Validate(cxt *portercontext.Context) error { if o.ArchiveFile != "" { // Verify the archive file can be accessed if _, err := cxt.FileSystem.Stat(o.ArchiveFile); err != nil { - return errors.Wrapf(err, "unable to access --archive %s", o.ArchiveFile) + return fmt.Errorf("unable to access --archive %s: %w", o.ArchiveFile, err) } if o.Reference == "" { @@ -149,7 +149,7 @@ func (p *Porter) publishFromFile(ctx context.Context, opts PublishOptions) error // empty, which is fine - we still may need to pick up tag and/or registry // overrides if err := m.SetInvocationImageAndReference(opts.Reference); err != nil { - return errors.Wrap(err, "unable to set invocation image name and reference") + return fmt.Errorf("unable to set invocation image name and reference: %w", err) } if origInvImg != m.Image { @@ -167,12 +167,12 @@ func (p *Porter) publishFromFile(ctx context.Context, opts PublishOptions) error var bundleRef cnab.BundleReference bundleRef.Reference, err = cnab.ParseOCIReference(m.Reference) if err != nil { - return errors.Wrapf(err, "invalid reference %s", m.Reference) + return fmt.Errorf("invalid reference %s: %w", m.Reference, err) } bundleRef.Digest, err = p.Registry.PushInvocationImage(ctx, m.Image) if err != nil { - return errors.Wrapf(err, "unable to push CNAB invocation image %q", m.Image) + return fmt.Errorf("unable to push CNAB invocation image %q: %w", m.Image, err) } bundleRef.Definition, err = p.rewriteBundleWithInvocationImageDigest(ctx, m, bundleRef.Digest) @@ -212,7 +212,7 @@ func (p *Porter) publishFromArchive(ctx context.Context, opts PublishOptions) er source := p.FileSystem.Abs(opts.ArchiveFile) tmpDir, err := p.FileSystem.TempDir("", "porter") if err != nil { - return errors.Wrap(err, "error creating temp directory for archive extraction") + return fmt.Errorf("error creating temp directory for archive extraction: %w", err) } defer p.FileSystem.RemoveAll(tmpDir) @@ -230,7 +230,7 @@ func (p *Porter) publishFromArchive(ctx context.Context, opts PublishOptions) er client := ggcr.NewRegistryClient() layout, err := client.ReadLayout(filepath.Join(extractedDir, "artifacts/layout")) if err != nil { - return errors.Wrapf(err, "failed to parse OCI Layout from archive %s", opts.ArchiveFile) + return fmt.Errorf("failed to parse OCI Layout from archive %s: %w", opts.ArchiveFile, err) } // Push updated images (renamed based on provided bundle tag) with same digests @@ -296,21 +296,21 @@ func (p *Porter) extractBundle(tmpDir, source string) (cnab.BundleReference, err imp := packager.NewImporter(source, tmpDir, l) err := imp.Import() if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "failed to extract bundle from archive %s", source) + return cnab.BundleReference{}, fmt.Errorf("failed to extract bundle from archive %s: %w", source, err) } bun, err := l.Load(filepath.Join(tmpDir, strings.TrimSuffix(filepath.Base(source), ".tgz"), "bundle.json")) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "failed to load bundle from archive %s", source) + return cnab.BundleReference{}, fmt.Errorf("failed to load bundle from archive %s: %w", source, err) } data, err := p.FileSystem.ReadFile(filepath.Join(tmpDir, strings.TrimSuffix(filepath.Base(source), ".tgz"), "relocation-mapping.json")) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "failed to load relocation-mapping.json from archive %s", source) + return cnab.BundleReference{}, fmt.Errorf("failed to load relocation-mapping.json from archive %s: %w", source, err) } var reloMap relocation.ImageRelocationMap err = json.Unmarshal(data, &reloMap) if err != nil { - return cnab.BundleReference{}, errors.Wrapf(err, "failed to parse relocation-mapping.json from archive %s", source) + return cnab.BundleReference{}, fmt.Errorf("failed to parse relocation-mapping.json from archive %s: %w", source, err) } return cnab.BundleReference{Definition: cnab.ExtendedBundle{Bundle: *bun}, RelocationMap: reloMap}, nil @@ -321,17 +321,17 @@ func (p *Porter) extractBundle(tmpDir, source string) (cnab.BundleReference, err func pushUpdatedImage(layout registry.Layout, origImg string, newImgName image.Name) (image.Digest, error) { origImgName, err := image.NewName(origImg) if err != nil { - return image.EmptyDigest, errors.Wrapf(err, "unable to parse image %q into domain/path components", origImg) + return image.EmptyDigest, fmt.Errorf("unable to parse image %q into domain/path components: %w", origImg, err) } digest, err := layout.Find(origImgName) if err != nil { - return image.EmptyDigest, errors.Wrapf(err, "unable to find image %s in archived OCI Layout", origImgName.String()) + return image.EmptyDigest, fmt.Errorf("unable to find image %s in archived OCI Layout: %w", origImgName.String(), err) } err = layout.Push(digest, newImgName) if err != nil { - return image.EmptyDigest, errors.Wrapf(err, "unable to push image %s", newImgName.String()) + return image.EmptyDigest, fmt.Errorf("unable to push image %s: %w", newImgName.String(), err) } return digest, nil @@ -341,7 +341,7 @@ func pushUpdatedImage(layout registry.Layout, origImg string, newImgName image.N func (p *Porter) updateBundleWithNewImage(bun cnab.ExtendedBundle, newImg image.Name, digest image.Digest, index interface{}) error { taggedImage, err := p.rewriteImageWithDigest(newImg.String(), digest.String()) if err != nil { - return errors.Wrapf(err, "unable to update image reference for %s", newImg.String()) + return fmt.Errorf("unable to update image reference for %s: %w", newImg.String(), err) } // update bundle with new image @@ -372,12 +372,12 @@ func (p *Porter) updateBundleWithNewImage(bun cnab.ExtendedBundle, newImg image. func getNewImageNameFromBundleReference(origImg, bundleTag string) (image.Name, error) { origName, err := image.NewName(origImg) if err != nil { - return image.EmptyName, errors.Wrapf(err, "unable to parse image %q into domain/path components", origImg) + return image.EmptyName, fmt.Errorf("unable to parse image %q into domain/path components: %w", origImg, err) } bundleName, err := image.NewName(bundleTag) if err != nil { - return image.EmptyName, errors.Wrapf(err, "unable to parse bundle tag %q into domain/path components", bundleTag) + return image.EmptyName, fmt.Errorf("unable to parse bundle tag %q into domain/path components: %w", bundleTag, err) } // Use the original image name with the bundle location to generate a randomized tag @@ -389,7 +389,7 @@ func getNewImageNameFromBundleReference(origImg, bundleTag string) (image.Name, imgName := bundleName.Name() newImgName, err := image.NewName(imgName) if err != nil { - return image.EmptyName, errors.Wrapf(err, "unable to parse bundle %q into domain/path components", bundleName.Name()) + return image.EmptyName, fmt.Errorf("unable to parse bundle %q into domain/path components: %w", bundleName.Name(), err) } return newImgName.WithTag(imgTag) @@ -398,19 +398,19 @@ func getNewImageNameFromBundleReference(origImg, bundleTag string) (image.Name, func (p *Porter) rewriteBundleWithInvocationImageDigest(ctx context.Context, m *manifest.Manifest, digest digest.Digest) (cnab.ExtendedBundle, error) { taggedImage, err := p.rewriteImageWithDigest(m.Image, digest.String()) if err != nil { - return cnab.ExtendedBundle{}, errors.Wrap(err, "unable to update invocation image reference") + return cnab.ExtendedBundle{}, fmt.Errorf("unable to update invocation image reference: %w", err) } m.Image = taggedImage fmt.Fprintln(p.Out, "\nRewriting CNAB bundle.json...") err = p.buildBundle(ctx, m, digest) if err != nil { - return cnab.ExtendedBundle{}, errors.Wrap(err, "unable to rewrite CNAB bundle.json with updated invocation image digest") + return cnab.ExtendedBundle{}, fmt.Errorf("unable to rewrite CNAB bundle.json with updated invocation image digest: %w", err) } bun, err := cnab.LoadBundle(p.Context, build.LOCAL_BUNDLE) if err != nil { - return cnab.ExtendedBundle{}, errors.Wrap(err, "unable to load CNAB bundle") + return cnab.ExtendedBundle{}, fmt.Errorf("unable to load CNAB bundle: %w", err) } return bun, nil diff --git a/pkg/porter/publish_test.go b/pkg/porter/publish_test.go index 1a23570f0..6af95316c 100644 --- a/pkg/porter/publish_test.go +++ b/pkg/porter/publish_test.go @@ -1,6 +1,7 @@ package porter import ( + "errors" "testing" "get.porter.sh/porter/pkg" @@ -8,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/cnab" "github.com/cnabio/cnab-go/bundle" "github.com/pivotal/image-relocation/pkg/image" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/porter/pull.go b/pkg/porter/pull.go index a93bbfd26..d763a5165 100644 --- a/pkg/porter/pull.go +++ b/pkg/porter/pull.go @@ -1,9 +1,10 @@ package porter import ( + "fmt" + "get.porter.sh/porter/pkg/cache" "get.porter.sh/porter/pkg/cnab" - "github.com/pkg/errors" ) type BundlePullOptions struct { @@ -31,7 +32,7 @@ func (b *BundlePullOptions) GetReference() cnab.OCIReference { func (b *BundlePullOptions) validateReference() error { ref, err := cnab.ParseOCIReference(b.Reference) if err != nil { - return errors.Wrap(err, "invalid value for --reference, specified value should be of the form REGISTRY/bundle:tag") + return fmt.Errorf("invalid value for --reference, specified value should be of the form REGISTRY/bundle:tag: %w", err) } b._ref = &ref return nil diff --git a/pkg/porter/reconcile.go b/pkg/porter/reconcile.go index a56eac69c..28d9b40a4 100644 --- a/pkg/porter/reconcile.go +++ b/pkg/porter/reconcile.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "sort" @@ -10,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/tracing" "get.porter.sh/porter/pkg/yaml" "github.com/google/go-cmp/cmp" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" ) @@ -55,7 +55,7 @@ func (p *Porter) ReconcileInstallation(ctx context.Context, opts ReconcileOption } if !ok { instYaml, _ := yaml.Marshal(opts.Installation) - return errors.Errorf("The installation does not define a valid bundle reference.\n%s", instYaml) + return fmt.Errorf("the installation does not define a valid bundle reference.\n%s", instYaml) } // Configure the bundle action that we should execute IF IT'S OUT OF SYNC @@ -227,12 +227,12 @@ func (p *Porter) IsInstallationInSync(ctx context.Context, i storage.Installatio oldParams, err := prepParametersForComparison(lastRunParams) if err != nil { - return false, errors.Wrapf(err, "error prepping old parameters for comparision") + return false, fmt.Errorf("error prepping old parameters for comparision: %w", err) } newParams, err := prepParametersForComparison(resolvedParams) if err != nil { - return false, errors.Wrapf(err, "error prepping current parameters for comparision") + return false, fmt.Errorf("error prepping current parameters for comparision: %w", err) } if !cmp.Equal(oldParams, newParams) { diff --git a/pkg/porter/resolver.go b/pkg/porter/resolver.go index afbc4c807..0838c1529 100644 --- a/pkg/porter/resolver.go +++ b/pkg/porter/resolver.go @@ -1,9 +1,10 @@ package porter import ( + "fmt" + "get.porter.sh/porter/pkg/cache" cnabtooci "get.porter.sh/porter/pkg/cnab/cnab-to-oci" - "github.com/pkg/errors" ) type BundleResolver struct { @@ -17,7 +18,7 @@ func (r *BundleResolver) Resolve(opts BundlePullOptions) (cache.CachedBundle, er if !opts.Force { cachedBundle, ok, err := r.Cache.FindBundle(opts.GetReference()) if err != nil { - return cache.CachedBundle{}, errors.Wrapf(err, "unable to load bundle %s from cache", opts.Reference) + return cache.CachedBundle{}, fmt.Errorf("unable to load bundle %s from cache: %w", opts.Reference, err) } // If we found the bundle, return the path to the bundle.json if ok { diff --git a/pkg/porter/run.go b/pkg/porter/run.go index 6f4ffb6ab..370882d85 100644 --- a/pkg/porter/run.go +++ b/pkg/porter/run.go @@ -9,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/manifest" "get.porter.sh/porter/pkg/runtime" "get.porter.sh/porter/pkg/schema" - "github.com/pkg/errors" ) type RunOptions struct { @@ -63,7 +62,7 @@ func (o *RunOptions) defaultDebug() error { debug, err := strconv.ParseBool(rawDebug) if err != nil { - return errors.Wrapf(err, "invalid PORTER_DEBUG, expected a bool (true/false) but got %s", rawDebug) + return fmt.Errorf("invalid PORTER_DEBUG, expected a bool (true/false) but got %s: %w", rawDebug, err) } if debug { diff --git a/pkg/porter/schema.go b/pkg/porter/schema.go index 44d414bc1..e7ba13dcb 100644 --- a/pkg/porter/schema.go +++ b/pkg/porter/schema.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/PaesslerAG/jsonpath" - "github.com/pkg/errors" ) type jsonSchema = map[string]interface{} @@ -22,7 +21,7 @@ func (p *Porter) PrintManifestSchema(ctx context.Context) error { schema, err := json.MarshalIndent(&schemaMap, "", " ") if err != nil { - return errors.Wrap(err, "could not marshal the composite porter manifest schema") + return fmt.Errorf("could not marshal the composite porter manifest schema: %w", err) } fmt.Fprintln(p.Out, string(schema)) @@ -32,7 +31,7 @@ func (p *Porter) PrintManifestSchema(ctx context.Context) error { func (p *Porter) GetManifestSchema(ctx context.Context) (jsonSchema, error) { replacementSchema, err := p.GetReplacementSchema() if err != nil && p.Debug { - fmt.Fprintln(p.Err, errors.Wrap(err, "ignoring replacement schema")) + fmt.Fprintln(p.Err, fmt.Errorf("ignoring replacement schema: %w", err)) } if replacementSchema != nil { return replacementSchema, nil @@ -46,7 +45,7 @@ func (p *Porter) GetManifestSchema(ctx context.Context) (jsonSchema, error) { manifestSchema := make(jsonSchema) err = json.Unmarshal(b, &manifestSchema) if err != nil { - return nil, errors.Wrap(err, "could not unmarshal the root porter manifest schema") + return nil, fmt.Errorf("could not unmarshal the root porter manifest schema: %w", err) } combinedSchema, err := p.injectMixinSchemas(ctx, manifestSchema) @@ -64,27 +63,27 @@ func (p *Porter) GetManifestSchema(ctx context.Context) (jsonSchema, error) { func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSchema) (jsonSchema, error) { propertiesSchema, ok := manifestSchema["properties"].(jsonSchema) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid properties type, expected map[string]interface{} but got %T", manifestSchema["properties"]) + return nil, fmt.Errorf("root porter manifest schema has invalid properties type, expected map[string]interface{} but got %T", manifestSchema["properties"]) } additionalPropertiesSchema, ok := manifestSchema["additionalProperties"].(jsonSchema) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid additionalProperties type, expected map[string]interface{} but got %T", manifestSchema["additionalProperties"]) + return nil, fmt.Errorf("root porter manifest schema has invalid additionalProperties type, expected map[string]interface{} but got %T", manifestSchema["additionalProperties"]) } mixinSchema, ok := propertiesSchema["mixins"].(jsonSchema) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid properties.mixins type, expected map[string]interface{} but got %T", propertiesSchema["mixins"]) + return nil, fmt.Errorf("root porter manifest schema has invalid properties.mixins type, expected map[string]interface{} but got %T", propertiesSchema["mixins"]) } mixinItemSchema, ok := mixinSchema["items"].(jsonSchema) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid properties.mixins.items type, expected map[string]interface{} but got %T", mixinSchema["items"]) + return nil, fmt.Errorf("root porter manifest schema has invalid properties.mixins.items type, expected map[string]interface{} but got %T", mixinSchema["items"]) } mixinEnumSchema, ok := mixinItemSchema["enum"].([]interface{}) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid properties.mixins.items.enum type, expected []interface{} but got %T", mixinItemSchema["enum"]) + return nil, fmt.Errorf("root porter manifest schema has invalid properties.mixins.items.enum type, expected []interface{} but got %T", mixinItemSchema["enum"]) } coreActions := []string{"install", "upgrade", "uninstall"} // custom actions are defined in json schema as additionalProperties @@ -92,7 +91,7 @@ func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSche for _, action := range coreActions { actionSchema, ok := propertiesSchema[action].(jsonSchema) if !ok { - return nil, errors.Errorf("root porter manifest schema has invalid properties.%s type, expected map[string]interface{} but got %T", action, propertiesSchema[string(action)]) + return nil, fmt.Errorf("root porter manifest schema has invalid properties.%s type, expected map[string]interface{} but got %T", action, propertiesSchema[string(action)]) } actionSchemas[action] = actionSchema } @@ -108,7 +107,7 @@ func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSche if err != nil { // if a mixin can't report its schema, don't include it and keep going if p.Debug { - fmt.Fprintln(p.Err, errors.Wrapf(err, "could not query mixin %s for its schema", mixin)) + fmt.Fprintln(p.Err, fmt.Errorf("could not query mixin %s for its schema: %w", mixin, err)) } continue } @@ -119,7 +118,7 @@ func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSche mixinSchemaMap := make(jsonSchema) err = json.Unmarshal([]byte(mixinSchema), &mixinSchemaMap) if err != nil && p.Debug { - fmt.Fprintln(p.Err, errors.Wrapf(err, "could not unmarshal mixin schema for %s, %q", mixin, mixinSchema)) + fmt.Fprintln(p.Err, fmt.Errorf("could not unmarshal mixin schema for %s, %q: %w", mixin, mixinSchema, err)) continue } @@ -131,16 +130,14 @@ func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSche for _, action := range coreActions { actionItemSchema, ok := actionSchemas[action]["items"].(jsonSchema) if !ok && p.Debug { - fmt.Fprintln(p.Err, errors.Errorf("root porter manifest schema has invalid properties.%s.items type, expected map[string]interface{} but got %T", action, actionSchemas[string(action)]["items"])) + fmt.Fprintln(p.Err, fmt.Errorf("root porter manifest schema has invalid properties.%s.items type, expected map[string]interface{} but got %T", action, actionSchemas[string(action)]["items"])) continue } actionAnyOfSchema, ok := actionItemSchema["anyOf"].([]interface{}) - if !ok { - if err != nil && p.Debug { - fmt.Fprintln(p.Err, errors.Errorf("root porter manifest schema has invalid properties.%s.items.anyOf type, expected []interface{} but got %T", action, actionItemSchema["anyOf"])) - continue - } + if !ok && p.Debug { + fmt.Fprintln(p.Err, fmt.Errorf("root porter manifest schema has invalid properties.%s.items.anyOf type, expected []interface{} but got %T", action, actionItemSchema["anyOf"])) + continue } actionRef := fmt.Sprintf("#/mixin.%s/definitions/%sStep", mixin, action) @@ -154,13 +151,13 @@ func (p *Porter) injectMixinSchemas(ctx context.Context, manifestSchema jsonSche if err == nil { actionItemSchema, ok := additionalPropertiesSchema["items"].(jsonSchema) if !ok && p.Debug { - fmt.Fprintln(p.Err, errors.Errorf("root porter manifest schema has invalid additionalProperties.items type, expected map[string]interface{} but got %T", additionalPropertiesSchema["items"])) + fmt.Fprintln(p.Err, fmt.Errorf("root porter manifest schema has invalid additionalProperties.items type, expected map[string]interface{} but got %T", additionalPropertiesSchema["items"])) continue } actionAnyOfSchema, ok := actionItemSchema["anyOf"].([]interface{}) if !ok && p.Debug { - fmt.Fprintln(p.Err, errors.Errorf("root porter manifest schema has invalid additionalProperties.items.anyOf type, expected []interface{} but got %T", actionItemSchema["anyOf"])) + fmt.Fprintln(p.Err, fmt.Errorf("root porter manifest schema has invalid additionalProperties.items.anyOf type, expected []interface{} but got %T", actionItemSchema["anyOf"])) continue } @@ -189,13 +186,13 @@ func (p *Porter) GetReplacementSchema() (jsonSchema, error) { b, err := p.FileSystem.ReadFile(replacementSchemaPath) if err != nil { - return nil, errors.Wrapf(err, "could not read replacement schema at %s", replacementSchemaPath) + return nil, fmt.Errorf("could not read replacement schema at %s: %w", replacementSchemaPath, err) } replacementSchema := make(jsonSchema) err = json.Unmarshal(b, &replacementSchema) if err != nil { - return nil, errors.Wrapf(err, "could not unmarshal replacement schema in %s", replacementSchemaPath) + return nil, fmt.Errorf("could not unmarshal replacement schema in %s: %w", replacementSchemaPath, err) } return replacementSchema, nil diff --git a/pkg/porter/stamp.go b/pkg/porter/stamp.go index 917258f09..6017695c1 100644 --- a/pkg/porter/stamp.go +++ b/pkg/porter/stamp.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "strings" @@ -10,7 +11,6 @@ import ( configadapter "get.porter.sh/porter/pkg/cnab/config-adapter" "get.porter.sh/porter/pkg/manifest" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) // ensureLocalBundleIsUpToDate ensures that the bundle is up to date with the porter manifest, @@ -64,7 +64,7 @@ func (p *Porter) IsBundleUpToDate(ctx context.Context, opts bundleFileOptions) ( if exists, _ := p.FileSystem.Exists(opts.CNABFile); exists { bun, err := cnab.LoadBundle(p.Context, opts.CNABFile) if err != nil { - return false, errors.Wrapf(err, "could not marshal data from %s", opts.CNABFile) + return false, fmt.Errorf("could not marshal data from %s: %w", opts.CNABFile, err) } // Check whether invocation images exist in host registry. @@ -90,19 +90,19 @@ func (p *Porter) IsBundleUpToDate(ctx context.Context, opts bundleFileOptions) ( oldStamp, err := configadapter.LoadStamp(bun) if err != nil { - return false, errors.Wrapf(err, "could not load stamp from %s", opts.CNABFile) + return false, fmt.Errorf("could not load stamp from %s: %w", opts.CNABFile, err) } mixins, err := p.getUsedMixins(ctx, m) if err != nil { - return false, errors.Wrapf(err, "error while listing used mixins") + return false, fmt.Errorf("error while listing used mixins: %w", err) } converter := configadapter.NewManifestConverter(p.Config, m, nil, mixins) newDigest, err := converter.DigestManifest() if err != nil { if p.Debug { - fmt.Fprintln(p.Err, errors.Wrap(err, "could not determine if the bundle is up-to-date so will rebuild just in case")) + fmt.Fprintln(p.Err, fmt.Errorf("could not determine if the bundle is up-to-date so will rebuild just in case: %w", err)) } return false, nil } diff --git a/pkg/porter/storage.go b/pkg/porter/storage.go index 7c28de17f..61b87d731 100644 --- a/pkg/porter/storage.go +++ b/pkg/porter/storage.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "io/fs" "os" @@ -9,7 +10,6 @@ import ( "get.porter.sh/porter/pkg" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) func (p *Porter) MigrateStorage(ctx context.Context) error { @@ -37,14 +37,14 @@ func (p *Porter) FixPermissions() error { if os.IsNotExist(err) { return nil } else { - return errors.Wrapf(err, "error checking file permissions for %s", path) + return fmt.Errorf("error checking file permissions for %s: %w", path, err) } } gotPerms := info.Mode().Perm() if mode != gotPerms|mode { if err := p.FileSystem.Chmod(path, mode); err != nil { - return errors.Wrapf(err, "could not set permissions on file %s to %o", path, mode) + return fmt.Errorf("could not set permissions on file %s to %o: %w", path, mode, err) } } return nil @@ -55,14 +55,14 @@ func (p *Porter) FixPermissions() error { p.FileSystem.Walk(dir, func(path string, info fs.FileInfo, err error) error { if err != nil { if !os.IsNotExist(err) { - bigErr = multierror.Append(bigErr, errors.Wrapf(err, "error walking path %s", path)) + bigErr = multierror.Append(bigErr, fmt.Errorf("error walking path %s: %w", path, err)) } return nil } if info.IsDir() { if err := p.FileSystem.Chmod(path, pkg.FileModeDirectory); err != nil { - bigErr = multierror.Append(bigErr, errors.Wrapf(err, "could not set permissions on directory %s to %o", path, mode)) + bigErr = multierror.Append(bigErr, fmt.Errorf("could not set permissions on directory %s to %o: %w", path, mode, err)) } } else { if err = fixFile(path, mode); err != nil { diff --git a/pkg/porter/uninstall.go b/pkg/porter/uninstall.go index 6b48d2596..8e9a8436d 100644 --- a/pkg/porter/uninstall.go +++ b/pkg/porter/uninstall.go @@ -2,6 +2,7 @@ package porter import ( "context" + "errors" "fmt" "io" @@ -9,7 +10,6 @@ import ( "get.porter.sh/porter/pkg/storage" "get.porter.sh/porter/pkg/tracing" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) var _ BundleAction = NewUninstallOptions() @@ -80,7 +80,7 @@ func (p *Porter) UninstallBundle(ctx context.Context, opts UninstallOptions) err installation, err := p.Installations.GetInstallation(ctx, opts.Namespace, opts.Name) if err != nil { - return errors.Wrapf(err, "could not find installation %s/%s", opts.Namespace, opts.Name) + return fmt.Errorf("could not find installation %s/%s: %w", opts.Namespace, opts.Name, err) } err = p.applyActionOptionsToInstallation(ctx, &installation, opts.BundleActionOptions) @@ -107,7 +107,7 @@ func (p *Porter) UninstallBundle(ctx context.Context, opts UninstallOptions) err uninstallErrs = multierror.Append(uninstallErrs, err) // If the installation is not found, no further action is needed - err := errors.Cause(err) + err := errors.Unwrap(err) if errors.Is(err, storage.ErrNotFound{}) { return err } diff --git a/pkg/porter/uninstall_test.go b/pkg/porter/uninstall_test.go index 6ff8c6e71..9585c7140 100644 --- a/pkg/porter/uninstall_test.go +++ b/pkg/porter/uninstall_test.go @@ -2,10 +2,10 @@ package porter import ( "bytes" + "errors" "fmt" "testing" - "github.com/pkg/errors" "github.com/stretchr/testify/require" ) diff --git a/pkg/porter/upgrade.go b/pkg/porter/upgrade.go index f1243c3e2..b4f977458 100644 --- a/pkg/porter/upgrade.go +++ b/pkg/porter/upgrade.go @@ -2,12 +2,12 @@ package porter import ( "context" + "errors" "fmt" "time" "get.porter.sh/porter/pkg/cnab" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" ) var _ BundleAction = NewUpgradeOptions() @@ -61,7 +61,7 @@ func (p *Porter) UpgradeBundle(ctx context.Context, opts UpgradeOptions) error { // Sync any changes specified by the user to the installation before running upgrade i, err := p.Installations.GetInstallation(ctx, opts.Namespace, opts.Name) if err != nil { - return errors.Wrapf(err, "could not find installation %s/%s", opts.Namespace, opts.Name) + return fmt.Errorf("could not find installation %s/%s: %w", opts.Namespace, opts.Name, err) } if opts.Reference != "" { diff --git a/pkg/porter/version.go b/pkg/porter/version.go index c41549e8b..e8ced1c1f 100644 --- a/pkg/porter/version.go +++ b/pkg/porter/version.go @@ -12,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/pkgmgmt" "get.porter.sh/porter/pkg/porter/version" "get.porter.sh/porter/pkg/printer" - "github.com/pkg/errors" ) type VersionOpts struct { @@ -106,7 +105,7 @@ Mixins ` tmpl, err := template.New("systemDebugInfo").Parse(plaintextTmpl) if err != nil { - return errors.Wrap(err, "Failed to parse plaintext template") + return fmt.Errorf("Failed to parse plaintext template: %w", err) } err = tmpl.Execute(p.Out, sysDebugInfo) return err diff --git a/pkg/portercontext/context.go b/pkg/portercontext/context.go index dfeacf0a2..915616f6b 100644 --- a/pkg/portercontext/context.go +++ b/pkg/portercontext/context.go @@ -18,7 +18,6 @@ import ( "github.com/hashicorp/go-multierror" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" - "github.com/pkg/errors" "github.com/spf13/afero" "go.opentelemetry.io/otel/attribute" "go.uber.org/zap" @@ -182,7 +181,7 @@ func (c *Context) configureLoggingWith(ctx context.Context, baseLogger zapcore.C if c.logCfg.LogToFile { fileLogger, err = c.configureFileLog(c.logCfg.LogDirectory) if err != nil { - tmpLog.Error(errors.Wrap(err, "could not configure a file logger").Error()) + tmpLog.Error(fmt.Errorf("could not configure a file logger: %w", err).Error()) } else { tmpLog.Debug("Writing logs to " + c.logFile.Name()) } @@ -194,7 +193,7 @@ func (c *Context) configureLoggingWith(ctx context.Context, baseLogger zapcore.C if !c.tracerInitalized { err = c.configureTelemetry(ctx, c.logCfg, tmpLog) if err != nil { - tmpLog.Error(errors.Wrap(err, "could not configure a tracer").Error()) + tmpLog.Error(fmt.Errorf("could not configure a tracer: %w", err).Error()) } } } else { @@ -235,7 +234,7 @@ func (c *Context) configureFileLog(dir string) (zapcore.Core, error) { if c.logFile == nil { // We may have already opened this logfile, and we are just changing the log level f, err := c.FileSystem.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, pkg.FileModeWritable) if err != nil { - return zapcore.NewNopCore(), errors.Wrapf(err, "could not start log file at %s", logfile) + return zapcore.NewNopCore(), fmt.Errorf("could not start log file at %s: %w", logfile, err) } c.logFile = f } @@ -443,7 +442,7 @@ func (c *Context) CopyDirectory(srcDir, destDir string, includeBaseDir bool) err return c.FileSystem.Walk(srcDir, func(path string, info os.FileInfo, err error) error { if err != nil { - return errors.WithStack(err) + return err } // Translate the path from the src to the final destination @@ -453,7 +452,12 @@ func (c *Context) CopyDirectory(srcDir, destDir string, includeBaseDir bool) err } if info.IsDir() { - return errors.WithStack(c.FileSystem.MkdirAll(dest, info.Mode())) + err := c.FileSystem.MkdirAll(dest, info.Mode()) + if err != nil { + return err + } + + return nil } return c.CopyFile(path, dest) @@ -463,16 +467,20 @@ func (c *Context) CopyDirectory(srcDir, destDir string, includeBaseDir bool) err func (c *Context) CopyFile(src, dest string) error { info, err := c.FileSystem.Stat(src) if err != nil { - return errors.WithStack(err) + return err } data, err := c.FileSystem.ReadFile(src) if err != nil { - return errors.WithStack(err) + return err } err = c.FileSystem.WriteFile(dest, data, info.Mode()) - return errors.WithStack(err) + if err != nil { + return err + } + + return nil } // WriteMixinOutputToFile writes the provided bytes (representing a mixin output) @@ -484,7 +492,7 @@ func (c *Context) WriteMixinOutputToFile(filename string, bytes []byte) error { } if !exists { if err := c.FileSystem.MkdirAll(MixinOutputsDir, pkg.FileModeDirectory); err != nil { - return errors.Wrap(err, "couldn't make output directory") + return fmt.Errorf("couldn't make output directory: %w", err) } } diff --git a/pkg/portercontext/helpers.go b/pkg/portercontext/helpers.go index 860af3888..edb79bfc6 100644 --- a/pkg/portercontext/helpers.go +++ b/pkg/portercontext/helpers.go @@ -3,6 +3,7 @@ package portercontext import ( "bytes" "context" + "errors" "fmt" "io" "io/ioutil" @@ -16,7 +17,6 @@ import ( "get.porter.sh/porter/pkg" "get.porter.sh/porter/pkg/test" "github.com/carolynvs/aferox" - "github.com/pkg/errors" "github.com/spf13/afero" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" @@ -142,12 +142,12 @@ func (c *TestContext) AddTestFileFromRoot(src, dest string) []byte { // mode is optional and only the first one passed is used. func (c *TestContext) AddTestFile(src, dest string, mode ...os.FileMode) []byte { if strings.Contains(src, "..") { - c.T.Fatal(errors.New("Use AddTestFileFromRoot when referencing a test file in a different directory than the test")) + c.T.Fatal(errors.New("use AddTestFileFromRoot when referencing a test file in a different directory than the test")) } data, err := ioutil.ReadFile(src) if err != nil { - c.T.Fatal(errors.Wrapf(err, "error reading file %s from host filesystem", src)) + c.T.Fatal(fmt.Errorf("error reading file %s from host filesystem: %w", src, err)) } var perms os.FileMode @@ -164,7 +164,7 @@ func (c *TestContext) AddTestFile(src, dest string, mode ...os.FileMode) []byte err = c.FileSystem.WriteFile(dest, data, perms) if err != nil { - c.T.Fatal(errors.Wrapf(err, "error writing file %s to test filesystem", dest)) + c.T.Fatal(fmt.Errorf("error writing file %s to test filesystem: %w", dest, err)) } return data @@ -184,7 +184,7 @@ func (c *TestContext) AddTestDirectoryFromRoot(srcDir, destDir string) { // mode is optional and should only be specified once func (c *TestContext) AddTestDirectory(srcDir, destDir string, mode ...os.FileMode) { if strings.Contains(srcDir, "..") { - c.T.Fatal(errors.New("Use AddTestDirectoryFromRoot when referencing a test directory in a different directory than the test")) + c.T.Fatal(errors.New("use AddTestDirectoryFromRoot when referencing a test directory in a different directory than the test")) } err := filepath.Walk(srcDir, func(path string, info os.FileInfo, err error) error { diff --git a/pkg/portercontext/telemetry.go b/pkg/portercontext/telemetry.go index 015ca1dfb..9942c30c6 100644 --- a/pkg/portercontext/telemetry.go +++ b/pkg/portercontext/telemetry.go @@ -11,7 +11,6 @@ import ( "get.porter.sh/porter/pkg" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" @@ -137,14 +136,14 @@ func (c *Context) createTraceClient(cfg LogConfiguration) (otlptrace.Client, err if cfg.TelemetryCertificate != "" { creds, err := credentials.NewClientTLSFromFile(cfg.TelemetryCertificate, "") if err != nil { - return nil, errors.Wrapf(err, "invalid telemetry certificate in %s", cfg.TelemetryCertificate) + return nil, fmt.Errorf("invalid telemetry certificate in %s: %w", cfg.TelemetryCertificate, err) } opts = append(opts, otlptracegrpc.WithTLSCredentials(creds)) } if cfg.TelemetryTimeout != "" { timeout, err := time.ParseDuration(cfg.TelemetryTimeout) if err != nil { - return nil, errors.Wrapf(err, "invalid telemetry timeout %s", cfg.TelemetryTimeout) + return nil, fmt.Errorf("invalid telemetry timeout %s: %w", cfg.TelemetryTimeout, err) } opts = append(opts, otlptracegrpc.WithTimeout(timeout)) } @@ -166,18 +165,18 @@ func (c *Context) createTraceClient(cfg LogConfiguration) (otlptrace.Client, err if cfg.TelemetryCertificate != "" { certB, err := c.FileSystem.ReadFile(cfg.TelemetryCertificate) if err != nil { - return nil, errors.Wrapf(err, "invalid telemetry certificate in %s", cfg.TelemetryCertificate) + return nil, fmt.Errorf("invalid telemetry certificate in %s: %w", cfg.TelemetryCertificate, err) } cp := x509.NewCertPool() if ok := cp.AppendCertsFromPEM(certB); !ok { - return nil, errors.Errorf("could not use certificate in %s", cfg.TelemetryCertificate) + return nil, fmt.Errorf("could not use certificate in %s", cfg.TelemetryCertificate) } opts = append(opts, otlptracehttp.WithTLSClientConfig(&tls.Config{RootCAs: cp})) } if cfg.TelemetryTimeout != "" { timeout, err := time.ParseDuration(cfg.TelemetryTimeout) if err != nil { - return nil, errors.Wrapf(err, "invalid telemetry timeout %s. Supported values are durations such as 30s or 1m.", cfg.TelemetryTimeout) + return nil, fmt.Errorf("invalid telemetry timeout %s. Supported values are durations such as 30s or 1m: %w", cfg.TelemetryTimeout, err) } opts = append(opts, otlptracehttp.WithTimeout(timeout)) } @@ -196,6 +195,6 @@ func (c *Context) createTraceClient(cfg LogConfiguration) (otlptrace.Client, err } return otlptracehttp.NewClient(opts...), nil default: - return nil, errors.Errorf("invalid OTEL_EXPORTER_OTLP_PROTOCOL value %s. Only grpc and http/protobuf are supported", cfg.TelemetryProtocol) + return nil, fmt.Errorf("invalid OTEL_EXPORTER_OTLP_PROTOCOL value %s. Only grpc and http/protobuf are supported", cfg.TelemetryProtocol) } } diff --git a/pkg/printer/json.go b/pkg/printer/json.go index 3a02c9a22..d1b0da3ed 100644 --- a/pkg/printer/json.go +++ b/pkg/printer/json.go @@ -5,13 +5,12 @@ import ( "io" "get.porter.sh/porter/pkg/encoding" - "github.com/pkg/errors" ) func PrintJson(out io.Writer, v interface{}) error { b, err := encoding.MarshalJson(v) if err != nil { - return errors.Wrap(err, "could not marshal value to json") + return fmt.Errorf("could not marshal value to json: %w", err) } fmt.Fprintln(out, string(b)) return nil diff --git a/pkg/printer/printer.go b/pkg/printer/printer.go index 0d92c6e0c..a035752b1 100644 --- a/pkg/printer/printer.go +++ b/pkg/printer/printer.go @@ -1,9 +1,8 @@ package printer import ( + "fmt" "strings" - - "github.com/pkg/errors" ) type Format string @@ -34,7 +33,7 @@ func (p *PrintOptions) ParseFormat() error { p.Format = format return nil default: - return errors.Errorf("invalid format: %s", p.RawFormat) + return fmt.Errorf("invalid format: %s", p.RawFormat) } } @@ -51,7 +50,7 @@ func (p *PrintOptions) Validate(defaultFormat Format, allowedFormats []Format) e return nil } } - return errors.Errorf("invalid format: %s", p.RawFormat) + return fmt.Errorf("invalid format: %s", p.RawFormat) } type PrintOptions struct { diff --git a/pkg/printer/table.go b/pkg/printer/table.go index 308a6ef22..72aab5160 100644 --- a/pkg/printer/table.go +++ b/pkg/printer/table.go @@ -1,11 +1,11 @@ package printer import ( + "fmt" "io" "reflect" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" ) func NewTableSection(out io.Writer) *tablewriter.Table { @@ -24,7 +24,7 @@ func NewTableSection(out io.Writer) *tablewriter.Table { // PrintTable outputs a dataset in tabular format func PrintTable(out io.Writer, v interface{}, getRow func(row interface{}) []string, headers ...string) error { if reflect.TypeOf(v).Kind() != reflect.Slice { - return errors.Errorf("invalid data passed to PrintTable, must be a slice but got %T", v) + return fmt.Errorf("invalid data passed to PrintTable, must be a slice but got %T", v) } rows := reflect.ValueOf(v) diff --git a/pkg/printer/yaml.go b/pkg/printer/yaml.go index 8dd435f5a..103b5a297 100644 --- a/pkg/printer/yaml.go +++ b/pkg/printer/yaml.go @@ -5,14 +5,13 @@ import ( "io" "get.porter.sh/porter/pkg/encoding" - "github.com/pkg/errors" ) // PrintYaml is a printer that prints the provided value in yaml func PrintYaml(out io.Writer, v interface{}) error { b, err := encoding.MarshalYaml(v) if err != nil { - return errors.Wrap(err, "could not marshal value to yaml") + return fmt.Errorf("could not marshal value to yaml: %w", err) } fmt.Fprint(out, string(b)) // yaml already includes a trailing newline, so don't print another return nil diff --git a/pkg/runtime/dependencies.go b/pkg/runtime/dependencies.go index 1737503ca..114240d7c 100644 --- a/pkg/runtime/dependencies.go +++ b/pkg/runtime/dependencies.go @@ -1,10 +1,10 @@ package runtime import ( + "fmt" "path/filepath" "get.porter.sh/porter/pkg/portercontext" - "github.com/pkg/errors" ) const ( @@ -18,5 +18,8 @@ func GetDependencyDefinitionPath(alias string) string { func GetDependencyDefinition(c *portercontext.Context, alias string) ([]byte, error) { f := GetDependencyDefinitionPath(alias) data, err := c.FileSystem.ReadFile(f) - return data, errors.Wrapf(err, "error reading bundle definition for %s at %s", alias, f) + if err != nil { + return nil, fmt.Errorf("error reading bundle definition for %s at %s: %w", alias, f, err) + } + return data, nil } diff --git a/pkg/runtime/outputs.go b/pkg/runtime/outputs.go index 610e3af17..44f1cff8e 100644 --- a/pkg/runtime/outputs.go +++ b/pkg/runtime/outputs.go @@ -1,8 +1,9 @@ package runtime import ( + "fmt" + "get.porter.sh/porter/pkg/manifest" - "github.com/pkg/errors" ) // ReadDependencyOutputValue reads the dependency's output using the alias for the dependency from the @@ -12,7 +13,7 @@ func (m *RuntimeManifest) ReadDependencyOutputValue(ref manifest.DependencyOutpu psEnvVar := manifest.ParamToEnvVar(ps) output, ok := m.LookupEnv(psEnvVar) if !ok { - err := errors.Errorf("bundle dependency %s output %s was not passed into the runtime", ref.Dependency, ref.Output) + err := fmt.Errorf("bundle dependency %s output %s was not passed into the runtime", ref.Dependency, ref.Output) return "", err } diff --git a/pkg/runtime/runtime-manifest.go b/pkg/runtime/runtime-manifest.go index c99b73d7f..9b7649e52 100644 --- a/pkg/runtime/runtime-manifest.go +++ b/pkg/runtime/runtime-manifest.go @@ -21,7 +21,6 @@ import ( "github.com/cnabio/cnab-go/bundle" "github.com/cnabio/cnab-to-oci/relocation" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) const ( @@ -72,7 +71,7 @@ func (m *RuntimeManifest) Validate() error { err = m.steps.Validate(m.Manifest) if err != nil { - return errors.Wrap(err, "invalid action configuration") + return fmt.Errorf("invalid action configuration: %w", err) } return nil @@ -106,7 +105,7 @@ func (m *RuntimeManifest) loadDependencyDefinitions() error { bun, err := bundle.Unmarshal(bunD) if err != nil { - return errors.Wrapf(err, "error unmarshaling bundle definition for dependency %s", dep.Name) + return fmt.Errorf("error unmarshaling bundle definition for dependency %s: %w", dep.Name, err) } m.bundles[dep.Name] = cnab.NewBundle(*bun) @@ -142,7 +141,7 @@ func (m *RuntimeManifest) resolveBundleOutput(outputName string) (string, error) psParamEnv := manifest.ParamToEnvVar(ps) outputValue, ok := m.LookupEnv(psParamEnv) if !ok { - return "", errors.Errorf("No parameter source was injected for output %s", outputName) + return "", fmt.Errorf("no parameter source was injected for output %s", outputName) } return outputValue, nil } @@ -196,7 +195,7 @@ func (m *RuntimeManifest) setStepsByAction() error { for a := range m.CustomActions { actions = append(actions, a) } - errors.Errorf("unsupported action %q, custom actions are defined for: %s", m.Action, strings.Join(actions, ", ")) + return fmt.Errorf("unsupported action %q, custom actions are defined for: %s", m.Action, strings.Join(actions, ", ")) } m.steps = customAction } @@ -407,7 +406,7 @@ func (m *RuntimeManifest) ResolveStep(step *manifest.Step) error { mustache.AllowMissingVariables = false sourceData, err := m.buildSourceData() if err != nil { - return errors.Wrap(err, "unable to build step template data") + return fmt.Errorf("unable to build step template data: %w", err) } if m.Debug { @@ -416,7 +415,7 @@ func (m *RuntimeManifest) ResolveStep(step *manifest.Step) error { payload, err := yaml.Marshal(step) if err != nil { - return errors.Wrapf(err, "invalid step data %v", step) + return fmt.Errorf("invalid step data %v: %w", step, err) } if m.Debug { @@ -425,7 +424,7 @@ func (m *RuntimeManifest) ResolveStep(step *manifest.Step) error { rendered, err := mustache.RenderRaw(string(payload), true, sourceData) if err != nil { - return errors.Wrapf(err, "unable to render step template %s", string(payload)) + return fmt.Errorf("unable to render step template %s: %w", string(payload), err) } if m.Debug { @@ -434,7 +433,7 @@ func (m *RuntimeManifest) ResolveStep(step *manifest.Step) error { err = yaml.Unmarshal([]byte(rendered), step) if err != nil { - return errors.Wrapf(err, "invalid step yaml\n%s", rendered) + return fmt.Errorf("invalid step yaml\n%s: %w", rendered, err) } return nil @@ -469,7 +468,7 @@ func (m *RuntimeManifest) Initialize() error { if os.IsNotExist(err) { continue } - return errors.Wrapf(err, "unable to acquire value for parameter %s", paramName) + return fmt.Errorf("unable to acquire value for parameter %s: %w", paramName, err) } // TODO(carolynvs): hack around parameters ALWAYS being injected even when empty files mess things up @@ -483,12 +482,12 @@ func (m *RuntimeManifest) Initialize() error { } decoded, err := base64.StdEncoding.DecodeString(string(bytes)) if err != nil { - return errors.Wrapf(err, "unable to decode parameter %s", paramName) + return fmt.Errorf("unable to decode parameter %s: %w", paramName, err) } err = m.FileSystem.WriteFile(param.Destination.Path, decoded, pkg.FileModeWritable) if err != nil { - return errors.Wrapf(err, "unable to write decoded parameter %s", paramName) + return fmt.Errorf("unable to write decoded parameter %s: %w", paramName, err) } } } @@ -499,7 +498,7 @@ func (m *RuntimeManifest) Initialize() error { func (m *RuntimeManifest) createOutputsDir() error { // Ensure outputs directory exists if err := m.FileSystem.MkdirAll(config.BundleOutputsDir, pkg.FileModeDirectory); err != nil { - return errors.Wrap(err, "unable to ensure CNAB outputs directory exists") + return fmt.Errorf("unable to ensure CNAB outputs directory exists: %w", err) } return nil } @@ -534,12 +533,16 @@ func (m *RuntimeManifest) unpackStateBag() error { f, err := os.OpenFile(dest, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)) if err != nil { - return errors.Wrapf(err, "error creating state file %s", dest) + return fmt.Errorf("error creating state file %s: %w", dest, err) } defer f.Close() _, err = io.Copy(f, tr) - return errors.Wrapf(err, "error unpacking state file %s", dest) + if err != nil { + return fmt.Errorf("error unpacking state file %s: %w", dest, err) + } + + return nil } stateArchive, err := m.FileSystem.Open(statePath) @@ -603,21 +606,25 @@ func (m *RuntimeManifest) packStateBag() error { } header, err := tar.FileInfoHeader(fi, fi.Name()) if err != nil { - return errors.Wrapf(err, "error creating tar header for state variable %s from path %s", s.Name, s.Path) + return fmt.Errorf("error creating tar header for state variable %s from path %s: %w", s.Name, s.Path, err) } header.Name = filepath.Join("porter-state", s.Name) if err := tw.WriteHeader(header); err != nil { - return errors.Wrapf(err, "error writing tar header for state variable %s", s.Name) + return fmt.Errorf("error writing tar header for state variable %s: %w", s.Name, err) } f, err := os.Open(s.Path) if err != nil { - return errors.Wrapf(err, "error reading state file %s for variable %s", s.Path, s.Name) + return fmt.Errorf("error reading state file %s for variable %s: %w", s.Path, s.Name, err) } _, err = io.Copy(tw, f) - return errors.Wrapf(err, "error archiving state file %s for variable %s", s.Path, s.Name) + if err != nil { + return fmt.Errorf("error archiving state file %s for variable %s: %w", s.Path, s.Name, err) + } + + return nil } // Save directly to the final output location since we've already collected outputs at this point @@ -689,7 +696,7 @@ func (m *RuntimeManifest) applyUnboundBundleOutputs() error { err := m.CopyFile(srcPath, dstPath) if err != nil { - bigErr = multierror.Append(bigErr, errors.Wrapf(err, "unable to copy output file from %s to %s", srcPath, dstPath)) + bigErr = multierror.Append(bigErr, fmt.Errorf("unable to copy output file from %s to %s: %w", srcPath, dstPath, err)) continue } } @@ -715,7 +722,7 @@ func (m *RuntimeManifest) ResolveImages(bun cnab.ExtendedBundle, reloMap relocat manifestImage.Digest = image.Digest err := resolveImage(&manifestImage, image.Image) if err != nil { - return errors.Wrap(err, "unable to update image map from bundle.json") + return fmt.Errorf("unable to update image map from bundle.json: %w", err) } m.ImageMap[alias] = manifestImage reverseLookup[image.Image] = alias @@ -725,7 +732,7 @@ func (m *RuntimeManifest) ResolveImages(bun cnab.ExtendedBundle, reloMap relocat if manifestImage, ok := m.ImageMap[alias]; ok { //note, there might be other images in the relocation mapping, like the invocation image err := resolveImage(&manifestImage, reloRef) if err != nil { - return errors.Wrap(err, "unable to update image map from relocation mapping") + return fmt.Errorf("unable to update image map from relocation mapping: %w", err) } m.ImageMap[alias] = manifestImage } diff --git a/pkg/runtime/runtime.go b/pkg/runtime/runtime.go index a6ed3bceb..e14f6d748 100644 --- a/pkg/runtime/runtime.go +++ b/pkg/runtime/runtime.go @@ -15,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/yaml" "github.com/cnabio/cnab-to-oci/relocation" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) // PorterRuntime orchestrates executing a bundle and managing state. @@ -60,12 +59,12 @@ func (r *PorterRuntime) Execute(ctx context.Context, rm *RuntimeManifest) error err = r.RuntimeManifest.ResolveImages(rtb, reloMap) if err != nil { - return errors.Wrap(err, "unable to resolve bundle images") + return fmt.Errorf("unable to resolve bundle images: %w", err) } err = r.FileSystem.MkdirAll(portercontext.MixinOutputsDir, pkg.FileModeDirectory) if err != nil { - return errors.Wrapf(err, "could not create outputs directory %s", portercontext.MixinOutputsDir) + return fmt.Errorf("could not create outputs directory %s: %w", portercontext.MixinOutputsDir, err) } var bigErr *multierror.Error @@ -91,7 +90,7 @@ func (r *PorterRuntime) executeStep(ctx context.Context, step *manifest.Step) er } err := r.RuntimeManifest.ResolveStep(step) if err != nil { - return errors.Wrap(err, "unable to resolve step") + return fmt.Errorf("unable to resolve step: %w", err) } description, _ := step.GetDescription() @@ -114,12 +113,12 @@ func (r *PorterRuntime) executeStep(ctx context.Context, step *manifest.Step) er } err = r.mixins.Run(ctx, r.Context, step.GetMixinName(), cmd) if err != nil { - return errors.Wrap(err, "mixin execution failed") + return fmt.Errorf("mixin execution failed: %w", err) } outputs, err := r.readMixinOutputs() if err != nil { - return errors.Wrap(err, "could not read step outputs") + return fmt.Errorf("could not read step outputs: %w", err) } err = r.RuntimeManifest.ApplyStepOutputs(outputs) @@ -145,7 +144,7 @@ func (r *PorterRuntime) applyStepOutputsToBundle(outputs map[string]string) erro err := r.FileSystem.WriteFile(outpath, []byte(outputValue), pkg.FileModeWritable) if err != nil { - return errors.Wrapf(err, "unable to write output file %s", outpath) + return fmt.Errorf("unable to write output file %s: %w", outpath, err) } } } @@ -170,7 +169,7 @@ func (r *PorterRuntime) readMixinOutputs() (map[string]string, error) { outfiles, err := r.FileSystem.ReadDir(portercontext.MixinOutputsDir) if err != nil { - return nil, errors.Wrapf(err, "could not list %s", portercontext.MixinOutputsDir) + return nil, fmt.Errorf("could not list %s: %w", portercontext.MixinOutputsDir, err) } for _, outfile := range outfiles { @@ -180,7 +179,7 @@ func (r *PorterRuntime) readMixinOutputs() (map[string]string, error) { outpath := filepath.Join(portercontext.MixinOutputsDir, outfile.Name()) contents, err := r.FileSystem.ReadFile(outpath) if err != nil { - return nil, errors.Wrapf(err, "could not read output file %s", outpath) + return nil, fmt.Errorf("could not read output file %s: %w", outpath, err) } outputs[outfile.Name()] = string(contents) @@ -205,11 +204,11 @@ func (r *PorterRuntime) getImageMappingFiles() (cnab.ExtendedBundle, relocation. if _, err := r.FileSystem.Stat("/cnab/app/relocation-mapping.json"); err == nil { reloBytes, err := r.FileSystem.ReadFile("/cnab/app/relocation-mapping.json") if err != nil { - return cnab.ExtendedBundle{}, nil, errors.Wrap(err, "couldn't read relocation file") + return cnab.ExtendedBundle{}, nil, fmt.Errorf("couldn't read relocation file: %w", err) } err = json.Unmarshal(reloBytes, &reloMap) if err != nil { - return cnab.ExtendedBundle{}, nil, errors.Wrap(err, "couldn't load relocation file") + return cnab.ExtendedBundle{}, nil, fmt.Errorf("couldn't load relocation file: %w", err) } } return b, reloMap, nil diff --git a/pkg/schema/check-strategy.go b/pkg/schema/check-strategy.go index 0211e554f..98a7952d2 100644 --- a/pkg/schema/check-strategy.go +++ b/pkg/schema/check-strategy.go @@ -1,10 +1,9 @@ package schema import ( + "errors" "fmt" "strings" - - "github.com/pkg/errors" ) // CheckStrategy is an enum of values for handling schemaVersion @@ -27,7 +26,7 @@ const ( ) // ErrInvalidSchemaVersion is used when the schemaVersion of two resources do not match exactly. -var ErrInvalidSchemaVersion = errors.New("Invalid schema version") +var ErrInvalidSchemaVersion = errors.New("invalid schema version") // ValidateSchemaVersion checks the specified schema version against the supported version, // returning if the result is a warning only. Warnings are returned when the versions are not an exact match. @@ -36,8 +35,8 @@ func ValidateSchemaVersion(strategy CheckStrategy, supported string, specified s if specified == "" { specified = "(none)" } - baseMessage := errors.Wrapf(ErrInvalidSchemaVersion, "The schema version is %s but the supported schema version is %s. See https://release-v1.porter.sh/reference/file-formats/#supported-versions for more details.", - specified, supported) + baseMessage := fmt.Errorf("the schema version is %s but the supported schema version is %s. See https://release-v1.porter.sh/reference/file-formats/#supported-versions for more details: %w", + specified, supported, ErrInvalidSchemaVersion) switch strategy { case CheckStrategyNone: @@ -59,7 +58,7 @@ func ValidateSchemaVersion(strategy CheckStrategy, supported string, specified s supportedMinor := getMinor(supported) if specifiedMinor != supportedMinor { - return false, errors.Wrapf(baseMessage, "The schema version MAJOR.MINOR values do not match") + return false, fmt.Errorf("the schema version MAJOR.MINOR values do not match: %w", baseMessage) } case CheckStrategyMajor: getMajor := func(version string) string { @@ -71,7 +70,7 @@ func ValidateSchemaVersion(strategy CheckStrategy, supported string, specified s supportedMajor := getMajor(supported) if specifiedMajor != supportedMajor { - return false, errors.Wrapf(baseMessage, "The schema version MAJOR values do not match") + return false, fmt.Errorf("the schema version MAJOR values do not match: %w", baseMessage) } default: return false, fmt.Errorf("unknown schema.CheckStrategy %v", strategy) @@ -82,5 +81,5 @@ func ValidateSchemaVersion(strategy CheckStrategy, supported string, specified s } // Even if the check passed, print a warning if it wasn't exactly the same - return true, errors.Wrap(baseMessage, "WARNING") + return true, fmt.Errorf("WARNING: %w", baseMessage) } diff --git a/pkg/schema/check-strategy_test.go b/pkg/schema/check-strategy_test.go index bc008a3a4..390522682 100644 --- a/pkg/schema/check-strategy_test.go +++ b/pkg/schema/check-strategy_test.go @@ -18,19 +18,19 @@ func TestValidateSchemaVersion(t *testing.T) { }{ {name: "exact - exact match", strategy: CheckStrategyExact, supported: "1.0.0", specified: "1.0.0"}, {name: "exact - patch mismatch", strategy: CheckStrategyExact, supported: "1.0.0", specified: "1.0.1", - wantErr: "The schema version is 1.0.1 but the supported schema version is 1.0.0"}, + wantErr: "the schema version is 1.0.1 but the supported schema version is 1.0.0"}, {name: "minor - exact match", strategy: CheckStrategyMinor, supported: "1.1.2", specified: "1.1.2"}, {name: "minor - minor match", strategy: CheckStrategyMinor, supported: "1.1.2", specified: "1.1.1", - wantWarning: true, wantErr: "WARNING: The schema version is 1.1.1 but the supported schema version is 1.1.2"}, + wantWarning: true, wantErr: "WARNING: the schema version is 1.1.1 but the supported schema version is 1.1.2"}, {name: "minor - minor mismatch", strategy: CheckStrategyMinor, supported: "1.2.0", specified: "1.1.0", - wantErr: "The schema version MAJOR.MINOR values do not match"}, + wantErr: "the schema version MAJOR.MINOR values do not match"}, {name: "major - exact match", strategy: CheckStrategyMajor, supported: "1.1.2", specified: "1.1.2"}, {name: "major - major match", strategy: CheckStrategyMajor, supported: "1.1.2", specified: "1.1.1", - wantWarning: true, wantErr: "WARNING: The schema version is 1.1.1 but the supported schema version is 1.1.2"}, + wantWarning: true, wantErr: "WARNING: the schema version is 1.1.1 but the supported schema version is 1.1.2"}, {name: "major - major mismatch", strategy: CheckStrategyMajor, supported: "1.1.2", specified: "2.0.0", - wantErr: "The schema version MAJOR values do not match"}, + wantErr: "the schema version MAJOR values do not match"}, {name: "none - mismatch", strategy: CheckStrategyNone, supported: "1.0.0", specified: "2.0.0", - wantWarning: true, wantErr: "WARNING: The schema version is 2.0.0 but the supported schema version is 1.0.0"}, + wantWarning: true, wantErr: "WARNING: the schema version is 2.0.0 but the supported schema version is 1.0.0"}, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/secrets/plugins/filesystem/store.go b/pkg/secrets/plugins/filesystem/store.go index 9729bd827..a6cfb5709 100644 --- a/pkg/secrets/plugins/filesystem/store.go +++ b/pkg/secrets/plugins/filesystem/store.go @@ -2,6 +2,7 @@ package filesystem import ( "context" + "errors" "fmt" "os" "path/filepath" @@ -11,7 +12,6 @@ import ( "get.porter.sh/porter/pkg/secrets/plugins" "get.porter.sh/porter/pkg/secrets/plugins/host" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) var _ plugins.SecretsProtocol = &Store{} diff --git a/pkg/secrets/plugins/in-memory/store.go b/pkg/secrets/plugins/in-memory/store.go index 7e87c8d1e..1fab53609 100644 --- a/pkg/secrets/plugins/in-memory/store.go +++ b/pkg/secrets/plugins/in-memory/store.go @@ -2,10 +2,10 @@ package inmemory import ( "context" + "errors" "get.porter.sh/porter/pkg/secrets/plugins" "github.com/cnabio/cnab-go/secrets/host" - "github.com/pkg/errors" ) var _ plugins.SecretsProtocol = &Store{} diff --git a/pkg/secrets/pluginstore/store.go b/pkg/secrets/pluginstore/store.go index 3c9a46740..f3d13f4fd 100644 --- a/pkg/secrets/pluginstore/store.go +++ b/pkg/secrets/pluginstore/store.go @@ -2,13 +2,13 @@ package pluginstore import ( "context" + "errors" "fmt" "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/plugins/pluggable" "get.porter.sh/porter/pkg/secrets/plugins" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" ) var _ plugins.SecretsProtocol = &Store{} diff --git a/pkg/storage/credential_store.go b/pkg/storage/credential_store.go index 4493d9e21..50d72ac5f 100644 --- a/pkg/storage/credential_store.go +++ b/pkg/storage/credential_store.go @@ -9,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/tracing" "github.com/cnabio/cnab-go/secrets/host" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) var _ CredentialSetProvider = &CredentialStore{} @@ -65,7 +64,7 @@ func (s CredentialStore) ResolveAll(ctx context.Context, creds CredentialSet) (s for _, cred := range creds.Credentials { value, err := s.Secrets.Resolve(ctx, cred.Source.Key, cred.Source.Value) if err != nil { - resolveErrors = multierror.Append(resolveErrors, errors.Wrapf(err, "unable to resolve credential %s.%s from %s %s", creds.Name, cred.Name, cred.Source.Key, cred.Source.Value)) + resolveErrors = multierror.Append(resolveErrors, fmt.Errorf("unable to resolve credential %s.%s from %s %s: %w", creds.Name, cred.Name, cred.Source.Key, cred.Source.Value, err)) } resolvedCreds[cred.Name] = value diff --git a/pkg/storage/credentialset.go b/pkg/storage/credentialset.go index 50998ae42..183bd0bcb 100644 --- a/pkg/storage/credentialset.go +++ b/pkg/storage/credentialset.go @@ -7,7 +7,6 @@ import ( "get.porter.sh/porter/pkg/secrets" "github.com/cnabio/cnab-go/bundle" "github.com/cnabio/cnab-go/schema" - "github.com/pkg/errors" ) var _ Document = &CredentialSet{} @@ -83,7 +82,7 @@ func (s CredentialSet) Validate() error { if s.SchemaVersion == "" { s.SchemaVersion = "(none)" } - return errors.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", s.SchemaVersion, CredentialSetSchemaVersion) + return fmt.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", s.SchemaVersion, CredentialSetSchemaVersion) } return nil } diff --git a/pkg/storage/credentialset_provider_helpers.go b/pkg/storage/credentialset_provider_helpers.go index e6fb43370..4078f000d 100644 --- a/pkg/storage/credentialset_provider_helpers.go +++ b/pkg/storage/credentialset_provider_helpers.go @@ -2,6 +2,7 @@ package storage import ( "context" + "fmt" "io" "io/ioutil" "path/filepath" @@ -12,7 +13,6 @@ import ( "get.porter.sh/porter/pkg/portercontext" "get.porter.sh/porter/pkg/secrets" "github.com/carolynvs/aferox" - "github.com/pkg/errors" "github.com/spf13/afero" ) @@ -63,26 +63,29 @@ func (p TestCredentialSetProvider) Load(path string) (CredentialSet, error) { fs := aferox.NewAferox(".", afero.NewOsFs()) var cset CredentialSet err := encoding.UnmarshalFile(fs, path, &cset) + if err != nil { + return cset, fmt.Errorf("error reading %s as a credential set: %w", path, err) + } - return cset, errors.Wrapf(err, "error reading %s as a credential set", path) + return cset, nil } func (p TestCredentialSetProvider) AddTestCredentials(path string) { cs, err := p.Load(path) if err != nil { - p.T.Fatal(errors.Wrapf(err, "could not read test credentials from %s", path)) + p.T.Fatal(fmt.Errorf("could not read test credentials from %s: %w", path, err)) } err = p.CredentialStore.InsertCredentialSet(context.Background(), cs) if err != nil { - p.T.Fatal(errors.Wrap(err, "could not load test credentials into in memory credential storage")) + p.T.Fatal(fmt.Errorf("could not load test credentials into in memory credential storage: %w", err)) } } func (p TestCredentialSetProvider) AddTestCredentialsDirectory(dir string) { files, err := ioutil.ReadDir(dir) if err != nil { - p.T.Fatal(errors.Wrapf(err, "could not list test directory %s", dir)) + p.T.Fatal(fmt.Errorf("could not list test directory %s: %w", dir, err)) } for _, fi := range files { diff --git a/pkg/storage/installation.go b/pkg/storage/installation.go index bc5517f51..c60470fd3 100644 --- a/pkg/storage/installation.go +++ b/pkg/storage/installation.go @@ -3,6 +3,7 @@ package storage import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -11,7 +12,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/cnabio/cnab-go/schema" "github.com/opencontainers/go-digest" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" ) @@ -130,14 +130,18 @@ func (i *Installation) Validate() error { if i.SchemaVersion == "" { i.SchemaVersion = "(none)" } - return errors.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", i.SchemaVersion, InstallationSchemaVersion) + return fmt.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", i.SchemaVersion, InstallationSchemaVersion) } // We can change these to better checks if we consolidate our logic around the various ways we let you // install from a bundle definition https://github.com/getporter/porter/issues/1024#issuecomment-899828081 // Until then, these are pretty weak checks _, _, err := i.Bundle.GetBundleReference() - return errors.Wrapf(err, "could not determine the fully-qualified bundle reference") + if err != nil { + return fmt.Errorf("could not determine the fully-qualified bundle reference: %w", err) + } + + return nil } // TrackBundle updates the bundle that the installation is tracking. @@ -252,18 +256,18 @@ func (r OCIReferenceParts) GetBundleReference() (cnab.OCIReference, bool, error) ref, err := cnab.ParseOCIReference(r.Repository) if err != nil { - return cnab.OCIReference{}, false, errors.Wrapf(err, "invalid bundle Repository %s", r.Repository) + return cnab.OCIReference{}, false, fmt.Errorf("invalid bundle Repository %s: %w", r.Repository, err) } if r.Digest != "" { d, err := digest.Parse(r.Digest) if err != nil { - return cnab.OCIReference{}, false, errors.Wrapf(err, "invalid bundle Digest %s", r.Digest) + return cnab.OCIReference{}, false, fmt.Errorf("invalid bundle Digest %s: %w", r.Digest, err) } ref, err = ref.WithDigest(d) if err != nil { - return cnab.OCIReference{}, false, errors.Wrapf(err, "error joining the bundle Repository %s and Digest %s", r.Repository, r.Digest) + return cnab.OCIReference{}, false, fmt.Errorf("error joining the bundle Repository %s and Digest %s: %w", r.Repository, r.Digest, err) } return ref, true, nil } @@ -278,7 +282,7 @@ func (r OCIReferenceParts) GetBundleReference() (cnab.OCIReference, bool, error) // everyone else can use the tag field if they do weird things ref, err = ref.WithTag("v" + v.String()) if err != nil { - return cnab.OCIReference{}, false, errors.Wrapf(err, "error joining the bundle Repository %s and Version %s", r.Repository, r.Version) + return cnab.OCIReference{}, false, fmt.Errorf("error joining the bundle Repository %s and Version %s: %w", r.Repository, r.Version, err) } return ref, true, nil } @@ -286,7 +290,7 @@ func (r OCIReferenceParts) GetBundleReference() (cnab.OCIReference, bool, error) if r.Tag != "" { ref, err = ref.WithTag(r.Tag) if err != nil { - return cnab.OCIReference{}, false, errors.Wrapf(err, "error joining the bundle Repository %s and Tag %s", r.Repository, r.Tag) + return cnab.OCIReference{}, false, fmt.Errorf("error joining the bundle Repository %s and Tag %s: %w", r.Repository, r.Tag, err) } return ref, true, nil } diff --git a/pkg/storage/installation_store.go b/pkg/storage/installation_store.go index 65a57092f..c2c11fa1c 100644 --- a/pkg/storage/installation_store.go +++ b/pkg/storage/installation_store.go @@ -2,9 +2,9 @@ package storage import ( "context" + "errors" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" ) diff --git a/pkg/storage/migrations/manager.go b/pkg/storage/migrations/manager.go index f0f204981..c87fc0368 100644 --- a/pkg/storage/migrations/manager.go +++ b/pkg/storage/migrations/manager.go @@ -3,6 +3,7 @@ package migrations import ( "context" "encoding/json" + "errors" "fmt" "io" "path/filepath" @@ -14,7 +15,6 @@ import ( "get.porter.sh/porter/pkg/tracing" "github.com/cnabio/cnab-go/schema" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) const ( @@ -74,7 +74,7 @@ func (m *Manager) Connect(ctx context.Context) error { if !m.allowOutOfDateSchema && m.MigrationRequired() { m.Close() - return span.Error(errors.Errorf(`The schema of Porter's data is in an older format than supported by this version of Porter. + return span.Error(fmt.Errorf(`The schema of Porter's data is in an older format than supported by this version of Porter. Porter %s uses the following database schema: @@ -208,12 +208,16 @@ func (m *Manager) loadSchema(ctx context.Context) error { return nil } } - return errors.Wrap(err, "could not read storage schema document") + return fmt.Errorf("could not read storage schema document: %w", err) } m.schema = schema - return errors.Wrap(err, "could not parse storage schema document") + if err != nil { + return fmt.Errorf("could not parse storage schema document: %w", err) + } + + return nil } // MigrationRequired determines if a migration of Porter's storage system is necessary. @@ -246,7 +250,7 @@ func (m *Manager) Migrate(ctx context.Context) (string, error) { logfilePath := filepath.Join(home, fmt.Sprintf("%s-migrate.log", time.Now().Format("20060102150405"))) logfile, err := m.FileSystem.Create(logfilePath) if err != nil { - return "", errors.Wrapf(err, "error creating logfile for migration at %s", logfilePath) + return "", fmt.Errorf("error creating logfile for migration at %s: %w", logfilePath, err) } defer logfile.Close() w := io.MultiWriter(m.Err, logfile) @@ -295,7 +299,7 @@ func (m *Manager) initEmptyPorterHome(ctx context.Context) (bool, error) { itemCheck := func(itemType string) (bool, error) { itemCount, err := m.store.Count(ctx, itemType, storage.CountOptions{}) if err != nil { - return false, errors.Wrapf(err, "error checking for existing %s when checking if PORTER_HOME is new", itemType) + return false, fmt.Errorf("error checking for existing %s when checking if PORTER_HOME is new: %w", itemType, err) } return itemCount > 0, nil @@ -340,7 +344,7 @@ func (m *Manager) WriteSchema(ctx context.Context) error { err := m.store.Update(ctx, CollectionConfig, storage.UpdateOptions{Document: m.schema, Upsert: true}) if err != nil { - return errors.Wrap(err, "Unable to save storage schema file") + return fmt.Errorf("Unable to save storage schema file: %w", err) } return nil diff --git a/pkg/storage/parameter_store.go b/pkg/storage/parameter_store.go index 8fcc20f3c..76abed039 100644 --- a/pkg/storage/parameter_store.go +++ b/pkg/storage/parameter_store.go @@ -9,7 +9,6 @@ import ( "get.porter.sh/porter/pkg/tracing" "github.com/cnabio/cnab-go/secrets/host" "github.com/hashicorp/go-multierror" - "github.com/pkg/errors" ) var _ ParameterSetProvider = &ParameterStore{} @@ -59,7 +58,7 @@ func (s ParameterStore) ResolveAll(ctx context.Context, params ParameterSet) (se for _, param := range params.Parameters { value, err := s.Secrets.Resolve(ctx, param.Source.Key, param.Source.Value) if err != nil { - resolveErrors = multierror.Append(resolveErrors, errors.Wrapf(err, "unable to resolve parameter %s.%s from %s %s", params.Name, param.Name, param.Source.Key, param.Source.Value)) + resolveErrors = multierror.Append(resolveErrors, fmt.Errorf("unable to resolve parameter %s.%s from %s %s: %w", params.Name, param.Name, param.Source.Key, param.Source.Value, err)) } resolvedParams[param.Name] = value diff --git a/pkg/storage/parameterset.go b/pkg/storage/parameterset.go index 01093c38d..d0d3d5ab1 100644 --- a/pkg/storage/parameterset.go +++ b/pkg/storage/parameterset.go @@ -6,7 +6,6 @@ import ( "get.porter.sh/porter/pkg/secrets" "github.com/cnabio/cnab-go/schema" - "github.com/pkg/errors" ) const INTERNAL_PARAMETERER_SET = "internal-parameter-set" @@ -80,7 +79,7 @@ func (s ParameterSet) Validate() error { if s.SchemaVersion == "" { s.SchemaVersion = "(none)" } - return errors.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", s.SchemaVersion, ParameterSetSchemaVersion) + return fmt.Errorf("invalid schemaVersion provided: %s. This version of Porter is compatible with %s.", s.SchemaVersion, ParameterSetSchemaVersion) } return nil } diff --git a/pkg/storage/parameterset_provider_helpers.go b/pkg/storage/parameterset_provider_helpers.go index 295e45208..14682dc82 100644 --- a/pkg/storage/parameterset_provider_helpers.go +++ b/pkg/storage/parameterset_provider_helpers.go @@ -2,6 +2,7 @@ package storage import ( "context" + "fmt" "io/ioutil" "path/filepath" "testing" @@ -10,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/encoding" "get.porter.sh/porter/pkg/secrets" "github.com/carolynvs/aferox" - "github.com/pkg/errors" "github.com/spf13/afero" ) @@ -56,26 +56,29 @@ func (p TestParameterSetProvider) Load(path string) (ParameterSet, error) { fs := aferox.NewAferox(".", afero.NewOsFs()) var pset ParameterSet err := encoding.UnmarshalFile(fs, path, &pset) + if err != nil { + return pset, fmt.Errorf("error reading %s as a parameter set: %w", path, err) + } - return pset, errors.Wrapf(err, "error reading %s as a parameter set", path) + return pset, nil } func (p TestParameterSetProvider) AddTestParameters(path string) { ps, err := p.Load(path) if err != nil { - p.T.Fatal(errors.Wrapf(err, "could not read test parameters from %s", path)) + p.T.Fatal(fmt.Errorf("could not read test parameters from %s: %w", path, err)) } err = p.ParameterStore.InsertParameterSet(context.Background(), ps) if err != nil { - p.T.Fatal(errors.Wrap(err, "could not load test parameters")) + p.T.Fatal(fmt.Errorf("could not load test parameters: %w", err)) } } func (p TestParameterSetProvider) AddTestParametersDirectory(dir string) { files, err := ioutil.ReadDir(dir) if err != nil { - p.T.Fatal(errors.Wrapf(err, "could not list test directory %s", dir)) + p.T.Fatal(fmt.Errorf("could not list test directory %s: %w", dir, err)) } for _, fi := range files { diff --git a/pkg/storage/plugin_adapter.go b/pkg/storage/plugin_adapter.go index 20b1f39a1..5ee89192d 100644 --- a/pkg/storage/plugin_adapter.go +++ b/pkg/storage/plugin_adapter.go @@ -8,7 +8,6 @@ import ( "strings" "get.porter.sh/porter/pkg/storage/plugins" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" ) @@ -83,7 +82,11 @@ func (a PluginAdapter) FindOne(ctx context.Context, collection string, opts Find } err = a.unmarshal(rawResults[0], out) - return errors.Wrapf(err, "could not unmarshal document of type %T", out) + if err != nil { + return fmt.Errorf("could not unmarshal document of type %T: %w", out, err) + } + + return nil } // unmarshalSlice unpacks a slice of bson documents onto the specified type slice (out) @@ -108,12 +111,16 @@ func (a PluginAdapter) unmarshalSlice(bsonResults []bson.Raw, out interface{}) e // Marshal the consolidated document to json data, err := json.Marshal(tmpResults) if err != nil { - return errors.Wrap(err, "error marshaling results into a single result document") + return fmt.Errorf("error marshaling results into a single result document: %w", err) } // Unmarshal the consolidated results onto our destination output err = json.Unmarshal(data, out) - return errors.Wrapf(err, "could not unmarshal slice onto type %T", out) + if err != nil { + return fmt.Errorf("could not unmarshal slice onto type %T: %w", out, err) + } + + return nil } // unmarshalSlice a bson document onto the specified typed output @@ -132,12 +139,16 @@ func (a PluginAdapter) unmarshal(bsonResult bson.Raw, out interface{}) error { // Marshal the consolidated document to json data, err := json.Marshal(tmpResult) if err != nil { - return errors.Wrap(err, "error marshaling results into a single result document") + return fmt.Errorf("error marshaling results into a single result document: %w", err) } // Unmarshal the consolidated results onto our destination output err = json.Unmarshal(data, out) - return errors.Wrapf(err, "could not unmarshal slice onto type %T", out) + if err != nil { + return fmt.Errorf("could not unmarshal slice onto type %T: %w", out, err) + } + + return nil } func (a PluginAdapter) Get(ctx context.Context, collection string, opts GetOptions, out interface{}) error { @@ -168,6 +179,9 @@ func (a PluginAdapter) Remove(ctx context.Context, collection string, opts Remov func (a PluginAdapter) Update(ctx context.Context, collection string, opts UpdateOptions) error { pluginOpts, err := opts.ToPluginOptions(collection) + if err != nil { + return err + } err = a.plugin.Update(ctx, pluginOpts) return a.handleError(err, collection) } diff --git a/pkg/storage/plugins/mongodb/mongodb.go b/pkg/storage/plugins/mongodb/mongodb.go index 8ec369c29..441ed0ddb 100644 --- a/pkg/storage/plugins/mongodb/mongodb.go +++ b/pkg/storage/plugins/mongodb/mongodb.go @@ -2,6 +2,7 @@ package mongodb import ( "context" + "errors" "fmt" "strings" "time" @@ -10,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/storage/plugins" "get.porter.sh/porter/pkg/tracing" "github.com/davecgh/go-spew/spew" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" diff --git a/pkg/storage/plugins/mongodb_docker/store.go b/pkg/storage/plugins/mongodb_docker/store.go index a9371b1dc..9600f7b81 100644 --- a/pkg/storage/plugins/mongodb_docker/store.go +++ b/pkg/storage/plugins/mongodb_docker/store.go @@ -2,6 +2,7 @@ package mongodb_docker import ( "context" + "errors" "fmt" "os/exec" "runtime" @@ -12,7 +13,6 @@ import ( "get.porter.sh/porter/pkg/storage/plugins" "get.porter.sh/porter/pkg/storage/plugins/mongodb" "get.porter.sh/porter/pkg/tracing" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" ) diff --git a/pkg/storage/sanitizer.go b/pkg/storage/sanitizer.go index 982689c0c..b8a874c3e 100644 --- a/pkg/storage/sanitizer.go +++ b/pkg/storage/sanitizer.go @@ -2,10 +2,10 @@ package storage import ( "context" + "fmt" "get.porter.sh/porter/pkg/cnab" "get.porter.sh/porter/pkg/secrets" - "github.com/pkg/errors" ) // Sanitizer identifies sensitive data in a database record, and replaces it with @@ -64,7 +64,7 @@ func (s *Sanitizer) CleanParameters(ctx context.Context, params []secrets.Strate cleaned := sanitizedParam(strategy, id) err := s.secrets.Create(ctx, cleaned.Source.Key, cleaned.Source.Value, cleaned.Value) if err != nil { - return nil, errors.Wrap(err, "failed to save sensitive param to secrete store") + return nil, fmt.Errorf("failed to save sensitive param to secrete store: %w", err) } strategy = cleaned } @@ -167,7 +167,7 @@ func (s *Sanitizer) RestoreOutputs(ctx context.Context, o Outputs) (Outputs, err for _, ot := range o.Value() { r, err := s.RestoreOutput(ctx, ot) if err != nil { - return o, errors.WithMessagef(err, "failed to resolve output %q using key %q", ot.Name, ot.Key) + return o, fmt.Errorf("failed to resolve output %q using key %q: %w", ot.Name, ot.Key, err) } resolved = append(resolved, r) } diff --git a/pkg/tracing/traceLogger.go b/pkg/tracing/traceLogger.go index c87ec3dc3..982aa46b9 100644 --- a/pkg/tracing/traceLogger.go +++ b/pkg/tracing/traceLogger.go @@ -6,7 +6,6 @@ import ( "runtime" "strings" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" @@ -201,11 +200,9 @@ func (l traceLogger) Error(err error, attrs ...attribute.KeyValue) error { trace.WithAttributes(attrs...), } - if st := findStack(err); st != nil { - errOpts = append(errOpts, trace.WithAttributes( - semconv.ExceptionStacktraceKey.String(fmt.Sprintf("%+v", st)), - )) - } + errOpts = append(errOpts, trace.WithAttributes( + semconv.ExceptionStacktraceKey.String(fmt.Sprintf("%+v", err)), + )) l.span.RecordError(err, errOpts...) l.span.SetStatus(codes.Error, err.Error()) @@ -220,38 +217,6 @@ func addLogToSpan(span trace.Span, msg string, level string, attrs ...attribute. span.AddEvent(msg, trace.WithAttributes(attrs...)) } -// Find the closest stack trace to where the error was generated -// https://github.com/pkg/errors/issues/173#issuecomment-456729811 -func findStack(err error) errors.StackTrace { - type causer interface { - Cause() error - } - - type stackTracer interface { - StackTrace() errors.StackTrace - } - - var stackErr error - - for { - if _, ok := err.(stackTracer); ok { - stackErr = err - } - - if causer, ok := err.(causer); ok { - err = causer.Cause() - } else { - break - } - } - - if stackErr != nil { - return stackErr.(stackTracer).StackTrace() - } - - return nil -} - func callerFunc() string { callerUnknown := "unknown" diff --git a/pkg/yaml/yq.go b/pkg/yaml/yq.go index e4e0db25b..0e019b958 100644 --- a/pkg/yaml/yq.go +++ b/pkg/yaml/yq.go @@ -2,6 +2,7 @@ package yaml import ( "bytes" + "fmt" "io/ioutil" "os" "sync" @@ -10,7 +11,6 @@ import ( "get.porter.sh/porter/pkg/config" "get.porter.sh/porter/pkg/portercontext" "github.com/mikefarah/yq/v3/pkg/yqlib" - "github.com/pkg/errors" "gopkg.in/op/go-logging.v1" "gopkg.in/yaml.v3" ) @@ -60,7 +60,7 @@ func (e *Editor) Read(data []byte) (n int, err error) { var decoder = yaml.NewDecoder(bytes.NewReader(data)) err = decoder.Decode(e.node) if err != nil { - return len(data), errors.Wrapf(err, "could not parse manifest:\n%s", string(data)) + return len(data), fmt.Errorf("could not parse manifest:\n%s: %w", string(data), err) } return len(data), nil @@ -69,23 +69,32 @@ func (e *Editor) Read(data []byte) (n int, err error) { func (e *Editor) ReadFile(src string) error { contents, err := e.context.FileSystem.ReadFile(src) if err != nil { - return errors.Wrapf(err, "could not read the manifest at %q", src) + return fmt.Errorf("could not read the manifest at %q: %w", src, err) } _, err = e.Read(contents) - return errors.Wrapf(err, "could not parse the manifest at %q", src) + if err != nil { + return fmt.Errorf("could not parse the manifest at %q: %w", src, err) + } + + return nil } func (e *Editor) WriteFile(dest string) error { destFile, err := e.context.FileSystem.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, pkg.FileModeWritable) if err != nil { - return errors.Wrapf(err, "could not open destination manifest location %s", config.Name) + return fmt.Errorf("could not open destination manifest location %s: %w", config.Name, err) } defer destFile.Close() // Encode the updated manifest to the proper location // yqlib.NewYamlEncoder takes: dest (io.Writer), indent spaces (int), colorized output (bool) var encoder = yqlib.NewYamlEncoder(destFile, 2, false) - return errors.Wrapf(encoder.Encode(e.node), "unable to write the manifest to %s", dest) + err = encoder.Encode(e.node) + if err != nil { + return fmt.Errorf("unable to write the manifest to %s: %w", dest, err) + } + + return nil } func (e *Editor) SetValue(path string, value string) error { @@ -95,5 +104,9 @@ func (e *Editor) SetValue(path string, value string) error { var parsedValue = valueParser.Parse(value, "", "", "", false) cmd := yqlib.UpdateCommand{Command: "update", Path: path, Value: parsedValue, Overwrite: true} err := e.yq.Update(e.node, cmd, true) - return errors.Wrapf(err, "could not update manifest path %q with value %q", path, value) + if err != nil { + return fmt.Errorf("could not update manifest path %q with value %q: %w", path, value, err) + } + + return nil } diff --git a/tests/tester/main.go b/tests/tester/main.go index 616767513..ee1c324ed 100644 --- a/tests/tester/main.go +++ b/tests/tester/main.go @@ -3,6 +3,7 @@ package tester import ( "bytes" "context" + "fmt" "io" "io/ioutil" "os" @@ -13,7 +14,6 @@ import ( "get.porter.sh/porter/pkg/storage/plugins/mongodb_docker" "get.porter.sh/porter/tests" "github.com/carolynvs/magex/shx" - "github.com/pkg/errors" "github.com/stretchr/testify/require" ) @@ -63,7 +63,7 @@ func NewTestWithConfig(t *testing.T, configFilePath string) (Tester, error) { test.TestDir, err = ioutil.TempDir("", "porter-test") if err != nil { - return *test, errors.Wrap(err, "could not create temp test directory") + return *test, fmt.Errorf("could not create temp test directory: %w", err) } test.dbName = tests.GenerateDatabaseName(t.Name()) @@ -135,7 +135,7 @@ func (t Tester) RunPorterWith(opts ...func(*shx.PreparedCommand)) (stdout string ran, _, err := cmd.Exec() if err != nil { if ran { - err = errors.Wrap(err, stderrBuf.String()) + err = fmt.Errorf("%s: %w", stderrBuf.String(), err) } return stdoutBuf.String(), output.String(), err } @@ -177,7 +177,7 @@ func (t *Tester) createPorterHome(configFilePath string) error { binDir := filepath.Join(t.RepoRoot, "bin") t.PorterHomeDir, err = ioutil.TempDir("", "porter") if err != nil { - return errors.Wrap(err, "could not create temp PORTER_HOME directory") + return fmt.Errorf("could not create temp PORTER_HOME directory: %w", err) } require.NoError(t.T, shx.Copy(filepath.Join(binDir, "porter*"), t.PorterHomeDir),