From 43c68bc17cba38514c2b9ed79641f6d21e242309 Mon Sep 17 00:00:00 2001 From: Jaime Soriano Pastor Date: Thu, 29 Jun 2023 17:28:59 +0200 Subject: [PATCH] Re-wrap errors (#1332) Use standard library for errors wrapping. Most code changes done with `github.com/xdg-go/go-rewrap-errors` and `goimports`. Steps followed to prepare this change: * `find . -name "*.go" -exec go run github.com/xdg-go/go-rewrap-errors@latest -w {} \;` * `find . -name "*.go" -exec goimports -w {} \;` * `go mod tidy` * Manually replaced uses of `log.Fatal(fmt.Errorf` with `log.Fatalf(...` (not really related, but took the opportunity to fix this). * `make check-static`, and fix linting issues related to error messages. * Fix case with nil error where `errors.Wrap` would have returned nil. --- cmd/build.go | 13 ++--- cmd/changelog.go | 13 ++--- cmd/check.go | 5 +- cmd/clean.go | 9 ++-- cmd/create_data_stream.go | 15 +++--- cmd/create_package.go | 8 +-- cmd/dump.go | 13 +++-- cmd/export.go | 14 ++--- cmd/format.go | 8 +-- cmd/install.go | 14 ++--- cmd/lint.go | 10 ++-- cmd/profiles.go | 13 ++--- cmd/service.go | 7 +-- cmd/stack.go | 16 +++--- cmd/status.go | 5 +- cmd/testrunner.go | 26 ++++----- cmd/uninstall.go | 12 +++-- go.mod | 2 +- internal/builder/dashboards.go | 7 ++- internal/builder/dynamic_mappings.go | 13 ++--- internal/builder/external_fields.go | 12 ++--- internal/builder/packages.go | 54 +++++++++---------- internal/cleanup/build.go | 16 +++--- internal/cleanup/service_logs.go | 6 +-- internal/cleanup/stack.go | 14 ++--- internal/cobraext/errors.go | 4 +- internal/cobraext/profiles.go | 10 ++-- internal/common/mapstr.go | 7 ++- internal/compose/compose.go | 27 +++++----- internal/configuration/locations/locations.go | 7 ++- internal/corpusgenerator/assets.go | 11 ++-- internal/corpusgenerator/client.go | 14 ++--- internal/docker/docker.go | 20 ++++--- internal/docs/exported_fields.go | 12 ++--- internal/docs/links_map.go | 9 ++-- internal/docs/readme.go | 36 ++++++------- internal/docs/sample_event.go | 6 +-- internal/elasticsearch/client.go | 25 +++++---- internal/export/dashboards.go | 19 ++++--- internal/export/object_transformer.go | 4 +- internal/export/transform_decode.go | 9 ++-- internal/export/transform_standardize.go | 21 ++++---- internal/export/transform_strip.go | 8 +-- internal/fields/dependency_manager.go | 28 +++++----- internal/files/clear.go | 7 ++- internal/files/compress.go | 10 ++-- internal/files/remove.go | 7 ++- internal/files/sign.go | 19 ++++--- internal/formatter/formatter.go | 12 ++--- internal/formatter/json_formatter.go | 7 ++- internal/formatter/yaml_formatter.go | 7 ++- internal/install/application_configuration.go | 9 ++-- internal/install/install.go | 36 ++++++------- internal/install/version_file.go | 6 +-- internal/kind/kind.go | 12 ++--- internal/kubectl/kubectl.go | 9 ++-- internal/kubectl/kubectl_apply.go | 27 +++++----- internal/packages/archetype/archetype.go | 15 +++--- internal/packages/archetype/data_stream.go | 12 ++--- internal/packages/archetype/package.go | 18 +++---- internal/packages/archetype/package_imgs.go | 4 +- internal/packages/archetype/package_test.go | 7 +-- internal/packages/assets.go | 27 +++++----- .../packages/buildmanifest/build_manifest.go | 8 +-- internal/packages/changelog/changelog.go | 6 +-- internal/packages/changelog/yaml.go | 13 +++-- internal/packages/conditions.go | 12 ++--- internal/packages/installer/installer.go | 6 +-- internal/packages/installer/zip_installer.go | 6 +-- internal/packages/packages.go | 35 ++++++------ internal/packages/status/status.go | 13 ++--- internal/profile/profile_json.go | 12 ++--- internal/registry/client.go | 13 +++-- internal/registry/revisions.go | 7 ++- internal/service/boot.go | 10 ++-- internal/stack/boot.go | 24 ++++----- internal/stack/compose.go | 26 +++++---- internal/stack/dump.go | 8 ++- internal/stack/errors.go | 4 +- internal/stack/logs.go | 13 +++-- internal/stack/network.go | 7 +-- internal/stack/options.go | 4 +- internal/stack/update.go | 8 +-- internal/storage/signature.go | 14 ++--- internal/storage/storage.go | 9 ++-- internal/surveyext/validators.go | 6 +-- internal/testrunner/coverageoutput.go | 33 ++++++------ internal/testrunner/errors.go | 4 +- internal/testrunner/report_format.go | 4 +- .../testrunner/reporters/formats/xunit.go | 4 +- internal/testrunner/reporters/outputs/file.go | 11 ++-- internal/testrunner/runners/asset/runner.go | 12 ++--- .../testrunner/runners/asset/test_config.go | 9 ++-- .../testrunner/runners/pipeline/coverage.go | 18 +++---- .../testrunner/runners/pipeline/runner.go | 49 +++++++++-------- .../testrunner/runners/pipeline/test_case.go | 19 ++++--- .../runners/pipeline/test_config.go | 10 ++-- .../runners/pipeline/test_result.go | 33 ++++++------ internal/testrunner/runners/runners.go | 1 + internal/testrunner/runners/static/runner.go | 16 +++--- .../testrunner/runners/static/test_config.go | 9 ++-- .../runners/system/servicedeployer/compose.go | 34 ++++++------ .../system/servicedeployer/custom_agent.go | 32 ++++++----- .../runners/system/servicedeployer/factory.go | 17 +++--- .../system/servicedeployer/kubernetes.go | 38 ++++++------- .../system/servicedeployer/terraform.go | 19 ++++--- .../system/servicedeployer/variants.go | 8 +-- .../testrunner/runners/system/test_config.go | 17 +++--- internal/testrunner/testrunner.go | 13 +++-- main.go | 4 +- tools/readme/main.go | 20 ++++--- 111 files changed, 765 insertions(+), 786 deletions(-) diff --git a/cmd/build.go b/cmd/build.go index d925cd0c0..2a38e355e 100644 --- a/cmd/build.go +++ b/cmd/build.go @@ -5,9 +5,10 @@ package cmd import ( + "errors" + "fmt" "path/filepath" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/builder" @@ -55,24 +56,24 @@ func buildCommandAction(cmd *cobra.Command, args []string) error { if signPackage { err := files.VerifySignerConfiguration() if err != nil { - return errors.Wrap(err, "can't verify signer configuration") + return fmt.Errorf("can't verify signer configuration: %w", err) } } packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } buildDir, err := builder.BuildDirectory() if err != nil { - return errors.Wrap(err, "can't prepare build directory") + return fmt.Errorf("can't prepare build directory: %w", err) } logger.Debugf("Use build directory: %s", buildDir) targets, err := docs.UpdateReadmes(packageRoot) if err != nil { - return errors.Wrap(err, "updating files failed") + return fmt.Errorf("updating files failed: %w", err) } for _, target := range targets { @@ -87,7 +88,7 @@ func buildCommandAction(cmd *cobra.Command, args []string) error { SkipValidation: skipValidation, }) if err != nil { - return errors.Wrap(err, "building package failed") + return fmt.Errorf("building package failed: %w", err) } cmd.Printf("Package built: %s\n", target) diff --git a/cmd/changelog.go b/cmd/changelog.go index c2d3c1bea..523a5597f 100644 --- a/cmd/changelog.go +++ b/cmd/changelog.go @@ -5,11 +5,12 @@ package cmd import ( + "fmt" "os" "path/filepath" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -60,13 +61,13 @@ func setupChangelogCommand() *cobraext.Command { func changelogAddCmd(cmd *cobra.Command, args []string) error { packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } version, _ := cmd.Flags().GetString(cobraext.ChangelogAddVersionFlagName) nextMode, _ := cmd.Flags().GetString(cobraext.ChangelogAddNextFlagName) if version != "" && nextMode != "" { - return errors.Errorf("flags %q and %q cannot be used at the same time", + return fmt.Errorf("flags %q and %q cannot be used at the same time", cobraext.ChangelogAddVersionFlagName, cobraext.ChangelogAddNextFlagName) } @@ -109,7 +110,7 @@ func changelogAddCmd(cmd *cobra.Command, args []string) error { func changelogCmdVersion(nextMode, packageRoot string) (*semver.Version, error) { revisions, err := changelog.ReadChangelogFromPackageRoot(packageRoot) if err != nil { - return nil, errors.Wrap(err, "failed to read current changelog") + return nil, fmt.Errorf("failed to read current changelog: %w", err) } if len(revisions) == 0 { return semver.MustParse("0.0.0"), nil @@ -117,7 +118,7 @@ func changelogCmdVersion(nextMode, packageRoot string) (*semver.Version, error) version, err := semver.NewVersion(revisions[0].Version) if err != nil { - return nil, errors.Wrapf(err, "invalid version in changelog %q", revisions[0].Version) + return nil, fmt.Errorf("invalid version in changelog %q: %w", revisions[0].Version, err) } switch nextMode { @@ -133,7 +134,7 @@ func changelogCmdVersion(nextMode, packageRoot string) (*semver.Version, error) v := version.IncPatch() version = &v default: - return nil, errors.Errorf("invalid value for %q: %s", + return nil, fmt.Errorf("invalid value for %q: %s", cobraext.ChangelogAddNextFlagName, nextMode) } diff --git a/cmd/check.go b/cmd/check.go index c994b21da..22e86deb1 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -5,7 +5,8 @@ package cmd import ( - "github.com/pkg/errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -27,7 +28,7 @@ func setupCheckCommand() *cobraext.Command { setupBuildCommand(), ) if err != nil { - return errors.Wrap(err, "checking package failed") + return fmt.Errorf("checking package failed: %w", err) } return nil }, diff --git a/cmd/clean.go b/cmd/clean.go index 9cf7e2392..48794116e 100644 --- a/cmd/clean.go +++ b/cmd/clean.go @@ -5,7 +5,8 @@ package cmd import ( - "github.com/pkg/errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cleanup" @@ -32,7 +33,7 @@ func cleanCommandAction(cmd *cobra.Command, args []string) error { target, err := cleanup.Build() if err != nil { - return errors.Wrap(err, "can't clean build resources") + return fmt.Errorf("can't clean build resources: %w", err) } if target != "" { @@ -41,7 +42,7 @@ func cleanCommandAction(cmd *cobra.Command, args []string) error { target, err = cleanup.Stack() if err != nil { - return errors.Wrap(err, "can't clean the development stack") + return fmt.Errorf("can't clean the development stack: %w", err) } if target != "" { cmd.Printf("Package removed from the development stack: %s\n", target) @@ -49,7 +50,7 @@ func cleanCommandAction(cmd *cobra.Command, args []string) error { target, err = cleanup.ServiceLogs() if err != nil { - return errors.Wrap(err, "can't clean temporary service logs") + return fmt.Errorf("can't clean temporary service logs: %w", err) } if target != "" { cmd.Printf("Temporary service logs removed: %s\n", target) diff --git a/cmd/create_data_stream.go b/cmd/create_data_stream.go index e4ec6689e..14e9fd6a8 100644 --- a/cmd/create_data_stream.go +++ b/cmd/create_data_stream.go @@ -5,8 +5,11 @@ package cmd import ( + "errors" + "fmt" + "github.com/AlecAivazis/survey/v2" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/packages" @@ -31,7 +34,7 @@ func createDataStreamCommandAction(cmd *cobra.Command, args []string) error { packageRoot, found, err := packages.FindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } if !found { return errors.New("package root not found, you can only create new data stream in the package context") @@ -67,7 +70,7 @@ func createDataStreamCommandAction(cmd *cobra.Command, args []string) error { var answers newDataStreamAnswers err = survey.Ask(qs, &answers) if err != nil { - return errors.Wrap(err, "prompt failed") + return fmt.Errorf("prompt failed: %w", err) } if answers.Type == "metrics" { @@ -83,7 +86,7 @@ func createDataStreamCommandAction(cmd *cobra.Command, args []string) error { } err = survey.Ask(qs, &answers) if err != nil { - return errors.Wrap(err, "prompt failed") + return fmt.Errorf("prompt failed: %w", err) } if !answers.SyntheticAndTimeSeries { @@ -99,7 +102,7 @@ func createDataStreamCommandAction(cmd *cobra.Command, args []string) error { } err = survey.Ask(qs, &answers) if err != nil { - return errors.Wrap(err, "prompt failed") + return fmt.Errorf("prompt failed: %w", err) } } } @@ -107,7 +110,7 @@ func createDataStreamCommandAction(cmd *cobra.Command, args []string) error { descriptor := createDataStreamDescriptorFromAnswers(answers, packageRoot) err = archetype.CreateDataStream(descriptor) if err != nil { - return errors.Wrap(err, "can't create new data stream") + return fmt.Errorf("can't create new data stream: %w", err) } cmd.Println("Done") diff --git a/cmd/create_package.go b/cmd/create_package.go index ab5f3b152..14cda0d34 100644 --- a/cmd/create_package.go +++ b/cmd/create_package.go @@ -5,8 +5,10 @@ package cmd import ( + "fmt" + "github.com/AlecAivazis/survey/v2" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/licenses" @@ -133,13 +135,13 @@ func createPackageCommandAction(cmd *cobra.Command, args []string) error { var answers newPackageAnswers err := survey.Ask(qs, &answers) if err != nil { - return errors.Wrap(err, "prompt failed") + return fmt.Errorf("prompt failed: %w", err) } descriptor := createPackageDescriptorFromAnswers(answers) err = archetype.CreatePackage(descriptor) if err != nil { - return errors.Wrap(err, "can't create new package") + return fmt.Errorf("can't create new package: %w", err) } cmd.Println("Done") diff --git a/cmd/dump.go b/cmd/dump.go index 9b6741088..939b52170 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -7,7 +7,6 @@ package cmd import ( "fmt" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -82,13 +81,13 @@ func dumpInstalledObjectsCmdAction(cmd *cobra.Command, args []string) error { } client, err := elasticsearch.NewClient(clientOptions...) if err != nil { - return errors.Wrap(err, "failed to initialize Elasticsearch client") + return fmt.Errorf("failed to initialize Elasticsearch client: %w", err) } dumper := dump.NewInstalledObjectsDumper(client.API, packageName) n, err := dumper.DumpAll(cmd.Context(), outputPath) if err != nil { - return errors.Wrap(err, "dump failed") + return fmt.Errorf("dump failed: %w", err) } if n == 0 { cmd.Printf("No objects were dumped for package %s, is it installed?\n", packageName) @@ -122,7 +121,7 @@ func dumpAgentPoliciesCmdAction(cmd *cobra.Command, args []string) error { } kibanaClient, err := kibana.NewClient(clientOptions...) if err != nil { - return errors.Wrap(err, "failed to initialize Kibana client") + return fmt.Errorf("failed to initialize Kibana client: %w", err) } switch { @@ -132,14 +131,14 @@ func dumpAgentPoliciesCmdAction(cmd *cobra.Command, args []string) error { dumper := dump.NewAgentPoliciesDumper(kibanaClient) err = dumper.DumpByName(cmd.Context(), outputPath, agentPolicy) if err != nil { - return errors.Wrap(err, "dump failed") + return fmt.Errorf("dump failed: %w", err) } cmd.Printf("Dumped agent policy %s to %s\n", agentPolicy, outputPath) case packageName != "": dumper := dump.NewAgentPoliciesDumper(kibanaClient) count, err := dumper.DumpByPackage(cmd.Context(), outputPath, packageName) if err != nil { - return errors.Wrap(err, "dump failed") + return fmt.Errorf("dump failed: %w", err) } if count != 0 { cmd.Printf("Dumped %d agent policies filtering by package name %s to %s\n", count, packageName, outputPath) @@ -150,7 +149,7 @@ func dumpAgentPoliciesCmdAction(cmd *cobra.Command, args []string) error { dumper := dump.NewAgentPoliciesDumper(kibanaClient) count, err := dumper.DumpAll(cmd.Context(), outputPath) if err != nil { - return errors.Wrap(err, "dump failed") + return fmt.Errorf("dump failed: %w", err) } if count != 0 { cmd.Printf("Dumped %d agent policies to %s\n", count, outputPath) diff --git a/cmd/export.go b/cmd/export.go index 71bf9a2ca..b72bb8a1c 100644 --- a/cmd/export.go +++ b/cmd/export.go @@ -8,7 +8,7 @@ import ( "fmt" "github.com/AlecAivazis/survey/v2" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -67,18 +67,18 @@ func exportDashboardsCmd(cmd *cobra.Command, args []string) error { kibanaClient, err := kibana.NewClient(opts...) if err != nil { - return errors.Wrap(err, "can't create Kibana client") + return fmt.Errorf("can't create Kibana client: %w", err) } kibanaVersion, err := kibanaClient.Version() if err != nil { - return errors.Wrap(err, "can't get Kibana status information") + return fmt.Errorf("can't get Kibana status information: %w", err) } if kibanaVersion.IsSnapshot() { message := fmt.Sprintf("exporting dashboards from a SNAPSHOT version of Kibana (%s) is discouraged. It could lead to invalid dashboards (for example if they use features that are reverted or modified before the final release)", kibanaVersion.Version()) if !allowSnapshot { - return errors.Errorf("%s. --%s flag can be used to ignore this error", message, cobraext.AllowSnapshotFlagName) + return fmt.Errorf("%s. --%s flag can be used to ignore this error", message, cobraext.AllowSnapshotFlagName) } fmt.Printf("Warning: %s\n", message) } @@ -86,7 +86,7 @@ func exportDashboardsCmd(cmd *cobra.Command, args []string) error { if len(dashboardIDs) == 0 { dashboardIDs, err = promptDashboardIDs(kibanaClient) if err != nil { - return errors.Wrap(err, "prompt for dashboard selection failed") + return fmt.Errorf("prompt for dashboard selection failed: %w", err) } if len(dashboardIDs) == 0 { @@ -97,7 +97,7 @@ func exportDashboardsCmd(cmd *cobra.Command, args []string) error { err = export.Dashboards(kibanaClient, dashboardIDs) if err != nil { - return errors.Wrap(err, "dashboards export failed") + return fmt.Errorf("dashboards export failed: %w", err) } cmd.Println("Done") @@ -107,7 +107,7 @@ func exportDashboardsCmd(cmd *cobra.Command, args []string) error { func promptDashboardIDs(kibanaClient *kibana.Client) ([]string, error) { savedDashboards, err := kibanaClient.FindDashboards() if err != nil { - return nil, errors.Wrap(err, "finding dashboards failed") + return nil, fmt.Errorf("finding dashboards failed: %w", err) } if len(savedDashboards) == 0 { diff --git a/cmd/format.go b/cmd/format.go index 69ce59fa4..622a76cf7 100644 --- a/cmd/format.go +++ b/cmd/format.go @@ -5,7 +5,9 @@ package cmd import ( - "github.com/pkg/errors" + "errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -34,7 +36,7 @@ func formatCommandAction(cmd *cobra.Command, args []string) error { packageRoot, found, err := packages.FindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } if !found { return errors.New("package root not found") @@ -47,7 +49,7 @@ func formatCommandAction(cmd *cobra.Command, args []string) error { err = formatter.Format(packageRoot, ff) if err != nil { - return errors.Wrapf(err, "formatting the integration failed (path: %s, failFast: %t)", packageRoot, ff) + return fmt.Errorf("formatting the integration failed (path: %s, failFast: %t): %w", packageRoot, ff, err) } cmd.Println("Done") diff --git a/cmd/install.go b/cmd/install.go index 40826d608..ddfbf370b 100644 --- a/cmd/install.go +++ b/cmd/install.go @@ -5,7 +5,9 @@ package cmd import ( - "github.com/pkg/errors" + "errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -49,7 +51,7 @@ func installCommandAction(cmd *cobra.Command, _ []string) error { kibanaClient, err := kibana.NewClient() if err != nil { - return errors.Wrap(err, "could not create kibana client") + return fmt.Errorf("could not create kibana client: %w", err) } if zipPathFile == "" && packageRootPath == "" { @@ -60,7 +62,7 @@ func installCommandAction(cmd *cobra.Command, _ []string) error { return errors.New("package root not found") } if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } } @@ -71,13 +73,13 @@ func installCommandAction(cmd *cobra.Command, _ []string) error { ZipPath: zipPathFile, }) if err != nil { - return errors.Wrap(err, "package installation failed") + return fmt.Errorf("package installation failed: %w", err) } // Check conditions keyValuePairs, err := cmd.Flags().GetStringSlice(cobraext.CheckConditionFlagName) if err != nil { - return errors.Wrap(err, "can't process check-condition flag") + return fmt.Errorf("can't process check-condition flag: %w", err) } if len(keyValuePairs) > 0 { manifest, err := installer.Manifest() @@ -88,7 +90,7 @@ func installCommandAction(cmd *cobra.Command, _ []string) error { cmd.Println("Check conditions for package") err = packages.CheckConditions(*manifest, keyValuePairs) if err != nil { - return errors.Wrap(err, "checking conditions failed") + return fmt.Errorf("checking conditions failed: %w", err) } cmd.Println("Requirements satisfied - the package can be installed.") cmd.Println("Done") diff --git a/cmd/lint.go b/cmd/lint.go index f1c8c4568..daf0a0be3 100644 --- a/cmd/lint.go +++ b/cmd/lint.go @@ -5,7 +5,9 @@ package cmd import ( - "github.com/pkg/errors" + "errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/package-spec/v2/code/go/pkg/validator" @@ -53,7 +55,7 @@ func lintCommandAction(cmd *cobra.Command, args []string) error { cmd.Printf("check if %s is up-to-date failed: %s\n", f.FileName, f.Error) } } - return errors.Wrap(err, "checking readme files are up-to-date failed") + return fmt.Errorf("checking readme files are up-to-date failed: %w", err) } return nil } @@ -64,11 +66,11 @@ func validateSourceCommandAction(cmd *cobra.Command, args []string) error { return errors.New("package root not found") } if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } err = validator.ValidateFromPath(packageRootPath) if err != nil { - return errors.Wrap(err, "linting package failed") + return fmt.Errorf("linting package failed: %w", err) } return nil diff --git a/cmd/profiles.go b/cmd/profiles.go index b2f6e0b59..6960e0735 100644 --- a/cmd/profiles.go +++ b/cmd/profiles.go @@ -6,12 +6,13 @@ package cmd import ( "encoding/json" + "errors" "fmt" "os" "time" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -59,7 +60,7 @@ User profiles can be configured with a "config.yml" file in the profile director } err = profile.CreateProfile(options) if err != nil { - return errors.Wrapf(err, "error creating profile %s from profile %s", newProfileName, fromName) + return fmt.Errorf("error creating profile %s from profile %s: %w", newProfileName, fromName, err) } if fromName == "" { @@ -89,7 +90,7 @@ User profiles can be configured with a "config.yml" file in the profile director err = profile.DeleteProfile(profileName) if err != nil { - return errors.Wrap(err, "error deleting profile") + return fmt.Errorf("error deleting profile: %w", err) } if currentProfile := config.CurrentProfile(); currentProfile == profileName { @@ -119,11 +120,11 @@ User profiles can be configured with a "config.yml" file in the profile director RunE: func(cmd *cobra.Command, args []string) error { loc, err := locations.NewLocationManager() if err != nil { - return errors.Wrap(err, "error fetching profile") + return fmt.Errorf("error fetching profile: %w", err) } profileList, err := profile.FetchAllProfiles(loc.ProfileDir()) if err != nil { - return errors.Wrap(err, "error listing all profiles") + return fmt.Errorf("error listing all profiles: %w", err) } if len(profileList) == 0 { fmt.Println("There are no profiles yet.") @@ -199,7 +200,7 @@ User profiles can be configured with a "config.yml" file in the profile director func formatJSON(profileList []profile.Metadata) error { data, err := json.Marshal(profileList) if err != nil { - return errors.Wrap(err, "error listing all profiles in JSON format") + return fmt.Errorf("error listing all profiles in JSON format: %w", err) } fmt.Print(string(data)) diff --git a/cmd/service.go b/cmd/service.go index fb5206b6a..42f6aa757 100644 --- a/cmd/service.go +++ b/cmd/service.go @@ -5,9 +5,10 @@ package cmd import ( + "errors" + "fmt" "path/filepath" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -43,7 +44,7 @@ func upCommandAction(cmd *cobra.Command, args []string) error { packageRoot, found, err := packages.FindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } if !found { return errors.New("package root not found") @@ -65,7 +66,7 @@ func upCommandAction(cmd *cobra.Command, args []string) error { Variant: variantFlag, }) if err != nil { - return errors.Wrap(err, "up command failed") + return fmt.Errorf("up command failed: %w", err) } return nil } diff --git a/cmd/stack.go b/cmd/stack.go index a2a755fe4..2eb110ae2 100644 --- a/cmd/stack.go +++ b/cmd/stack.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/jedib0t/go-pretty/table" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -68,7 +68,7 @@ func setupStackCommand() *cobraext.Command { err = validateServicesFlag(services) if err != nil { - return errors.Wrap(err, "validating services failed") + return fmt.Errorf("validating services failed: %w", err) } stackVersion, err := cmd.Flags().GetString(cobraext.StackVersionFlagName) @@ -96,7 +96,7 @@ func setupStackCommand() *cobraext.Command { Printer: cmd, }) if err != nil { - return errors.Wrap(err, "booting up the stack failed") + return fmt.Errorf("booting up the stack failed: %w", err) } cmd.Println("Done") @@ -130,7 +130,7 @@ func setupStackCommand() *cobraext.Command { Printer: cmd, }) if err != nil { - return errors.Wrap(err, "tearing down the stack failed") + return fmt.Errorf("tearing down the stack failed: %w", err) } cmd.Println("Done") @@ -165,7 +165,7 @@ func setupStackCommand() *cobraext.Command { Printer: cmd, }) if err != nil { - return errors.Wrap(err, "failed updating the stack images") + return fmt.Errorf("failed updating the stack images: %w", err) } cmd.Println("Done") @@ -194,7 +194,7 @@ func setupStackCommand() *cobraext.Command { shellCode, err := stack.ShellInit(profile, shellName) if err != nil { - return errors.Wrap(err, "shellinit failed") + return fmt.Errorf("shellinit failed: %w", err) } fmt.Println(shellCode) return nil @@ -227,7 +227,7 @@ func setupStackCommand() *cobraext.Command { Profile: profile, }) if err != nil { - return errors.Wrap(err, "dump failed") + return fmt.Errorf("dump failed: %w", err) } cmd.Printf("Path to stack dump: %s\n", target) @@ -257,7 +257,7 @@ func setupStackCommand() *cobraext.Command { Printer: cmd, }) if err != nil { - return errors.Wrap(err, "failed getting stack status") + return fmt.Errorf("failed getting stack status: %w", err) } cmd.Println("Status of Elastic stack services:") diff --git a/cmd/status.go b/cmd/status.go index 3a4f9f723..4a1d07f69 100644 --- a/cmd/status.go +++ b/cmd/status.go @@ -5,6 +5,7 @@ package cmd import ( + "errors" "fmt" "io" "os" @@ -13,7 +14,7 @@ import ( "github.com/Masterminds/semver/v3" "github.com/fatih/color" "github.com/olekukonko/tablewriter" - "github.com/pkg/errors" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -82,7 +83,7 @@ func getPackageStatus(packageName string, options registry.SearchOptions) (*stat return nil, errors.New("no package specified and package root not found") } if err != nil { - return nil, errors.Wrap(err, "locating package root failed") + return nil, fmt.Errorf("locating package root failed: %w", err) } return status.LocalPackage(packageRootPath, options) } diff --git a/cmd/testrunner.go b/cmd/testrunner.go index 603f60ba2..ec04598a7 100644 --- a/cmd/testrunner.go +++ b/cmd/testrunner.go @@ -5,12 +5,12 @@ package cmd import ( + "errors" "fmt" "os" "path/filepath" "strings" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -130,17 +130,17 @@ func testTypeCommandActionFactory(runner testrunner.TestRunner) cobraext.Command return errors.New("package root not found") } if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } manifest, err := packages.ReadPackageManifestFromPackageRoot(packageRootPath) if err != nil { - return errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRootPath) + return fmt.Errorf("reading package manifest failed (path: %s): %w", packageRootPath, err) } hasDataStreams, err := packageHasDataStreams(manifest) if err != nil { - return errors.Wrapf(err, "cannot determine if package has data streams") + return fmt.Errorf("cannot determine if package has data streams: %w", err) } signal.Enable() @@ -167,12 +167,12 @@ func testTypeCommandActionFactory(runner testrunner.TestRunner) cobraext.Command if runner.TestFolderRequired() { testFolders, err = testrunner.FindTestFolders(packageRootPath, dataStreams, testType) if err != nil { - return errors.Wrap(err, "unable to determine test folder paths") + return fmt.Errorf("unable to determine test folder paths: %w", err) } } else { testFolders, err = testrunner.AssumeTestFolders(packageRootPath, dataStreams, testType) if err != nil { - return errors.Wrap(err, "unable to assume test folder paths") + return fmt.Errorf("unable to assume test folder paths: %w", err) } } @@ -188,7 +188,7 @@ func testTypeCommandActionFactory(runner testrunner.TestRunner) cobraext.Command if runner.TestFolderRequired() { testFolders, err = testrunner.FindTestFolders(packageRootPath, nil, testType) if err != nil { - return errors.Wrap(err, "unable to determine test folder paths") + return fmt.Errorf("unable to determine test folder paths: %w", err) } if failOnMissing && len(testFolders) == 0 { return fmt.Errorf("no %s tests found", testType) @@ -216,7 +216,7 @@ func testTypeCommandActionFactory(runner testrunner.TestRunner) cobraext.Command esClient, err := elasticsearch.NewClient() if err != nil { - return errors.Wrap(err, "can't create Elasticsearch client") + return fmt.Errorf("can't create Elasticsearch client: %w", err) } err = esClient.CheckHealth(cmd.Context()) if err != nil { @@ -239,24 +239,24 @@ func testTypeCommandActionFactory(runner testrunner.TestRunner) cobraext.Command results = append(results, r...) if err != nil { - return errors.Wrapf(err, "error running package %s tests", testType) + return fmt.Errorf("error running package %s tests: %w", testType, err) } } format := testrunner.TestReportFormat(reportFormat) report, err := testrunner.FormatReport(format, results) if err != nil { - return errors.Wrap(err, "error formatting test report") + return fmt.Errorf("error formatting test report: %w", err) } if err := testrunner.WriteReport(manifest.Name, testrunner.TestReportOutput(reportOutput), report, format); err != nil { - return errors.Wrap(err, "error writing test report") + return fmt.Errorf("error writing test report: %w", err) } if testCoverage { err := testrunner.WriteCoverage(packageRootPath, manifest.Name, runner.Type(), results) if err != nil { - return errors.Wrap(err, "error writing test coverage") + return fmt.Errorf("error writing test coverage: %w", err) } } @@ -286,7 +286,7 @@ func validateDataStreamsFlag(packageRootPath string, dataStreams []string) error path := filepath.Join(packageRootPath, "data_stream", dataStream) fileInfo, err := os.Stat(path) if err != nil { - return errors.Wrapf(err, "stat directory failed (path: %s)", path) + return fmt.Errorf("stat directory failed (path: %s): %w", path, err) } if !fileInfo.IsDir() { diff --git a/cmd/uninstall.go b/cmd/uninstall.go index 71a72469e..4d3a5b0d5 100644 --- a/cmd/uninstall.go +++ b/cmd/uninstall.go @@ -5,7 +5,9 @@ package cmd import ( - "github.com/pkg/errors" + "errors" + "fmt" + "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/cobraext" @@ -35,23 +37,23 @@ func uninstallCommandAction(cmd *cobra.Command, args []string) error { return errors.New("package root not found") } if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } kibanaClient, err := kibana.NewClient() if err != nil { - return errors.Wrap(err, "could not create kibana client") + return fmt.Errorf("could not create kibana client: %w", err) } packageInstaller, err := installer.CreateForManifest(kibanaClient, packageRootPath) if err != nil { - return errors.Wrap(err, "can't create the package installer") + return fmt.Errorf("can't create the package installer: %w", err) } // Uninstall the package cmd.Println("Uninstall the package") err = packageInstaller.Uninstall() if err != nil { - return errors.Wrap(err, "can't uninstall the package") + return fmt.Errorf("can't uninstall the package: %w", err) } cmd.Println("Done") return nil diff --git a/go.mod b/go.mod index a52cd9b4e..da381a873 100644 --- a/go.mod +++ b/go.mod @@ -27,7 +27,6 @@ require ( github.com/magefile/mage v1.15.0 github.com/mholt/archiver/v3 v3.5.1 github.com/olekukonko/tablewriter v0.0.5 - github.com/pkg/errors v0.9.1 github.com/pmezard/go-difflib v1.0.0 github.com/shirou/gopsutil/v3 v3.23.5 github.com/spf13/cobra v1.7.0 @@ -124,6 +123,7 @@ require ( github.com/peterbourgon/diskv v2.0.1+incompatible // indirect github.com/pierrec/lz4/v4 v4.1.17 // indirect github.com/pjbgf/sha1cd v0.3.0 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect github.com/rivo/uniseg v0.4.3 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect diff --git a/internal/builder/dashboards.go b/internal/builder/dashboards.go index 87223ef25..24d533e8b 100644 --- a/internal/builder/dashboards.go +++ b/internal/builder/dashboards.go @@ -6,11 +6,10 @@ package builder import ( "encoding/json" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/common" ) @@ -58,7 +57,7 @@ func encodedSavedObject(data []byte) ([]byte, bool, error) { savedObject := common.MapStr{} err := json.Unmarshal(data, &savedObject) if err != nil { - return nil, false, errors.Wrapf(err, "unmarshalling saved object failed") + return nil, false, fmt.Errorf("unmarshalling saved object failed: %w", err) } var changed bool @@ -83,7 +82,7 @@ func encodedSavedObject(data []byte) ([]byte, bool, error) { } _, err = savedObject.Put(v, string(r)) if err != nil { - return nil, false, errors.Wrapf(err, "can't put value to the saved object") + return nil, false, fmt.Errorf("can't put value to the saved object: %w", err) } changed = true } diff --git a/internal/builder/dynamic_mappings.go b/internal/builder/dynamic_mappings.go index f1e9d0967..7f0c458f8 100644 --- a/internal/builder/dynamic_mappings.go +++ b/internal/builder/dynamic_mappings.go @@ -6,13 +6,14 @@ package builder import ( _ "embed" + "errors" "fmt" "os" "path/filepath" "strconv" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" + "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/formatter" @@ -86,12 +87,12 @@ func addDynamicMappings(packageRoot, destinationDir string) error { func shouldImportEcsMappings(specVersion, packageRoot string) (bool, error) { v, err := semver.NewVersion(specVersion) if err != nil { - return false, errors.Wrap(err, "invalid spec version") + return false, fmt.Errorf("invalid spec version: %w", err) } bm, ok, err := buildmanifest.ReadBuildManifest(packageRoot) if err != nil { - return false, errors.Wrap(err, "can't read build manifest") + return false, fmt.Errorf("can't read build manifest: %w", err) } if !ok { logger.Debug("Build manifest hasn't been defined for the package") @@ -153,14 +154,14 @@ func addEcsMappings(doc *yaml.Node, mappings ecsTemplates) error { var templates yaml.Node err := templates.Encode(mappings.Mappings.DynamicTemplates) if err != nil { - return errors.Wrap(err, "failed to encode dynamic templates") + return fmt.Errorf("failed to encode dynamic templates: %w", err) } renameMappingsNames(&templates) err = appendElements(doc, []string{"elasticsearch", "index_template", "mappings", "dynamic_templates"}, &templates) if err != nil { - return errors.Wrap(err, "failed to append dynamic templates") + return fmt.Errorf("failed to append dynamic templates: %w", err) } return nil @@ -214,7 +215,7 @@ func appendElements(root *yaml.Node, path []string, values *yaml.Node) error { return err } if len(root.Content) >= index { - return errors.Errorf("index out of range in nodes from key %s", key) + return fmt.Errorf("index out of range in nodes from key %s", key) } return appendElements(root.Content[index], rest, values) diff --git a/internal/builder/external_fields.go b/internal/builder/external_fields.go index 961500adf..355edffc0 100644 --- a/internal/builder/external_fields.go +++ b/internal/builder/external_fields.go @@ -5,10 +5,10 @@ package builder import ( + "fmt" "os" "path/filepath" - "github.com/pkg/errors" "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/common" @@ -20,7 +20,7 @@ import ( func resolveExternalFields(packageRoot, destinationDir string) error { bm, ok, err := buildmanifest.ReadBuildManifest(packageRoot) if err != nil { - return errors.Wrap(err, "can't read build manifest") + return fmt.Errorf("can't read build manifest: %w", err) } if !ok { logger.Debugf("Build manifest hasn't been defined for the package") @@ -34,7 +34,7 @@ func resolveExternalFields(packageRoot, destinationDir string) error { logger.Debugf("Package has external dependencies defined") fdm, err := fields.CreateFieldDependencyManager(bm.Dependencies) if err != nil { - return errors.Wrap(err, "can't create field dependency manager") + return fmt.Errorf("can't create field dependency manager: %w", err) } dataStreamFieldsFiles, err := filepath.Glob(filepath.Join(destinationDir, "data_stream", "*", "fields", "*.yml")) @@ -76,12 +76,12 @@ func injectFields(fdm *fields.DependencyManager, content []byte) ([]byte, bool, var f []common.MapStr err := yaml.Unmarshal(content, &f) if err != nil { - return nil, false, errors.Wrap(err, "can't unmarshal source file") + return nil, false, fmt.Errorf("can't unmarshal source file: %w", err) } f, changed, err := fdm.InjectFields(f) if err != nil { - return nil, false, errors.Wrap(err, "can't resolve fields") + return nil, false, fmt.Errorf("can't resolve fields: %w", err) } if !changed { return content, false, nil @@ -89,7 +89,7 @@ func injectFields(fdm *fields.DependencyManager, content []byte) ([]byte, bool, content, err = yaml.Marshal(&f) if err != nil { - return nil, false, errors.Wrap(err, "can't marshal source file") + return nil, false, fmt.Errorf("can't marshal source file: %w", err) } return content, true, nil } diff --git a/internal/builder/packages.go b/internal/builder/packages.go index 9e28fd11c..45725be74 100644 --- a/internal/builder/packages.go +++ b/internal/builder/packages.go @@ -5,12 +5,12 @@ package builder import ( + "errors" "fmt" "os" "path/filepath" "github.com/magefile/mage/sh" - "github.com/pkg/errors" "github.com/elastic/package-spec/v2/code/go/pkg/validator" @@ -37,12 +37,12 @@ type BuildOptions struct { func BuildDirectory() (string, error) { buildDir, found, err := findBuildDirectory() if err != nil { - return "", errors.Wrap(err, "can't locate build directory") + return "", fmt.Errorf("can't locate build directory: %w", err) } if !found { buildDir, err = createBuildDirectory() if err != nil { - return "", errors.Wrap(err, "can't create new build directory") + return "", fmt.Errorf("can't create new build directory: %w", err) } } return buildDir, nil @@ -51,7 +51,7 @@ func BuildDirectory() (string, error) { func findBuildDirectory() (string, bool, error) { workDir, err := os.Getwd() if err != nil { - return "", false, errors.Wrap(err, "can't locate build directory") + return "", false, fmt.Errorf("can't locate build directory: %w", err) } dir := workDir @@ -76,11 +76,11 @@ func findBuildDirectory() (string, bool, error) { func BuildPackagesDirectory(packageRoot string) (string, error) { buildDir, err := buildPackagesRootDirectory() if err != nil { - return "", errors.Wrap(err, "can't locate build packages root directory") + return "", fmt.Errorf("can't locate build packages root directory: %w", err) } m, err := packages.ReadPackageManifestFromPackageRoot(packageRoot) if err != nil { - return "", errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRoot) + return "", fmt.Errorf("reading package manifest failed (path: %s): %w", packageRoot, err) } return filepath.Join(buildDir, m.Name, m.Version), nil } @@ -89,11 +89,11 @@ func BuildPackagesDirectory(packageRoot string) (string, error) { func buildPackagesZipPath(packageRoot string) (string, error) { buildDir, err := buildPackagesRootDirectory() if err != nil { - return "", errors.Wrap(err, "can't locate build packages root directory") + return "", fmt.Errorf("can't locate build packages root directory: %w", err) } m, err := packages.ReadPackageManifestFromPackageRoot(packageRoot) if err != nil { - return "", errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRoot) + return "", fmt.Errorf("reading package manifest failed (path: %s): %w", packageRoot, err) } return ZippedBuiltPackagePath(buildDir, *m), nil } @@ -106,12 +106,12 @@ func ZippedBuiltPackagePath(buildDir string, m packages.PackageManifest) string func buildPackagesRootDirectory() (string, error) { buildDir, found, err := FindBuildPackagesDirectory() if err != nil { - return "", errors.Wrap(err, "can't locate build directory") + return "", fmt.Errorf("can't locate build directory: %w", err) } if !found { buildDir, err = createBuildDirectory(builtPackagesFolder) if err != nil { - return "", errors.Wrap(err, "can't create new build directory") + return "", fmt.Errorf("can't create new build directory: %w", err) } } return buildDir, nil @@ -146,43 +146,43 @@ func FindBuildPackagesDirectory() (string, bool, error) { func BuildPackage(options BuildOptions) (string, error) { destinationDir, err := BuildPackagesDirectory(options.PackageRoot) if err != nil { - return "", errors.Wrap(err, "can't locate build directory") + return "", fmt.Errorf("can't locate build directory: %w", err) } logger.Debugf("Build directory: %s\n", destinationDir) logger.Debugf("Clear target directory (path: %s)", destinationDir) err = files.ClearDir(destinationDir) if err != nil { - return "", errors.Wrap(err, "clearing package contents failed") + return "", fmt.Errorf("clearing package contents failed: %w", err) } logger.Debugf("Copy package content (source: %s)", options.PackageRoot) err = files.CopyWithoutDev(options.PackageRoot, destinationDir) if err != nil { - return "", errors.Wrap(err, "copying package contents failed") + return "", fmt.Errorf("copying package contents failed: %w", err) } logger.Debug("Copy license file if needed") err = copyLicenseTextFile(filepath.Join(destinationDir, licenseTextFileName)) if err != nil { - return "", errors.Wrap(err, "copying license text file") + return "", fmt.Errorf("copying license text file: %w", err) } logger.Debug("Encode dashboards") err = encodeDashboards(destinationDir) if err != nil { - return "", errors.Wrap(err, "encoding dashboards failed") + return "", fmt.Errorf("encoding dashboards failed: %w", err) } logger.Debug("Resolve external fields") err = resolveExternalFields(options.PackageRoot, destinationDir) if err != nil { - return "", errors.Wrap(err, "resolving external fields failed") + return "", fmt.Errorf("resolving external fields failed: %w", err) } err = addDynamicMappings(options.PackageRoot, destinationDir) if err != nil { - return "", errors.Wrap(err, "adding dynamic mappings") + return "", fmt.Errorf("adding dynamic mappings: %w", err) } if options.CreateZip { @@ -197,7 +197,7 @@ func BuildPackage(options BuildOptions) (string, error) { logger.Debugf("Validating built package (path: %s)", destinationDir) err = validator.ValidateFromPath(destinationDir) if err != nil { - return "", errors.Wrap(err, "invalid content found in built package") + return "", fmt.Errorf("invalid content found in built package: %w", err) } return destinationDir, nil } @@ -206,12 +206,12 @@ func buildZippedPackage(options BuildOptions, destinationDir string) (string, er logger.Debug("Build zipped package") zippedPackagePath, err := buildPackagesZipPath(options.PackageRoot) if err != nil { - return "", errors.Wrap(err, "can't evaluate path for the zipped package") + return "", fmt.Errorf("can't evaluate path for the zipped package: %w", err) } err = files.Zip(destinationDir, zippedPackagePath) if err != nil { - return "", errors.Wrapf(err, "can't compress the built package (compressed file path: %s)", zippedPackagePath) + return "", fmt.Errorf("can't compress the built package (compressed file path: %s): %w", zippedPackagePath, err) } if options.SkipValidation { @@ -220,7 +220,7 @@ func buildZippedPackage(options BuildOptions, destinationDir string) (string, er logger.Debugf("Validating built .zip package (path: %s)", zippedPackagePath) err = validator.ValidateFromZip(zippedPackagePath) if err != nil { - return "", errors.Wrapf(err, "invalid content found in built zip package") + return "", fmt.Errorf("invalid content found in built zip package: %w", err) } } @@ -238,7 +238,7 @@ func signZippedPackage(options BuildOptions, zippedPackagePath string) error { logger.Debug("Sign the package") m, err := packages.ReadPackageManifestFromPackageRoot(options.PackageRoot) if err != nil { - return errors.Wrapf(err, "reading package manifest failed (path: %s)", options.PackageRoot) + return fmt.Errorf("reading package manifest failed (path: %s): %w", options.PackageRoot, err) } err = files.Sign(zippedPackagePath, files.SignOptions{ @@ -246,7 +246,7 @@ func signZippedPackage(options BuildOptions, zippedPackagePath string) error { PackageVersion: m.Version, }) if err != nil { - return errors.Wrapf(err, "can't sign the zipped package (path: %s)", zippedPackagePath) + return fmt.Errorf("can't sign the zipped package (path: %s): %w", zippedPackagePath, err) } return nil } @@ -269,13 +269,13 @@ func copyLicenseTextFile(licensePath string) error { return nil } if err != nil { - return errors.Wrapf(err, "failure while looking for license %q in repository", repositoryLicenseTextFileName) + return fmt.Errorf("failure while looking for license %q in repository: %w", repositoryLicenseTextFileName, err) } logger.Infof("License text found in %q will be included in package", sourceLicensePath) err = sh.Copy(licensePath, sourceLicensePath) if err != nil { - return errors.Wrap(err, "can't copy license from repository") + return fmt.Errorf("can't copy license from repository: %w", err) } return nil @@ -297,7 +297,7 @@ func createBuildDirectory(dirs ...string) (string, error) { buildDir := filepath.Join(p...) err = os.MkdirAll(buildDir, 0755) if err != nil { - return "", errors.Wrapf(err, "mkdir failed (path: %s)", buildDir) + return "", fmt.Errorf("mkdir failed (path: %s): %w", buildDir, err) } return buildDir, nil } @@ -311,7 +311,7 @@ func findRepositoryLicense(licenseTextFileName string) (string, error) { sourceFileName := filepath.Join(dir, licenseTextFileName) _, err = os.Stat(sourceFileName) if err != nil { - return "", errors.Wrapf(err, "failed to find repository license") + return "", fmt.Errorf("failed to find repository license: %w", err) } return sourceFileName, nil diff --git a/internal/cleanup/build.go b/internal/cleanup/build.go index bddfd7a97..8a55642a9 100644 --- a/internal/cleanup/build.go +++ b/internal/cleanup/build.go @@ -5,11 +5,11 @@ package cleanup import ( + "errors" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/builder" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/packages" @@ -21,17 +21,17 @@ func Build() (string, error) { packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return "", errors.Wrap(err, "locating package root failed") + return "", fmt.Errorf("locating package root failed: %w", err) } m, err := packages.ReadPackageManifestFromPackageRoot(packageRoot) if err != nil { - return "", errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRoot) + return "", fmt.Errorf("reading package manifest failed (path: %s): %w", packageRoot, err) } buildDir, found, err := builder.FindBuildPackagesDirectory() if err != nil { - return "", errors.Wrap(err, "locating build directory failed") + return "", fmt.Errorf("locating build directory failed: %w", err) } if !found { @@ -44,7 +44,7 @@ func Build() (string, error) { _, err = os.Stat(destinationDir) if err != nil && !errors.Is(err, os.ErrNotExist) { - return "", errors.Wrapf(err, "stat file failed: %s", destinationDir) + return "", fmt.Errorf("stat file failed: %s: %w", destinationDir, err) } if errors.Is(err, os.ErrNotExist) { logger.Debugf("Package hasn't been built (missing path: %s)", destinationDir) @@ -54,14 +54,14 @@ func Build() (string, error) { logger.Debugf("Remove directory (path: %s)", destinationDir) err = os.RemoveAll(destinationDir) if err != nil { - return "", errors.Wrapf(err, "can't remove directory (path: %s)", destinationDir) + return "", fmt.Errorf("can't remove directory (path: %s): %w", destinationDir, err) } zippedBuildPackagePath := builder.ZippedBuiltPackagePath(buildDir, *m) logger.Debugf("Remove zipped built package (path: %s)", zippedBuildPackagePath) err = os.RemoveAll(zippedBuildPackagePath) if err != nil { - return "", errors.Wrapf(err, "can't remove zipped built package (path: %s)", zippedBuildPackagePath) + return "", fmt.Errorf("can't remove zipped built package (path: %s): %w", zippedBuildPackagePath, err) } return destinationDir, nil } diff --git a/internal/cleanup/service_logs.go b/internal/cleanup/service_logs.go index b5d78a882..9dda02cbe 100644 --- a/internal/cleanup/service_logs.go +++ b/internal/cleanup/service_logs.go @@ -5,7 +5,7 @@ package cleanup import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/files" @@ -18,13 +18,13 @@ func ServiceLogs() (string, error) { locationManager, err := locations.NewLocationManager() if err != nil { - return "", errors.Wrap(err, "can't find service logs dir") + return "", fmt.Errorf("can't find service logs dir: %w", err) } logger.Debugf("Remove folder content (path: %s)", locationManager.ServiceLogDir()) err = files.RemoveContent(locationManager.ServiceLogDir()) if err != nil { - return "", errors.Wrapf(err, "can't remove content (path: %s)", locationManager.ServiceLogDir()) + return "", fmt.Errorf("can't remove content (path: %s): %w", locationManager.ServiceLogDir(), err) } return locationManager.ServiceLogDir(), nil } diff --git a/internal/cleanup/stack.go b/internal/cleanup/stack.go index d3312a025..f4844f71c 100644 --- a/internal/cleanup/stack.go +++ b/internal/cleanup/stack.go @@ -5,11 +5,11 @@ package cleanup import ( + "errors" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/packages" @@ -22,23 +22,23 @@ func Stack() (string, error) { packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return "", errors.Wrap(err, "locating package root failed") + return "", fmt.Errorf("locating package root failed: %w", err) } m, err := packages.ReadPackageManifestFromPackageRoot(packageRoot) if err != nil { - return "", errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRoot) + return "", fmt.Errorf("reading package manifest failed (path: %s): %w", packageRoot, err) } locationManager, err := locations.NewLocationManager() if err != nil { - return "", errors.Wrap(err, "can't find stack packages dir") + return "", fmt.Errorf("can't find stack packages dir: %w", err) } destinationDir := filepath.Join(locationManager.PackagesDir(), m.Name) _, err = os.Stat(destinationDir) if err != nil && !errors.Is(err, os.ErrNotExist) { - return "", errors.Wrapf(err, "stat file failed: %s", destinationDir) + return "", fmt.Errorf("stat file failed: %s: %w", destinationDir, err) } if errors.Is(err, os.ErrNotExist) { logger.Debugf("Stack package is not part of the development stack (missing path: %s)", destinationDir) @@ -48,7 +48,7 @@ func Stack() (string, error) { logger.Debugf("Remove folder (path: %s)", destinationDir) err = os.RemoveAll(destinationDir) if err != nil { - return "", errors.Wrapf(err, "can't remove directory (path: %s)", destinationDir) + return "", fmt.Errorf("can't remove directory (path: %s): %w", destinationDir, err) } return destinationDir, nil } diff --git a/internal/cobraext/errors.go b/internal/cobraext/errors.go index 52c29c467..1a37d769a 100644 --- a/internal/cobraext/errors.go +++ b/internal/cobraext/errors.go @@ -4,9 +4,9 @@ package cobraext -import "github.com/pkg/errors" +import "fmt" // FlagParsingError method wraps the original error with parsing error. func FlagParsingError(err error, flagName string) error { - return errors.Wrapf(err, "error parsing --%s flag", flagName) + return fmt.Errorf("error parsing --%s flag: %w", flagName, err) } diff --git a/internal/cobraext/profiles.go b/internal/cobraext/profiles.go index 968631243..bade86a9f 100644 --- a/internal/cobraext/profiles.go +++ b/internal/cobraext/profiles.go @@ -5,10 +5,10 @@ package cobraext import ( + "errors" "fmt" "strings" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/elastic/elastic-package/internal/configuration/locations" @@ -35,7 +35,7 @@ func GetProfileFlag(cmd *cobra.Command) (*profile.Profile, error) { if errors.Is(err, profile.ErrNotAProfile) { list, err := availableProfilesAsAList() if err != nil { - return nil, errors.Wrap(err, "error listing known profiles") + return nil, fmt.Errorf("error listing known profiles: %w", err) } if len(list) == 0 { return nil, fmt.Errorf("%s is not a valid profile", profileName) @@ -43,7 +43,7 @@ func GetProfileFlag(cmd *cobra.Command) (*profile.Profile, error) { return nil, fmt.Errorf("%s is not a valid profile, known profiles are: %s", profileName, strings.Join(list, ", ")) } if err != nil { - return nil, errors.Wrap(err, "error loading profile") + return nil, fmt.Errorf("error loading profile: %w", err) } return p, nil @@ -52,13 +52,13 @@ func GetProfileFlag(cmd *cobra.Command) (*profile.Profile, error) { func availableProfilesAsAList() ([]string, error) { loc, err := locations.NewLocationManager() if err != nil { - return []string{}, errors.Wrap(err, "error fetching profile path") + return []string{}, fmt.Errorf("error fetching profile path: %w", err) } profileNames := []string{} profileList, err := profile.FetchAllProfiles(loc.ProfileDir()) if err != nil { - return profileNames, errors.Wrap(err, "error fetching all profiles") + return profileNames, fmt.Errorf("error fetching all profiles: %w", err) } for _, prof := range profileList { profileNames = append(profileNames, prof.Name) diff --git a/internal/common/mapstr.go b/internal/common/mapstr.go index 9356bac37..721ca69a3 100644 --- a/internal/common/mapstr.go +++ b/internal/common/mapstr.go @@ -10,10 +10,9 @@ package common import ( "encoding/json" + "errors" "fmt" "strings" - - "github.com/pkg/errors" ) var ( @@ -148,7 +147,7 @@ func ToMapStrSlice(slice interface{}) ([]MapStr, error) { for _, v := range sliceI { m, err := toMapStr(v) if err != nil { - return nil, errors.Wrap(err, "can't convert element to MapStr") + return nil, fmt.Errorf("can't convert element to MapStr: %w", err) } mapStrs = append(mapStrs, m) } @@ -161,7 +160,7 @@ func ToMapStrSlice(slice interface{}) ([]MapStr, error) { func toMapStr(v interface{}) (MapStr, error) { m, ok := tryToMapStr(v) if !ok { - return nil, errors.Errorf("expected map but type is %T", v) + return nil, fmt.Errorf("expected map but type is %T", v) } return m, nil } diff --git a/internal/compose/compose.go b/internal/compose/compose.go index 035b98b60..5c71f5020 100644 --- a/internal/compose/compose.go +++ b/internal/compose/compose.go @@ -6,6 +6,7 @@ package compose import ( "bytes" + "errors" "fmt" "io" "os" @@ -15,7 +16,7 @@ import ( "time" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" + "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/docker" @@ -82,7 +83,7 @@ func (p *portMapping) UnmarshalYAML(node *yaml.Node) error { if node.Kind == yaml.MappingNode { b, err := yaml.Marshal(node) if err != nil { - return errors.Wrap(err, "could not re-encode YAML map node to YAML") + return fmt.Errorf("could not re-encode YAML map node to YAML: %w", err) } var s struct { @@ -93,7 +94,7 @@ func (p *portMapping) UnmarshalYAML(node *yaml.Node) error { } if err := yaml.Unmarshal(b, &s); err != nil { - return errors.Wrap(err, "could not unmarshal YAML map node") + return fmt.Errorf("could not unmarshal YAML map node: %w", err) } p.InternalPort = int(s.Target) @@ -130,14 +131,14 @@ func (p *portMapping) UnmarshalYAML(node *yaml.Node) error { internalPort, err := strconv.Atoi(internalPortStr) if err != nil { - return errors.Wrap(err, "error parsing internal port as integer") + return fmt.Errorf("error parsing internal port as integer: %w", err) } p.InternalPort = internalPort if externalPortStr != "" { externalPort, err := strconv.Atoi(externalPortStr) if err != nil { - return errors.Wrap(err, "error parsing external port as integer") + return fmt.Errorf("error parsing external port as integer: %w", err) } p.ExternalPort = externalPort } @@ -161,7 +162,7 @@ func NewProject(name string, paths ...string) (*Project, error) { for _, path := range paths { info, err := os.Stat(path) if err != nil { - return nil, errors.Wrapf(err, "could not find Docker Compose configuration file: %s", path) + return nil, fmt.Errorf("could not find Docker Compose configuration file: %s: %w", path, err) } if info.IsDir() { @@ -206,7 +207,7 @@ func (p *Project) Up(opts CommandOptions) error { args = append(args, opts.Services...) if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, env: opts.Env}); err != nil { - return errors.Wrap(err, "running Docker Compose up command failed") + return fmt.Errorf("running Docker Compose up command failed: %w", err) } return nil @@ -219,7 +220,7 @@ func (p *Project) Down(opts CommandOptions) error { args = append(args, opts.ExtraArgs...) if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, env: opts.Env}); err != nil { - return errors.Wrap(err, "running Docker Compose down command failed") + return fmt.Errorf("running Docker Compose down command failed: %w", err) } return nil @@ -233,7 +234,7 @@ func (p *Project) Build(opts CommandOptions) error { args = append(args, opts.Services...) if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, env: opts.Env}); err != nil { - return errors.Wrap(err, "running Docker Compose build command failed") + return fmt.Errorf("running Docker Compose build command failed: %w", err) } return nil @@ -247,7 +248,7 @@ func (p *Project) Kill(opts CommandOptions) error { args = append(args, opts.Services...) if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, env: opts.Env}); err != nil { - return errors.Wrap(err, "running Docker Compose kill command failed") + return fmt.Errorf("running Docker Compose kill command failed: %w", err) } return nil @@ -281,7 +282,7 @@ func (p *Project) Pull(opts CommandOptions) error { args = append(args, opts.Services...) if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, env: opts.Env}); err != nil { - return errors.Wrap(err, "running Docker Compose pull command failed") + return fmt.Errorf("running Docker Compose pull command failed: %w", err) } return nil @@ -418,12 +419,12 @@ func (p *Project) dockerComposeVersion() (*semver.Version, error) { "--short", } if err := p.runDockerComposeCmd(dockerComposeOptions{args: args, stdout: &b}); err != nil { - return nil, errors.Wrap(err, "running Docker Compose version command failed") + return nil, fmt.Errorf("running Docker Compose version command failed: %w", err) } dcVersion := b.String() ver, err := semver.NewVersion(strings.TrimSpace(dcVersion)) if err != nil { - return nil, errors.Wrapf(err, "docker compose version is not a valid semver (value: %s)", dcVersion) + return nil, fmt.Errorf("docker compose version is not a valid semver (value: %s): %w", dcVersion, err) } return ver, nil } diff --git a/internal/configuration/locations/locations.go b/internal/configuration/locations/locations.go index 5e36081f1..18888f7e6 100644 --- a/internal/configuration/locations/locations.go +++ b/internal/configuration/locations/locations.go @@ -6,11 +6,10 @@ package locations import ( + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/environment" ) @@ -44,7 +43,7 @@ type LocationManager struct { func NewLocationManager() (*LocationManager, error) { cfg, err := configurationDir() if err != nil { - return nil, errors.Wrap(err, "error getting config dir") + return nil, fmt.Errorf("error getting config dir: %w", err) } return &LocationManager{stackPath: cfg}, nil @@ -112,7 +111,7 @@ func configurationDir() (string, error) { homeDir, err := os.UserHomeDir() if err != nil { - return "", errors.Wrap(err, "reading home dir failed") + return "", fmt.Errorf("reading home dir failed: %w", err) } return filepath.Join(homeDir, elasticPackageDir), nil } diff --git a/internal/corpusgenerator/assets.go b/internal/corpusgenerator/assets.go index f8555d389..390175dac 100644 --- a/internal/corpusgenerator/assets.go +++ b/internal/corpusgenerator/assets.go @@ -12,7 +12,6 @@ import ( "github.com/elastic/elastic-integration-corpus-generator-tool/pkg/genlib" "github.com/elastic/elastic-integration-corpus-generator-tool/pkg/genlib/config" "github.com/elastic/elastic-integration-corpus-generator-tool/pkg/genlib/fields" - "github.com/pkg/errors" ) const ( @@ -26,7 +25,7 @@ func (c *Client) GetGoTextTemplate(packageName, dataStreamName string) ([]byte, assetsSubFolder := fmt.Sprintf("%s.%s", packageName, dataStreamName) statusCode, respBody, err := c.get(fmt.Sprintf("%s/%s", assetsSubFolder, gotextTemplateAssetName)) if err != nil { - return nil, errors.Wrap(err, "could not get gotext template") + return nil, fmt.Errorf("could not get gotext template: %w", err) } if statusCode != http.StatusOK { @@ -43,7 +42,7 @@ func (c *Client) GetConf(packageName, dataStreamName string) (genlib.Config, err statusCode, respBody, err := c.get(fmt.Sprintf("%s/%s", assetsSubFolder, confYamlAssetName)) if err != nil { - return genlib.Config{}, errors.Wrap(err, "could not get config yaml") + return genlib.Config{}, fmt.Errorf("could not get config yaml: %w", err) } if statusCode != http.StatusOK { @@ -52,7 +51,7 @@ func (c *Client) GetConf(packageName, dataStreamName string) (genlib.Config, err cfg, err := config.LoadConfigFromYaml(respBody) if err != nil { - return genlib.Config{}, errors.Wrap(err, "could not load config yaml") + return genlib.Config{}, fmt.Errorf("could not load config yaml: %w", err) } return cfg, nil @@ -64,7 +63,7 @@ func (c *Client) GetFields(packageName, dataStreamName string) (genlib.Fields, e statusCode, respBody, err := c.get(fmt.Sprintf("%s/%s", assetsSubFolder, fieldsYamlAssetName)) if err != nil { - return genlib.Fields{}, errors.Wrap(err, "could not get fields yaml") + return genlib.Fields{}, fmt.Errorf("could not get fields yaml: %w", err) } if statusCode != http.StatusOK { @@ -74,7 +73,7 @@ func (c *Client) GetFields(packageName, dataStreamName string) (genlib.Fields, e ctx := context.Background() fields, err := fields.LoadFieldsWithTemplateFromString(ctx, string(respBody)) if err != nil { - return genlib.Fields{}, errors.Wrap(err, "could not load fields yaml") + return genlib.Fields{}, fmt.Errorf("could not load fields yaml: %w", err) } return fields, nil diff --git a/internal/corpusgenerator/client.go b/internal/corpusgenerator/client.go index 2afe5e1c2..05dce6771 100644 --- a/internal/corpusgenerator/client.go +++ b/internal/corpusgenerator/client.go @@ -6,13 +6,13 @@ package corpusgenerator import ( "bytes" + "fmt" "io" "net/http" "net/url" "strings" "github.com/elastic/elastic-integration-corpus-generator-tool/pkg/genlib" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/logger" ) @@ -49,12 +49,12 @@ func (c *Client) sendRequest(method, resourcePath string, body []byte) (int, []b commitAssetsBaseURL := strings.Replace(integrationCorpusGeneratorAssetsBaseURL, commitPlaceholder, c.commit, -1) base, err := url.Parse(commitAssetsBaseURL) if err != nil { - return 0, nil, errors.Wrapf(err, "could not create base URL from commit: %v", c.commit) + return 0, nil, fmt.Errorf("could not create base URL from commit: %v: %w", c.commit, err) } rel, err := url.Parse(resourcePath) if err != nil { - return 0, nil, errors.Wrapf(err, "could not create relative URL from resource path: %v", resourcePath) + return 0, nil, fmt.Errorf("could not create relative URL from resource path: %v: %w", resourcePath, err) } u := base.JoinPath(rel.EscapedPath()) @@ -63,18 +63,18 @@ func (c *Client) sendRequest(method, resourcePath string, body []byte) (int, []b req, err := http.NewRequest(method, u.String(), reqBody) if err != nil { - return 0, nil, errors.Wrapf(err, "could not create %v request to elastic-integration-corpus-generator-tool repo: %s", method, resourcePath) + return 0, nil, fmt.Errorf("could not create %v request to elastic-integration-corpus-generator-tool repo: %s: %w", method, resourcePath, err) } client := http.Client{} resp, err := client.Do(req) if err != nil { - return 0, nil, errors.Wrap(err, "could not send request to elastic-integration-corpus-generator-tool repo") + return 0, nil, fmt.Errorf("could not send request to elastic-integration-corpus-generator-tool repo: %w", err) } if resp.Body == nil { - return 0, nil, errors.Wrap(err, "could not get response from elastic-integration-corpus-generator-tool repo") + return 0, nil, fmt.Errorf("could not get response from elastic-integration-corpus-generator-tool repo: %w", err) } defer func() { @@ -83,7 +83,7 @@ func (c *Client) sendRequest(method, resourcePath string, body []byte) (int, []b body, err = io.ReadAll(resp.Body) if err != nil { - return resp.StatusCode, nil, errors.Wrap(err, "could not read response body") + return resp.StatusCode, nil, fmt.Errorf("could not read response body: %w", err) } return resp.StatusCode, body, nil diff --git a/internal/docker/docker.go b/internal/docker/docker.go index 1bd6b8f0e..d8732fe25 100644 --- a/internal/docker/docker.go +++ b/internal/docker/docker.go @@ -13,8 +13,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/logger" ) @@ -67,7 +65,7 @@ func Pull(image string) error { logger.Debugf("run command: %s", cmd) err := cmd.Run() if err != nil { - return errors.Wrap(err, "running docker command failed") + return fmt.Errorf("running docker command failed: %w", err) } return nil } @@ -81,7 +79,7 @@ func ContainerID(containerName string) (string, error) { logger.Debugf("output command: %s", cmd) output, err := cmd.Output() if err != nil { - return "", errors.Wrapf(err, "could not find \"%s\" container (stderr=%q)", containerName, errOutput.String()) + return "", fmt.Errorf("could not find \"%s\" container (stderr=%q): %w", containerName, errOutput.String(), err) } containerIDs := strings.Fields(string(output)) if len(containerIDs) != 1 { @@ -100,7 +98,7 @@ func ContainerIDsWithLabel(key, value string) ([]string, error) { logger.Debugf("output command: %s", cmd) output, err := cmd.Output() if err != nil { - return []string{}, errors.Wrapf(err, "error getting containers with label \"%s\" (stderr=%q)", label, errOutput.String()) + return []string{}, fmt.Errorf("error getting containers with label \"%s\" (stderr=%q): %w", label, errOutput.String(), err) } containerIDs := strings.Fields(string(output)) return containerIDs, nil @@ -115,13 +113,13 @@ func InspectNetwork(network string) ([]NetworkDescription, error) { logger.Debugf("output command: %s", cmd) output, err := cmd.Output() if err != nil { - return nil, errors.Wrapf(err, "could not inspect the network (stderr=%q)", errOutput.String()) + return nil, fmt.Errorf("could not inspect the network (stderr=%q): %w", errOutput.String(), err) } var networkDescriptions []NetworkDescription err = json.Unmarshal(output, &networkDescriptions) if err != nil { - return nil, errors.Wrapf(err, "can't unmarshal network inspect for %s (stderr=%q)", network, errOutput.String()) + return nil, fmt.Errorf("can't unmarshal network inspect for %s (stderr=%q): %w", network, errOutput.String(), err) } return networkDescriptions, nil } @@ -134,7 +132,7 @@ func ConnectToNetwork(containerID, network string) error { logger.Debugf("run command: %s", cmd) if err := cmd.Run(); err != nil { - return errors.Wrapf(err, "could not attach container to the stack network (stderr=%q)", errOutput.String()) + return fmt.Errorf("could not attach container to the stack network (stderr=%q): %w", errOutput.String(), err) } return nil } @@ -151,13 +149,13 @@ func InspectContainers(containerIDs ...string) ([]ContainerDescription, error) { logger.Debugf("output command: %s", cmd) output, err := cmd.Output() if err != nil { - return nil, errors.Wrapf(err, "could not inspect containers (stderr=%q)", errOutput.String()) + return nil, fmt.Errorf("could not inspect containers (stderr=%q): %w", errOutput.String(), err) } var containerDescriptions []ContainerDescription err = json.Unmarshal(output, &containerDescriptions) if err != nil { - return nil, errors.Wrapf(err, "can't unmarshal container inspect for %s (stderr=%q)", strings.Join(containerIDs, ","), errOutput.String()) + return nil, fmt.Errorf("can't unmarshal container inspect for %s (stderr=%q): %w", strings.Join(containerIDs, ","), errOutput.String(), err) } return containerDescriptions, nil } @@ -170,7 +168,7 @@ func Copy(containerName, containerPath, localPath string) error { logger.Debugf("run command: %s", cmd) if err := cmd.Run(); err != nil { - return errors.Wrapf(err, "could not copy files from the container (stderr=%q)", errOutput.String()) + return fmt.Errorf("could not copy files from the container (stderr=%q): %w", errOutput.String(), err) } return nil } diff --git a/internal/docs/exported_fields.go b/internal/docs/exported_fields.go index 585a0f693..ad9cc9440 100644 --- a/internal/docs/exported_fields.go +++ b/internal/docs/exported_fields.go @@ -9,8 +9,6 @@ import ( "sort" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/fields" ) @@ -27,12 +25,12 @@ var escaper = strings.NewReplacer("*", "\\*", "{", "\\{", "}", "\\}", "<", "\\<" func renderExportedFields(fieldsParentDir string) (string, error) { validator, err := fields.CreateValidatorForDirectory(fieldsParentDir) if err != nil { - return "", errors.Wrapf(err, "can't create fields validator instance (path: %s)", fieldsParentDir) + return "", fmt.Errorf("can't create fields validator instance (path: %s): %w", fieldsParentDir, err) } collected, err := collectFieldsFromDefinitions(validator) if err != nil { - return "", errors.Wrap(err, "collecting fields files failed") + return "", fmt.Errorf("collecting fields files failed: %w", err) } var builder strings.Builder @@ -110,7 +108,7 @@ func collectFieldsFromDefinitions(validator *fields.Validator) ([]fieldsTableRec for _, f := range root { records, err = visitFields("", f, records, validator.FieldDependencyManager) if err != nil { - return nil, errors.Wrapf(err, "visiting fields failed") + return nil, fmt.Errorf("visiting fields failed: %w", err) } } return uniqueTableRecords(records), nil @@ -127,7 +125,7 @@ func visitFields(namePrefix string, f fields.FieldDefinition, records []fieldsTa if f.External != "" { imported, err := fdm.ImportField(f.External, name) if err != nil { - return nil, errors.Wrap(err, "can't import field") + return nil, fmt.Errorf("can't import field: %w", err) } // Override imported fields with the definition, except for the type and external. @@ -160,7 +158,7 @@ func visitFields(namePrefix string, f fields.FieldDefinition, records []fieldsTa for _, fieldEntry := range f.Fields { records, err = visitFields(name, fieldEntry, records, fdm) if err != nil { - return nil, errors.Wrapf(err, "recursive visiting fields failed (namePrefix: %s)", namePrefix) + return nil, fmt.Errorf("recursive visiting fields failed (namePrefix: %s): %w", namePrefix, err) } } return records, nil diff --git a/internal/docs/links_map.go b/internal/docs/links_map.go index cefaad82c..d024bf690 100644 --- a/internal/docs/links_map.go +++ b/internal/docs/links_map.go @@ -9,7 +9,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/environment" @@ -39,12 +38,12 @@ func (l linkMap) Get(key string) (string, error) { if url, ok := l.Links[key]; ok { return url, nil } - return "", errors.Errorf("link key not found: %s", key) + return "", fmt.Errorf("link key not found: %s", key) } func (l linkMap) Add(key, value string) error { if _, ok := l.Links[key]; ok { - return errors.Errorf("link key already present: %s", key) + return fmt.Errorf("link key already present: %s", key) } l.Links[key] = value return nil @@ -53,7 +52,7 @@ func (l linkMap) Add(key, value string) error { func readLinksMap() (linkMap, error) { linksFilePath, err := linksDefinitionsFilePath() if err != nil { - return linkMap{}, errors.Wrap(err, "locating links file failed") + return linkMap{}, fmt.Errorf("locating links file failed: %w", err) } links := newLinkMap() @@ -64,7 +63,7 @@ func readLinksMap() (linkMap, error) { logger.Debugf("Using links definitions file: %s", linksFilePath) contents, err := os.ReadFile(linksFilePath) if err != nil { - return linkMap{}, errors.Wrapf(err, "readfile failed (path: %s)", linksFilePath) + return linkMap{}, fmt.Errorf("readfile failed (path: %s): %w", linksFilePath, err) } err = yaml.Unmarshal(contents, &links) diff --git a/internal/docs/readme.go b/internal/docs/readme.go index 97e6303e5..3b60a7197 100644 --- a/internal/docs/readme.go +++ b/internal/docs/readme.go @@ -6,12 +6,12 @@ package docs import ( "bytes" + "errors" "fmt" "os" "path/filepath" "text/template" - "github.com/pkg/errors" "github.com/pmezard/go-difflib/difflib" "github.com/elastic/elastic-package/internal/builder" @@ -31,12 +31,12 @@ type ReadmeFile struct { func AreReadmesUpToDate() ([]ReadmeFile, error) { packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return nil, errors.Wrap(err, "package root not found") + return nil, fmt.Errorf("package root not found: %w", err) } files, err := filepath.Glob(filepath.Join(packageRoot, "_dev", "build", "docs", "*.md")) if err != nil && !errors.Is(err, os.ErrNotExist) { - return nil, errors.Wrap(err, "reading directory entries failed") + return nil, fmt.Errorf("reading directory entries failed: %w", err) } var readmeFiles []ReadmeFile @@ -65,7 +65,7 @@ func isReadmeUpToDate(fileName, packageRoot string) (bool, string, error) { rendered, shouldBeRendered, err := generateReadme(fileName, packageRoot) if err != nil { - return false, "", errors.Wrap(err, "generating readme file failed") + return false, "", fmt.Errorf("generating readme file failed: %w", err) } if !shouldBeRendered { return true, "", nil // README file is static and doesn't use template. @@ -73,7 +73,7 @@ func isReadmeUpToDate(fileName, packageRoot string) (bool, string, error) { existing, found, err := readReadme(fileName, packageRoot) if err != nil { - return false, "", errors.Wrap(err, "reading README file failed") + return false, "", fmt.Errorf("reading README file failed: %w", err) } if !found { return false, "", nil @@ -97,7 +97,7 @@ func isReadmeUpToDate(fileName, packageRoot string) (bool, string, error) { func UpdateReadmes(packageRoot string) ([]string, error) { readmeFiles, err := filepath.Glob(filepath.Join(packageRoot, "_dev", "build", "docs", "*.md")) if err != nil { - return nil, errors.Wrap(err, "reading directory entries failed") + return nil, fmt.Errorf("reading directory entries failed: %w", err) } var targets []string @@ -105,7 +105,7 @@ func UpdateReadmes(packageRoot string) ([]string, error) { fileName := filepath.Base(filePath) target, err := updateReadme(fileName, packageRoot) if err != nil { - return nil, errors.Wrapf(err, "updating readme file %s failed", fileName) + return nil, fmt.Errorf("updating readme file %s failed: %w", fileName, err) } if target != "" { @@ -128,17 +128,17 @@ func updateReadme(fileName, packageRoot string) (string, error) { target, err := writeReadme(fileName, packageRoot, rendered) if err != nil { - return "", errors.Wrapf(err, "writing %s file failed", fileName) + return "", fmt.Errorf("writing %s file failed: %w", fileName, err) } packageBuildRoot, err := builder.BuildPackagesDirectory(packageRoot) if err != nil { - return "", errors.Wrap(err, "package build root not found") + return "", fmt.Errorf("package build root not found: %w", err) } _, err = writeReadme(fileName, packageBuildRoot, rendered) if err != nil { - return "", errors.Wrapf(err, "writing %s file failed", fileName) + return "", fmt.Errorf("writing %s file failed: %w", fileName, err) } return target, nil } @@ -147,7 +147,7 @@ func generateReadme(fileName, packageRoot string) ([]byte, bool, error) { logger.Debugf("Generate %s file (package: %s)", fileName, packageRoot) templatePath, found, err := findReadmeTemplatePath(fileName, packageRoot) if err != nil { - return nil, false, errors.Wrapf(err, "can't locate %s template file", fileName) + return nil, false, fmt.Errorf("can't locate %s template file: %w", fileName, err) } if !found { logger.Debug("README file is static, can't be generated from the template file") @@ -162,7 +162,7 @@ func generateReadme(fileName, packageRoot string) ([]byte, bool, error) { rendered, err := renderReadme(fileName, packageRoot, templatePath, linksMap) if err != nil { - return nil, true, errors.Wrap(err, "rendering Readme failed") + return nil, true, fmt.Errorf("rendering Readme failed: %w", err) } return rendered, true, nil } @@ -174,7 +174,7 @@ func findReadmeTemplatePath(fileName, packageRoot string) (string, bool, error) return "", false, nil // README.md file not found } if err != nil { - return "", false, errors.Wrapf(err, "can't stat the %s file", fileName) + return "", false, fmt.Errorf("can't stat the %s file: %w", fileName, err) } return templatePath, true, nil } @@ -203,13 +203,13 @@ func renderReadme(fileName, packageRoot, templatePath string, linksMap linkMap) }, }).ParseFiles(templatePath) if err != nil { - return nil, errors.Wrapf(err, "parsing README template failed (path: %s)", templatePath) + return nil, fmt.Errorf("parsing README template failed (path: %s): %w", templatePath, err) } var rendered bytes.Buffer err = t.Execute(&rendered, nil) if err != nil { - return nil, errors.Wrap(err, "executing template failed") + return nil, fmt.Errorf("executing template failed: %w", err) } return rendered.Bytes(), nil } @@ -223,7 +223,7 @@ func readReadme(fileName, packageRoot string) ([]byte, bool, error) { return nil, false, nil } if err != nil { - return nil, false, errors.Wrapf(err, "readfile failed (path: %s)", readmePath) + return nil, false, fmt.Errorf("readfile failed (path: %s): %w", readmePath, err) } return b, true, err } @@ -235,7 +235,7 @@ func writeReadme(fileName, packageRoot string, content []byte) (string, error) { logger.Debugf("Create directories: %s", docsPath) err := os.MkdirAll(docsPath, 0o755) if err != nil { - return "", errors.Wrapf(err, "mkdir failed (path: %s)", docsPath) + return "", fmt.Errorf("mkdir failed (path: %s): %w", docsPath, err) } aReadmePath := readmePath(fileName, packageRoot) @@ -243,7 +243,7 @@ func writeReadme(fileName, packageRoot string, content []byte) (string, error) { err = os.WriteFile(aReadmePath, content, 0o644) if err != nil { - return "", errors.Wrapf(err, "writing file failed (path: %s)", aReadmePath) + return "", fmt.Errorf("writing file failed (path: %s): %w", aReadmePath, err) } return aReadmePath, nil } diff --git a/internal/docs/sample_event.go b/internal/docs/sample_event.go index 91d5e5969..60305e532 100644 --- a/internal/docs/sample_event.go +++ b/internal/docs/sample_event.go @@ -11,8 +11,6 @@ import ( "strings" "github.com/elastic/elastic-package/internal/formatter" - - "github.com/pkg/errors" ) const sampleEventFile = "sample_event.json" @@ -22,12 +20,12 @@ func renderSampleEvent(packageRoot, dataStreamName string) (string, error) { body, err := os.ReadFile(eventPath) if err != nil { - return "", errors.Wrapf(err, "reading sample event file failed (path: %s)", eventPath) + return "", fmt.Errorf("reading sample event file failed (path: %s): %w", eventPath, err) } formatted, _, err := formatter.JSONFormatter(body) if err != nil { - return "", errors.Wrapf(err, "formatting sample event file failed (path: %s)", eventPath) + return "", fmt.Errorf("formatting sample event file failed (path: %s): %w", eventPath, err) } var builder strings.Builder diff --git a/internal/elasticsearch/client.go b/internal/elasticsearch/client.go index ef8b8ee28..4b6a8ae07 100644 --- a/internal/elasticsearch/client.go +++ b/internal/elasticsearch/client.go @@ -8,14 +8,13 @@ import ( "context" "crypto/tls" "encoding/json" + "errors" "fmt" "io" "net/http" "os" "strings" - "github.com/pkg/errors" - "github.com/elastic/go-elasticsearch/v7" "github.com/elastic/go-elasticsearch/v7/esapi" @@ -118,7 +117,7 @@ func NewClient(customOptions ...ClientOption) (*Client, error) { client, err := elasticsearch.NewClient(config) if err != nil { - return nil, errors.Wrap(err, "can't create instance") + return nil, fmt.Errorf("can't create instance: %w", err) } return &Client{Client: client}, nil } @@ -127,13 +126,13 @@ func NewClient(customOptions ...ClientOption) (*Client, error) { func (client *Client) CheckHealth(ctx context.Context) error { resp, err := client.Cluster.Health(client.Cluster.Health.WithContext(ctx)) if err != nil { - return errors.Wrap(err, "error checking cluster health") + return fmt.Errorf("error checking cluster health: %w", err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - return errors.Wrap(err, "error reading cluster health response") + return fmt.Errorf("error reading cluster health response: %w", err) } var clusterHealth struct { @@ -141,18 +140,18 @@ func (client *Client) CheckHealth(ctx context.Context) error { } err = json.Unmarshal(body, &clusterHealth) if err != nil { - return errors.Wrap(err, "error decoding cluster health response") + return fmt.Errorf("error decoding cluster health response: %w", err) } if status := clusterHealth.Status; status != "green" && status != "yellow" { if status != "red" { - return errors.Errorf("cluster in unhealthy state: %q", status) + return fmt.Errorf("cluster in unhealthy state: %q", status) } cause, err := client.redHealthCause(ctx) if err != nil { - return errors.Wrapf(err, "cluster in unhealthy state, failed to identify cause") + return fmt.Errorf("cluster in unhealthy state, failed to identify cause: %w", err) } - return errors.Errorf("cluster in unhealthy state: %s", cause) + return fmt.Errorf("cluster in unhealthy state: %s", cause) } return nil @@ -164,17 +163,17 @@ func (client *Client) CheckHealth(ctx context.Context) error { func (client *Client) redHealthCause(ctx context.Context) (string, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "/_internal/_health", nil) if err != nil { - return "", errors.Wrap(err, "error creating internal health request") + return "", fmt.Errorf("error creating internal health request: %w", err) } resp, err := client.Transport.Perform(req) if err != nil { - return "", errors.Wrap(err, "error performing internal health request") + return "", fmt.Errorf("error performing internal health request: %w", err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - return "", errors.Wrap(err, "error reading internal health response") + return "", fmt.Errorf("error reading internal health response: %w", err) } var internalHealth struct { @@ -191,7 +190,7 @@ func (client *Client) redHealthCause(ctx context.Context) (string, error) { } err = json.Unmarshal(body, &internalHealth) if err != nil { - return "", errors.Wrap(err, "error decoding internal health response") + return "", fmt.Errorf("error decoding internal health response: %w", err) } if internalHealth.Status != "red" { return "", errors.New("cluster state is not red?") diff --git a/internal/export/dashboards.go b/internal/export/dashboards.go index 500f6dec5..a8c5ac1e3 100644 --- a/internal/export/dashboards.go +++ b/internal/export/dashboards.go @@ -6,11 +6,10 @@ package export import ( "encoding/json" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/common" "github.com/elastic/elastic-package/internal/kibana" "github.com/elastic/elastic-package/internal/logger" @@ -22,18 +21,18 @@ import ( func Dashboards(kibanaClient *kibana.Client, dashboardsIDs []string) error { packageRoot, err := packages.MustFindPackageRoot() if err != nil { - return errors.Wrap(err, "locating package root failed") + return fmt.Errorf("locating package root failed: %w", err) } logger.Debugf("Package root found: %s", packageRoot) m, err := packages.ReadPackageManifestFromPackageRoot(packageRoot) if err != nil { - return errors.Wrapf(err, "reading package manifest failed (path: %s)", packageRoot) + return fmt.Errorf("reading package manifest failed (path: %s): %w", packageRoot, err) } objects, err := kibanaClient.Export(dashboardsIDs) if err != nil { - return errors.Wrap(err, "exporting dashboards using Kibana client failed") + return fmt.Errorf("exporting dashboards using Kibana client failed: %w", err) } ctx := &transformationContext{ @@ -42,12 +41,12 @@ func Dashboards(kibanaClient *kibana.Client, dashboardsIDs []string) error { objects, err = applyTransformations(ctx, objects) if err != nil { - return errors.Wrap(err, "can't transform Kibana objects") + return fmt.Errorf("can't transform Kibana objects: %w", err) } err = saveObjectsToFiles(packageRoot, objects) if err != nil { - return errors.Wrap(err, "can't save Kibana objects") + return fmt.Errorf("can't save Kibana objects: %w", err) } return nil } @@ -74,21 +73,21 @@ func saveObjectsToFiles(packageRoot string, objects []common.MapStr) error { // Marshal object to byte content b, err := json.MarshalIndent(&object, "", " ") if err != nil { - return errors.Wrapf(err, "marshalling Kibana object failed (ID: %s)", id.(string)) + return fmt.Errorf("marshalling Kibana object failed (ID: %s): %w", id.(string), err) } // Create target directory targetDir := filepath.Join(packageRoot, "kibana", aType.(string)) err = os.MkdirAll(targetDir, 0755) if err != nil { - return errors.Wrapf(err, "creating target directory failed (path: %s)", targetDir) + return fmt.Errorf("creating target directory failed (path: %s): %w", targetDir, err) } // Save object to file objectPath := filepath.Join(targetDir, id.(string)+".json") err = os.WriteFile(objectPath, b, 0644) if err != nil { - return errors.Wrap(err, "writing to file failed") + return fmt.Errorf("writing to file failed: %w", err) } } return nil diff --git a/internal/export/object_transformer.go b/internal/export/object_transformer.go index c19813424..cb333d6fd 100644 --- a/internal/export/object_transformer.go +++ b/internal/export/object_transformer.go @@ -5,7 +5,7 @@ package export import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/elastic-package/internal/common" ) @@ -36,7 +36,7 @@ func (ot *objectTransformer) transform(objects []common.MapStr) ([]common.MapStr object, err = fn(ot.ctx, object) if err != nil { id, _ := object.GetValue("id") - return nil, errors.Wrapf(err, "object transformation failed (ID: %s)", id) + return nil, fmt.Errorf("object transformation failed (ID: %s): %w", id, err) } } diff --git a/internal/export/transform_decode.go b/internal/export/transform_decode.go index 50fcd7c87..be6646677 100644 --- a/internal/export/transform_decode.go +++ b/internal/export/transform_decode.go @@ -6,8 +6,7 @@ package export import ( "encoding/json" - - "github.com/pkg/errors" + "fmt" "github.com/elastic/elastic-package/internal/common" ) @@ -30,7 +29,7 @@ func decodeObject(ctx *transformationContext, object common.MapStr) (common.MapS if err == common.ErrKeyNotFound { continue } else if err != nil { - return nil, errors.Wrapf(err, "retrieving value failed (key: %s)", fieldToDecode) + return nil, fmt.Errorf("retrieving value failed (key: %s): %w", fieldToDecode, err) } var target interface{} @@ -43,13 +42,13 @@ func decodeObject(ctx *transformationContext, object common.MapStr) (common.MapS } else { err = json.Unmarshal([]byte(v.(string)), &array) if err != nil { - return nil, errors.Wrapf(err, "can't unmarshal encoded field (key: %s)", fieldToDecode) + return nil, fmt.Errorf("can't unmarshal encoded field (key: %s): %w", fieldToDecode, err) } target = array } _, err = object.Put(fieldToDecode, target) if err != nil { - return nil, errors.Wrapf(err, "can't update field (key: %s)", fieldToDecode) + return nil, fmt.Errorf("can't update field (key: %s): %w", fieldToDecode, err) } } return object, nil diff --git a/internal/export/transform_standardize.go b/internal/export/transform_standardize.go index 713735700..a3a4ad293 100644 --- a/internal/export/transform_standardize.go +++ b/internal/export/transform_standardize.go @@ -5,11 +5,10 @@ package export import ( + "fmt" "regexp" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/common" ) @@ -20,23 +19,23 @@ func standardizeObjectID(ctx *transformationContext, object common.MapStr) (comm id, _ := object.GetValue("id") _, err := object.Put("id", adjustObjectID(ctx, id.(string))) if err != nil { - return nil, errors.Wrapf(err, "can't update object ID") + return nil, fmt.Errorf("can't update object ID: %w", err) } // Adjust references references, err := object.GetValue("references") if err != nil && err != common.ErrKeyNotFound { - return nil, errors.Wrap(err, "retrieving object references failed") + return nil, fmt.Errorf("retrieving object references failed: %w", err) } newReferences, err := adjustObjectReferences(ctx, references.([]interface{})) if err != nil { - return nil, errors.Wrapf(err, "can't adjust object references (ID: %s)", id) + return nil, fmt.Errorf("can't adjust object references (ID: %s): %w", id, err) } _, err = object.Put("references", newReferences) if err != nil { - return nil, errors.Wrapf(err, "can't update references") + return nil, fmt.Errorf("can't update references: %w", err) } return object, nil } @@ -62,7 +61,7 @@ func standardizeObjectProperties(ctx *transformationContext, object common.MapSt if key == "title" { _, err := object.Put(key, adjustTitleProperty(value.(string))) if err != nil { - return nil, errors.Wrapf(err, "can't update field (key: %s)", key) + return nil, fmt.Errorf("can't update field (key: %s): %w", key, err) } continue } @@ -70,7 +69,7 @@ func standardizeObjectProperties(ctx *transformationContext, object common.MapSt if key == "markdown" { _, err := object.Put(key, adjustMarkdownProperty(ctx, value.(string))) if err != nil { - return nil, errors.Wrapf(err, "can't update field (key: %s)", key) + return nil, fmt.Errorf("can't update field (key: %s): %w", key, err) } continue } @@ -83,7 +82,7 @@ func standardizeObjectProperties(ctx *transformationContext, object common.MapSt case map[string]interface{}: target, err = standardizeObjectProperties(ctx, value) if err != nil { - return nil, errors.Wrapf(err, "can't standardize object (key: %s)", key) + return nil, fmt.Errorf("can't standardize object (key: %s): %w", key, err) } updated = true case []map[string]interface{}: @@ -91,7 +90,7 @@ func standardizeObjectProperties(ctx *transformationContext, object common.MapSt for i, obj := range arr { newValue, err := standardizeObjectProperties(ctx, obj) if err != nil { - return nil, errors.Wrapf(err, "can't standardize object (array index: %d)", i) + return nil, fmt.Errorf("can't standardize object (array index: %d): %w", i, err) } arr[i] = newValue } @@ -105,7 +104,7 @@ func standardizeObjectProperties(ctx *transformationContext, object common.MapSt _, err = object.Put(key, target) if err != nil { - return nil, errors.Wrapf(err, "can't update field (key: %s)", key) + return nil, fmt.Errorf("can't update field (key: %s): %w", key, err) } } return object, nil diff --git a/internal/export/transform_strip.go b/internal/export/transform_strip.go index 610dcd14f..5acc1656c 100644 --- a/internal/export/transform_strip.go +++ b/internal/export/transform_strip.go @@ -5,7 +5,7 @@ package export import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/elastic-package/internal/common" ) @@ -13,17 +13,17 @@ import ( func stripObjectProperties(ctx *transformationContext, object common.MapStr) (common.MapStr, error) { err := object.Delete("namespaces") if err != nil && err != common.ErrKeyNotFound { - return nil, errors.Wrapf(err, "removing field \"namespaces\" failed") + return nil, fmt.Errorf("removing field \"namespaces\" failed: %w", err) } err = object.Delete("updated_at") if err != nil && err != common.ErrKeyNotFound { - return nil, errors.Wrapf(err, "removing field \"updated_at\" failed") + return nil, fmt.Errorf("removing field \"updated_at\" failed: %w", err) } err = object.Delete("version") if err != nil && err != common.ErrKeyNotFound { - return nil, errors.Wrapf(err, "removing field \"version\" failed") + return nil, fmt.Errorf("removing field \"version\" failed: %w", err) } return object, nil } diff --git a/internal/fields/dependency_manager.go b/internal/fields/dependency_manager.go index d9abc1245..82e80ad64 100644 --- a/internal/fields/dependency_manager.go +++ b/internal/fields/dependency_manager.go @@ -5,6 +5,7 @@ package fields import ( + "errors" "fmt" "io" "net/http" @@ -12,7 +13,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/common" @@ -38,7 +38,7 @@ type DependencyManager struct { func CreateFieldDependencyManager(deps buildmanifest.Dependencies) (*DependencyManager, error) { schema, err := buildFieldsSchema(deps) if err != nil { - return nil, errors.Wrap(err, "can't build fields schema") + return nil, fmt.Errorf("can't build fields schema: %w", err) } return &DependencyManager{ schema: schema, @@ -49,7 +49,7 @@ func buildFieldsSchema(deps buildmanifest.Dependencies) (map[string][]FieldDefin schema := map[string][]FieldDefinition{} ecsSchema, err := loadECSFieldsSchema(deps.ECS) if err != nil { - return nil, errors.Wrap(err, "can't load fields") + return nil, fmt.Errorf("can't load fields: %w", err) } schema[ecsSchemaName] = ecsSchema return schema, nil @@ -63,7 +63,7 @@ func loadECSFieldsSchema(dep buildmanifest.ECSDependency) ([]FieldDefinition, er content, err := readECSFieldsSchemaFile(dep) if err != nil { - return nil, errors.Wrap(err, "error reading ECS fields schema file") + return nil, fmt.Errorf("error reading ECS fields schema file: %w", err) } return parseECSFieldsSchema(content) @@ -72,12 +72,12 @@ func loadECSFieldsSchema(dep buildmanifest.ECSDependency) ([]FieldDefinition, er func readECSFieldsSchemaFile(dep buildmanifest.ECSDependency) ([]byte, error) { gitReference, err := asGitReference(dep.Reference) if err != nil { - return nil, errors.Wrap(err, "can't process the value as Git reference") + return nil, fmt.Errorf("can't process the value as Git reference: %w", err) } loc, err := locations.NewLocationManager() if err != nil { - return nil, errors.Wrap(err, "error fetching profile path") + return nil, fmt.Errorf("error fetching profile path: %w", err) } cachedSchemaPath := filepath.Join(loc.FieldsCacheDir(), ecsSchemaName, gitReference, ecsSchemaFile) content, err := os.ReadFile(cachedSchemaPath) @@ -88,7 +88,7 @@ func readECSFieldsSchemaFile(dep buildmanifest.ECSDependency) ([]byte, error) { logger.Debugf("Schema URL: %s", url) resp, err := http.Get(url) if err != nil { - return nil, errors.Wrapf(err, "can't download the online schema (URL: %s)", url) + return nil, fmt.Errorf("can't download the online schema (URL: %s): %w", url, err) } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { @@ -99,23 +99,23 @@ func readECSFieldsSchemaFile(dep buildmanifest.ECSDependency) ([]byte, error) { content, err = io.ReadAll(resp.Body) if err != nil { - return nil, errors.Wrapf(err, "can't read schema content (URL: %s)", url) + return nil, fmt.Errorf("can't read schema content (URL: %s): %w", url, err) } logger.Debugf("Downloaded %d bytes", len(content)) cachedSchemaDir := filepath.Dir(cachedSchemaPath) err = os.MkdirAll(cachedSchemaDir, 0755) if err != nil { - return nil, errors.Wrapf(err, "can't create cache directories for schema (path: %s)", cachedSchemaDir) + return nil, fmt.Errorf("can't create cache directories for schema (path: %s): %w", cachedSchemaDir, err) } logger.Debugf("Cache downloaded schema: %s", cachedSchemaPath) err = os.WriteFile(cachedSchemaPath, content, 0644) if err != nil { - return nil, errors.Wrapf(err, "can't write cached schema (path: %s)", cachedSchemaPath) + return nil, fmt.Errorf("can't write cached schema (path: %s): %w", cachedSchemaPath, err) } } else if err != nil { - return nil, errors.Wrapf(err, "can't read cached schema (path: %s)", cachedSchemaPath) + return nil, fmt.Errorf("can't read cached schema (path: %s): %w", cachedSchemaPath, err) } return content, nil @@ -125,7 +125,7 @@ func parseECSFieldsSchema(content []byte) ([]FieldDefinition, error) { var fields FieldDefinitions err := yaml.Unmarshal(content, &fields) if err != nil { - return nil, errors.Wrap(err, "unmarshalling field body failed") + return nil, fmt.Errorf("unmarshalling field body failed: %w", err) } return fields, nil @@ -153,7 +153,7 @@ func (dm *DependencyManager) injectFieldsWithRoot(root string, defs []common.Map if external != nil { imported, err := dm.ImportField(external.(string), fieldPath) if err != nil { - return nil, false, errors.Wrap(err, "can't import field") + return nil, false, fmt.Errorf("can't import field: %w", err) } transformed := transformImportedField(imported) @@ -175,7 +175,7 @@ func (dm *DependencyManager) injectFieldsWithRoot(root string, defs []common.Map if fields != nil { fieldsMs, err := common.ToMapStrSlice(fields) if err != nil { - return nil, false, errors.Wrap(err, "can't convert fields") + return nil, false, fmt.Errorf("can't convert fields: %w", err) } updatedFields, fieldsChanged, err := dm.injectFieldsWithRoot(fieldPath, fieldsMs) if err != nil { diff --git a/internal/files/clear.go b/internal/files/clear.go index feaf781b4..10e397b7f 100644 --- a/internal/files/clear.go +++ b/internal/files/clear.go @@ -5,9 +5,8 @@ package files import ( + "fmt" "os" - - "github.com/pkg/errors" ) // ClearDir method removes all items from the destination directory. @@ -15,12 +14,12 @@ import ( func ClearDir(destinationPath string) error { err := os.RemoveAll(destinationPath) if err != nil { - return errors.Wrapf(err, "removing directory failed (path: %s)", destinationPath) + return fmt.Errorf("removing directory failed (path: %s): %w", destinationPath, err) } err = os.MkdirAll(destinationPath, 0755) if err != nil { - return errors.Wrapf(err, "creating directory failed (path: %s)", destinationPath) + return fmt.Errorf("creating directory failed (path: %s): %w", destinationPath, err) } return nil } diff --git a/internal/files/compress.go b/internal/files/compress.go index 0ce701975..5e2651b03 100644 --- a/internal/files/compress.go +++ b/internal/files/compress.go @@ -6,6 +6,7 @@ package files import ( "compress/flate" + "fmt" "os" "path/filepath" "strings" @@ -13,7 +14,6 @@ import ( "github.com/elastic/elastic-package/internal/logger" "github.com/mholt/archiver/v3" - "github.com/pkg/errors" ) // Zip function creates the .zip archive from the source path (built package content). @@ -32,24 +32,24 @@ func Zip(sourcePath, destinationFile string) error { // Create a temporary work directory to properly name the root directory in the archive, e.g. aws-1.0.1 tempDir, err := os.MkdirTemp("", "elastic-package-") if err != nil { - return errors.Wrap(err, "can't prepare a temporary directory") + return fmt.Errorf("can't prepare a temporary directory: %w", err) } defer os.RemoveAll(tempDir) workDir := filepath.Join(tempDir, folderNameFromFileName(destinationFile)) err = os.MkdirAll(workDir, 0755) if err != nil { - return errors.Wrapf(err, "can't prepare work directory: %s", workDir) + return fmt.Errorf("can't prepare work directory: %s: %w", workDir, err) } logger.Debugf("Create work directory for archiving: %s", workDir) err = CopyAll(sourcePath, workDir) if err != nil { - return errors.Wrapf(err, "can't create a work directory (path: %s)", workDir) + return fmt.Errorf("can't create a work directory (path: %s): %w", workDir, err) } err = z.Archive([]string{workDir}, destinationFile) if err != nil { - return errors.Wrapf(err, "can't archive source directory (source path: %s)", sourcePath) + return fmt.Errorf("can't archive source directory (source path: %s): %w", sourcePath, err) } return nil } diff --git a/internal/files/remove.go b/internal/files/remove.go index 153050a13..3746e087e 100644 --- a/internal/files/remove.go +++ b/internal/files/remove.go @@ -5,24 +5,23 @@ package files import ( + "fmt" "os" "path/filepath" - - "github.com/pkg/errors" ) // RemoveContent method wipes out the directory content. func RemoveContent(dir string) error { fis, err := os.ReadDir(dir) if err != nil { - return errors.Wrapf(err, "readdir failed (path: %s)", dir) + return fmt.Errorf("readdir failed (path: %s): %w", dir, err) } for _, fi := range fis { p := filepath.Join(dir, fi.Name()) err = os.RemoveAll(p) if err != nil { - return errors.Wrapf(err, "removing resource failed (path: %s)", p) + return fmt.Errorf("removing resource failed (path: %s): %w", p, err) } } return nil diff --git a/internal/files/sign.go b/internal/files/sign.go index 6ae1324cb..b4a009947 100644 --- a/internal/files/sign.go +++ b/internal/files/sign.go @@ -11,7 +11,6 @@ import ( "github.com/ProtonMail/gopenpgp/v2/armor" "github.com/ProtonMail/gopenpgp/v2/constants" "github.com/ProtonMail/gopenpgp/v2/crypto" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/environment" "github.com/elastic/elastic-package/internal/logger" @@ -38,7 +37,7 @@ func VerifySignerConfiguration() error { _, err := os.Stat(signerPrivateKeyfile) if err != nil { - return errors.Wrap(err, "can't access the signer private keyfile") + return fmt.Errorf("can't access the signer private keyfile: %w", err) } signerPassphrase := os.Getenv(signerPassphraseEnv) @@ -55,7 +54,7 @@ func Sign(targetFile string, options SignOptions) error { logger.Debugf("Read signer private keyfile: %s", signerPrivateKeyfile) signerPrivateKey, err := os.ReadFile(signerPrivateKeyfile) if err != nil { - return errors.Wrapf(err, "can't read the signer private keyfile (path: %s)", signerPrivateKeyfile) + return fmt.Errorf("can't read the signer private keyfile (path: %s): %w", signerPrivateKeyfile, err) } signerPassphrase := []byte(os.Getenv(signerPassphraseEnv)) @@ -63,42 +62,42 @@ func Sign(targetFile string, options SignOptions) error { logger.Debug("Start the signing routine") signingKey, err := crypto.NewKeyFromArmored(string(signerPrivateKey)) if err != nil { - return errors.Wrap(err, "crypto.NewKeyFromArmored failed") + return fmt.Errorf("crypto.NewKeyFromArmored failed: %w", err) } unlockedKey, err := signingKey.Unlock(signerPassphrase) if err != nil { - return errors.Wrap(err, "signingKey.Unlock failed") + return fmt.Errorf("signingKey.Unlock failed: %w", err) } defer unlockedKey.ClearPrivateParams() keyRing, err := crypto.NewKeyRing(unlockedKey) if err != nil { - return errors.Wrap(err, "crypto.NewKeyRing failed") + return fmt.Errorf("crypto.NewKeyRing failed: %w", err) } messageReader, err := os.Open(targetFile) if err != nil { - return errors.Wrapf(err, "os.Open failed (targetFile: %s)", targetFile) + return fmt.Errorf("os.Open failed (targetFile: %s): %w", targetFile, err) } defer messageReader.Close() signature, err := keyRing.SignDetachedStream(messageReader) if err != nil { - return errors.Wrap(err, "keyRing.SignDetached failed") + return fmt.Errorf("keyRing.SignDetached failed: %w", err) } armoredSignature, err := armor.ArmorWithTypeAndCustomHeaders(signature.Data, constants.PGPSignatureHeader, fmt.Sprintf("%s-%s", options.PackageName, options.PackageVersion), signatureComment) if err != nil { - return errors.Wrap(err, "signature.GetArmored failed") + return fmt.Errorf("signature.GetArmored failed: %w", err) } logger.Debug("Signature generated for the target file, writing the .sig file") targetSigFile := targetFile + ".sig" err = os.WriteFile(targetSigFile, []byte(armoredSignature), 0644) if err != nil { - return errors.Wrap(err, "can't write the signature file") + return fmt.Errorf("can't write the signature file: %w", err) } logger.Infof("Signature file written: %s", targetSigFile) diff --git a/internal/formatter/formatter.go b/internal/formatter/formatter.go index 4bef4b77b..c2b408c85 100644 --- a/internal/formatter/formatter.go +++ b/internal/formatter/formatter.go @@ -8,8 +8,6 @@ import ( "fmt" "os" "path/filepath" - - "github.com/pkg/errors" ) type formatter func(content []byte) ([]byte, bool, error) @@ -35,13 +33,13 @@ func Format(packageRoot string, failFast bool) error { } err = formatFile(path, failFast) if err != nil { - return errors.Wrapf(err, "formatting file failed (path: %s)", path) + return fmt.Errorf("formatting file failed (path: %s): %w", path, err) } return nil }) if err != nil { - return errors.Wrap(err, "walking through the integration files failed") + return fmt.Errorf("walking through the integration files failed: %w", err) } return nil } @@ -52,7 +50,7 @@ func formatFile(path string, failFast bool) error { content, err := os.ReadFile(path) if err != nil { - return errors.Wrap(err, "reading file content failed") + return fmt.Errorf("reading file content failed: %w", err) } format, defined := formatters[ext] @@ -62,7 +60,7 @@ func formatFile(path string, failFast bool) error { newContent, alreadyFormatted, err := format(content) if err != nil { - return errors.Wrap(err, "formatting file content failed") + return fmt.Errorf("formatting file content failed: %w", err) } if alreadyFormatted { @@ -75,7 +73,7 @@ func formatFile(path string, failFast bool) error { err = os.WriteFile(path, newContent, 0755) if err != nil { - return errors.Wrapf(err, "rewriting file failed (path: %s)", path) + return fmt.Errorf("rewriting file failed (path: %s): %w", path, err) } return nil } diff --git a/internal/formatter/json_formatter.go b/internal/formatter/json_formatter.go index 88f8a8f55..b20f30e90 100644 --- a/internal/formatter/json_formatter.go +++ b/internal/formatter/json_formatter.go @@ -6,8 +6,7 @@ package formatter import ( "encoding/json" - - "github.com/pkg/errors" + "fmt" ) // JSONFormatter function is responsible for formatting the given JSON input. @@ -16,12 +15,12 @@ func JSONFormatter(content []byte) ([]byte, bool, error) { var rawMessage json.RawMessage err := json.Unmarshal(content, &rawMessage) if err != nil { - return nil, false, errors.Wrap(err, "unmarshalling JSON file failed") + return nil, false, fmt.Errorf("unmarshalling JSON file failed: %w", err) } formatted, err := json.MarshalIndent(&rawMessage, "", " ") if err != nil { - return nil, false, errors.Wrap(err, "marshalling JSON raw message failed") + return nil, false, fmt.Errorf("marshalling JSON raw message failed: %w", err) } return formatted, string(content) == string(formatted), nil } diff --git a/internal/formatter/yaml_formatter.go b/internal/formatter/yaml_formatter.go index 013df9e74..7fbcca936 100644 --- a/internal/formatter/yaml_formatter.go +++ b/internal/formatter/yaml_formatter.go @@ -6,10 +6,9 @@ package formatter import ( "bytes" + "fmt" "gopkg.in/yaml.v3" - - "github.com/pkg/errors" ) // YAMLFormatter function is responsible for formatting the given YAML input. @@ -20,7 +19,7 @@ func YAMLFormatter(content []byte) ([]byte, bool, error) { var node yaml.Node err := yaml.Unmarshal(content, &node) if err != nil { - return nil, false, errors.Wrap(err, "unmarshalling YAML file failed") + return nil, false, fmt.Errorf("unmarshalling YAML file failed: %w", err) } var b bytes.Buffer @@ -28,7 +27,7 @@ func YAMLFormatter(content []byte) ([]byte, bool, error) { encoder.SetIndent(2) err = encoder.Encode(&node) if err != nil { - return nil, false, errors.Wrap(err, "marshalling YAML node failed") + return nil, false, fmt.Errorf("marshalling YAML node failed: %w", err) } formatted := b.Bytes() diff --git a/internal/install/application_configuration.go b/internal/install/application_configuration.go index 5213204aa..a131ffab8 100644 --- a/internal/install/application_configuration.go +++ b/internal/install/application_configuration.go @@ -5,12 +5,13 @@ package install import ( + "errors" "fmt" "os" "path/filepath" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" + "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/configuration/locations" @@ -157,7 +158,7 @@ func selectElasticAgentImageName(version string) string { func Configuration() (*ApplicationConfiguration, error) { configPath, err := locations.NewLocationManager() if err != nil { - return nil, errors.Wrap(err, "can't read configuration directory") + return nil, fmt.Errorf("can't read configuration directory: %w", err) } cfg, err := os.ReadFile(filepath.Join(configPath.RootDir(), applicationConfigurationYmlFile)) @@ -165,13 +166,13 @@ func Configuration() (*ApplicationConfiguration, error) { return DefaultConfiguration(), nil } if err != nil { - return nil, errors.Wrap(err, "can't read configuration file") + return nil, fmt.Errorf("can't read configuration file: %w", err) } var c configFile err = yaml.Unmarshal(cfg, &c) if err != nil { - return nil, errors.Wrap(err, "can't unmarshal configuration file") + return nil, fmt.Errorf("can't unmarshal configuration file: %w", err) } return &ApplicationConfiguration{ diff --git a/internal/install/install.go b/internal/install/install.go index 814ba072b..92eddb5e6 100644 --- a/internal/install/install.go +++ b/internal/install/install.go @@ -5,11 +5,11 @@ package install import ( + "errors" "fmt" "os" "path/filepath" - "github.com/pkg/errors" "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/configuration/locations" @@ -22,17 +22,17 @@ const versionFilename = "version" func EnsureInstalled() error { elasticPackagePath, err := locations.NewLocationManager() if err != nil { - return errors.Wrap(err, "failed locating the configuration directory") + return fmt.Errorf("failed locating the configuration directory: %w", err) } installed, err := checkIfAlreadyInstalled(elasticPackagePath) if err != nil { - return errors.Wrap(err, "failed to check if there is an elastic-package installation") + return fmt.Errorf("failed to check if there is an elastic-package installation: %w", err) } if installed { latestInstalled, err := checkIfLatestVersionInstalled(elasticPackagePath) if err != nil { - return errors.Wrap(err, "failed to check if latest version is installed") + return fmt.Errorf("failed to check if latest version is installed: %w", err) } if latestInstalled { return nil @@ -43,19 +43,19 @@ func EnsureInstalled() error { // Create the root .elastic-package path. err = createElasticPackageDirectory(elasticPackagePath) if err != nil { - return errors.Wrap(err, "creating elastic package directory failed") + return fmt.Errorf("creating elastic package directory failed: %w", err) } // Write the root config.yml file. err = WriteConfigFile(elasticPackagePath, DefaultConfiguration()) if err != nil { - return errors.Wrap(err, "writing configuration file failed") + return fmt.Errorf("writing configuration file failed: %w", err) } // Write root version file. err = writeVersionFile(elasticPackagePath) if err != nil { - return errors.Wrap(err, "writing version file failed") + return fmt.Errorf("writing version file failed: %w", err) } // Create initial profile: @@ -66,11 +66,11 @@ func EnsureInstalled() error { } err = profile.CreateProfile(options) if err != nil { - return errors.Wrap(err, "creation of initial profile failed") + return fmt.Errorf("creation of initial profile failed: %w", err) } if err := createServiceLogsDir(elasticPackagePath); err != nil { - return errors.Wrap(err, "creating service logs directory failed") + return fmt.Errorf("creating service logs directory failed: %w", err) } fmt.Fprintln(os.Stderr, "elastic-package has been installed.") @@ -83,7 +83,7 @@ func checkIfAlreadyInstalled(elasticPackagePath *locations.LocationManager) (boo return false, nil } if err != nil { - return false, errors.Wrapf(err, "stat file failed (path: %s)", elasticPackagePath) + return false, fmt.Errorf("stat file failed (path: %s): %w", elasticPackagePath, err) } return true, nil } @@ -92,17 +92,17 @@ func createElasticPackageDirectory(elasticPackagePath *locations.LocationManager //remove unmanaged subdirectories err := os.RemoveAll(elasticPackagePath.TempDir()) // remove in case of potential upgrade if err != nil { - return errors.Wrapf(err, "removing directory failed (path: %s)", elasticPackagePath) + return fmt.Errorf("removing directory failed (path: %s): %w", elasticPackagePath, err) } err = os.RemoveAll(elasticPackagePath.DeployerDir()) // remove in case of potential upgrade if err != nil { - return errors.Wrapf(err, "removing directory failed (path: %s)", elasticPackagePath) + return fmt.Errorf("removing directory failed (path: %s): %w", elasticPackagePath, err) } err = os.MkdirAll(elasticPackagePath.RootDir(), 0755) if err != nil { - return errors.Wrapf(err, "creating directory failed (path: %s)", elasticPackagePath) + return fmt.Errorf("creating directory failed (path: %s): %w", elasticPackagePath, err) } return nil } @@ -110,12 +110,12 @@ func createElasticPackageDirectory(elasticPackagePath *locations.LocationManager func WriteConfigFile(elasticPackagePath *locations.LocationManager, configuration *ApplicationConfiguration) error { d, err := yaml.Marshal(configuration.c) if err != nil { - return errors.Wrap(err, "failed to encode configuration") + return fmt.Errorf("failed to encode configuration: %w", err) } err = writeStaticResource(err, filepath.Join(elasticPackagePath.RootDir(), applicationConfigurationYmlFile), string(d)) if err != nil { - return errors.Wrap(err, "writing static resource failed") + return fmt.Errorf("writing static resource failed: %w", err) } return nil } @@ -127,7 +127,7 @@ func writeStaticResource(err error, path, content string) error { err = os.WriteFile(path, []byte(content), 0644) if err != nil { - return errors.Wrapf(err, "writing file failed (path: %s)", path) + return fmt.Errorf("writing file failed (path: %s): %w", path, err) } return nil } @@ -135,7 +135,7 @@ func writeStaticResource(err error, path, content string) error { func migrateConfigDirectory(elasticPackagePath *locations.LocationManager) error { err := writeVersionFile(elasticPackagePath) if err != nil { - return errors.Wrap(err, "writing version file failed") + return fmt.Errorf("writing version file failed: %w", err) } return nil @@ -145,7 +145,7 @@ func createServiceLogsDir(elasticPackagePath *locations.LocationManager) error { dirPath := elasticPackagePath.ServiceLogDir() err := os.MkdirAll(dirPath, 0755) if err != nil { - return errors.Wrapf(err, "mkdir failed (path: %s)", dirPath) + return fmt.Errorf("mkdir failed (path: %s): %w", dirPath, err) } return nil } diff --git a/internal/install/version_file.go b/internal/install/version_file.go index 331aa7684..89d8f79a7 100644 --- a/internal/install/version_file.go +++ b/internal/install/version_file.go @@ -10,8 +10,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/version" @@ -24,7 +22,7 @@ func checkIfLatestVersionInstalled(elasticPackagePath *locations.LocationManager return false, nil // old version, no version file } if err != nil { - return false, errors.Wrap(err, "reading version file failed") + return false, fmt.Errorf("reading version file failed: %w", err) } v := string(versionFile) if version.CommitHash == "undefined" && strings.Contains(v, "undefined") { @@ -39,7 +37,7 @@ func writeVersionFile(elasticPackagePath *locations.LocationManager) error { filepath.Join(elasticPackagePath.RootDir(), versionFilename), buildVersionFile(version.CommitHash, version.BuildTime)) if err != nil { - return errors.Wrap(err, "writing static resource failed") + return fmt.Errorf("writing static resource failed: %w", err) } return nil } diff --git a/internal/kind/kind.go b/internal/kind/kind.go index 578970203..91bf86283 100644 --- a/internal/kind/kind.go +++ b/internal/kind/kind.go @@ -7,8 +7,6 @@ package kind import ( "fmt" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/docker" "github.com/elastic/elastic-package/internal/kubectl" "github.com/elastic/elastic-package/internal/logger" @@ -26,7 +24,7 @@ func VerifyContext() error { currentContext, err := kubectl.CurrentContext() if err != nil { - return errors.Wrap(err, "can't read current Kubernetes context") + return fmt.Errorf("can't read current Kubernetes context: %w", err) } if currentContext != kindContext { return fmt.Errorf("unexpected Kubernetes context selected (actual: %s, expected: %s)", currentContext, kindContext) @@ -38,7 +36,7 @@ func VerifyContext() error { func ConnectToElasticStackNetwork() error { containerID, err := controlPlaneContainerID() if err != nil { - return errors.Wrap(err, "can't find kind-control plane node") + return fmt.Errorf("can't find kind-control plane node: %w", err) } stackNetwork := stack.Network() @@ -46,7 +44,7 @@ func ConnectToElasticStackNetwork() error { networkDescriptions, err := docker.InspectNetwork(stackNetwork) if err != nil { - return errors.Wrap(err, "can't inspect network") + return fmt.Errorf("can't inspect network: %w", err) } if len(networkDescriptions) != 1 { return fmt.Errorf("expected single network description, got %d entries", len(networkDescriptions)) @@ -62,7 +60,7 @@ func ConnectToElasticStackNetwork() error { logger.Debugf("attach %s container (ID: %s) to stack network %s", ControlPlaneContainerName, containerID, stackNetwork) err = docker.ConnectToNetwork(containerID, stackNetwork) if err != nil { - return errors.Wrap(err, "can't connect to the Elastic stack network") + return fmt.Errorf("can't connect to the Elastic stack network: %w", err) } return nil } @@ -72,7 +70,7 @@ func controlPlaneContainerID() (string, error) { containerID, err := docker.ContainerID(ControlPlaneContainerName) if err != nil { - return "", errors.Wrap(err, "can't find container ID, make sure you have run \"kind create cluster\"") + return "", fmt.Errorf("can't find container ID, make sure you have run \"kind create cluster\": %w", err) } return containerID, nil } diff --git a/internal/kubectl/kubectl.go b/internal/kubectl/kubectl.go index 38a436795..f3277e766 100644 --- a/internal/kubectl/kubectl.go +++ b/internal/kubectl/kubectl.go @@ -6,11 +6,10 @@ package kubectl import ( "bytes" + "fmt" "os/exec" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/logger" ) @@ -25,7 +24,7 @@ func CurrentContext() (string, error) { logger.Debugf("output command: %s", cmd) output, err := cmd.Output() if err != nil { - return "", errors.Wrapf(err, "kubectl command failed (stderr=%q)", errOutput.String()) + return "", fmt.Errorf("kubectl command failed (stderr=%q): %w", errOutput.String(), err) } return string(bytes.TrimSpace(output)), nil } @@ -52,7 +51,7 @@ func modifyKubernetesResources(action string, definitionPaths []string) ([]byte, logger.Debugf("run command: %s", cmd) output, err := cmd.Output() if err != nil { - return nil, errors.Wrapf(err, "kubectl apply failed (stderr=%q)", errOutput.String()) + return nil, fmt.Errorf("kubectl apply failed (stderr=%q): %w", errOutput.String(), err) } return output, nil } @@ -70,7 +69,7 @@ func applyKubernetesResourcesStdin(input []byte) ([]byte, error) { logger.Debugf("run command: %s", kubectlCmd) output, err := kubectlCmd.Output() if err != nil { - return nil, errors.Wrapf(err, "kubectl apply failed (stderr=%q)", errOutput.String()) + return nil, fmt.Errorf("kubectl apply failed (stderr=%q): %w", errOutput.String(), err) } return output, nil } diff --git a/internal/kubectl/kubectl_apply.go b/internal/kubectl/kubectl_apply.go index a58c18490..cee7c05dd 100644 --- a/internal/kubectl/kubectl_apply.go +++ b/internal/kubectl/kubectl_apply.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "github.com/pkg/errors" "gopkg.in/yaml.v3" "helm.sh/helm/v3/pkg/kube" "k8s.io/apimachinery/pkg/api/meta" @@ -74,13 +73,13 @@ func Apply(definitionsPath []string) error { logger.Debugf("Apply Kubernetes custom definitions") out, err := modifyKubernetesResources("apply", definitionsPath) if err != nil { - return errors.Wrap(err, "can't modify Kubernetes resources (apply)") + return fmt.Errorf("can't modify Kubernetes resources (apply): %w", err) } logger.Debugf("Handle \"apply\" command output") err = handleApplyCommandOutput(out) if err != nil { - return errors.Wrap(err, "can't handle command output") + return fmt.Errorf("can't handle command output: %w", err) } return nil } @@ -90,13 +89,13 @@ func ApplyStdin(input []byte) error { logger.Debugf("Apply Kubernetes stdin") out, err := applyKubernetesResourcesStdin(input) if err != nil { - return errors.Wrap(err, "can't modify Kubernetes resources (apply stdin)") + return fmt.Errorf("can't modify Kubernetes resources (apply stdin): %w", err) } logger.Debugf("Handle \"apply\" command output") err = handleApplyCommandOutput(out) if err != nil { - return errors.Wrap(err, "can't handle command output") + return fmt.Errorf("can't handle command output: %w", err) } return nil } @@ -105,13 +104,13 @@ func handleApplyCommandOutput(out []byte) error { logger.Debugf("Extract resources from command output") resources, err := extractResources(out) if err != nil { - return errors.Wrap(err, "can't extract resources") + return fmt.Errorf("can't extract resources: %w", err) } logger.Debugf("Wait for ready resources") err = waitForReadyResources(resources) if err != nil { - return errors.Wrap(err, "resources are not ready") + return fmt.Errorf("resources are not ready: %w", err) } return nil } @@ -121,7 +120,7 @@ func waitForReadyResources(resources []resource) error { for _, r := range resources { resInfo, err := createResourceInfo(r) if err != nil { - return errors.Wrap(err, "can't fetch resource info") + return fmt.Errorf("can't fetch resource info: %w", err) } resList = append(resList, resInfo) } @@ -137,7 +136,7 @@ func waitForReadyResources(resources []resource) error { // Can be solved with multi-node clusters. err := kubeClient.Wait(resList, readinessTimeout) if err != nil { - return errors.Wrap(err, "waiter failed") + return fmt.Errorf("waiter failed: %w", err) } return nil } @@ -158,7 +157,7 @@ func extractResource(output []byte) (*resource, error) { var r resource err := yaml.Unmarshal(output, &r) if err != nil { - return nil, errors.Wrap(err, "can't unmarshal command output") + return nil, fmt.Errorf("can't unmarshal command output: %w", err) } return &r, nil } @@ -171,7 +170,7 @@ func createResourceInfo(r resource) (*kresource.Info, error) { restClient, err := createRESTClientForResource(r) if err != nil { - return nil, errors.Wrap(err, "can't create REST client for resource") + return nil, fmt.Errorf("can't create REST client for resource: %w", err) } var group string @@ -206,7 +205,7 @@ func createResourceInfo(r resource) (*kresource.Info, error) { logger.Debugf("Sync resource info: %s (kind: %s, namespace: %s)", r.Metadata.Name, r.Kind, r.Metadata.Namespace) err = resInfo.Get() if err != nil { - return nil, errors.Wrap(err, "can't sync resource info") + return nil, fmt.Errorf("can't sync resource info: %w", err) } return resInfo, nil } @@ -215,7 +214,7 @@ func createRESTClientForResource(r resource) (*rest.RESTClient, error) { restClientGetter := genericclioptions.NewConfigFlags(true) restConfig, err := restClientGetter.ToRESTConfig() if err != nil { - return nil, errors.Wrap(err, "can't convert to REST config") + return nil, fmt.Errorf("can't convert to REST config: %w", err) } restConfig.NegotiatedSerializer = kresource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer @@ -227,7 +226,7 @@ func createRESTClientForResource(r resource) (*rest.RESTClient, error) { restClient, err := rest.UnversionedRESTClientFor(restConfig) if err != nil { - return nil, errors.Wrap(err, "can't create unversioned REST client") + return nil, fmt.Errorf("can't create unversioned REST client: %w", err) } return restClient, nil } diff --git a/internal/packages/archetype/archetype.go b/internal/packages/archetype/archetype.go index cefe75925..7e2bf1c83 100644 --- a/internal/packages/archetype/archetype.go +++ b/internal/packages/archetype/archetype.go @@ -7,11 +7,10 @@ package archetype import ( "bytes" "encoding/base64" + "fmt" "os" "path/filepath" "text/template" - - "github.com/pkg/errors" ) func renderResourceFile(templateBody string, data interface{}, targetPath string) error { @@ -19,18 +18,18 @@ func renderResourceFile(templateBody string, data interface{}, targetPath string var rendered bytes.Buffer err := t.Execute(&rendered, data) if err != nil { - return errors.Wrap(err, "can't render package resource") + return fmt.Errorf("can't render package resource: %w", err) } err = os.MkdirAll(filepath.Dir(targetPath), 0755) if err != nil { - return errors.Wrap(err, "can't create base directory") + return fmt.Errorf("can't create base directory: %w", err) } packageManifestPath := targetPath err = os.WriteFile(packageManifestPath, rendered.Bytes(), 0644) if err != nil { - return errors.Wrapf(err, "can't write resource file (path: %s)", packageManifestPath) + return fmt.Errorf("can't write resource file (path: %s): %w", packageManifestPath, err) } return nil } @@ -38,7 +37,7 @@ func renderResourceFile(templateBody string, data interface{}, targetPath string func decodeBase64Resource(encoded string) ([]byte, error) { decoded, err := base64.StdEncoding.DecodeString(encoded) if err != nil { - return nil, errors.Wrap(err, "can't decode encoded resource") + return nil, fmt.Errorf("can't decode encoded resource: %w", err) } return decoded, nil } @@ -46,13 +45,13 @@ func decodeBase64Resource(encoded string) ([]byte, error) { func writeRawResourceFile(content []byte, targetPath string) error { err := os.MkdirAll(filepath.Dir(targetPath), 0755) if err != nil { - return errors.Wrap(err, "can't create base directory") + return fmt.Errorf("can't create base directory: %w", err) } packageManifestPath := targetPath err = os.WriteFile(packageManifestPath, content, 0644) if err != nil { - return errors.Wrapf(err, "can't write resource file (path: %s)", packageManifestPath) + return fmt.Errorf("can't write resource file (path: %s): %w", packageManifestPath, err) } return nil } diff --git a/internal/packages/archetype/data_stream.go b/internal/packages/archetype/data_stream.go index cf8daa3d9..8b36ff029 100644 --- a/internal/packages/archetype/data_stream.go +++ b/internal/packages/archetype/data_stream.go @@ -9,8 +9,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/formatter" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/packages" @@ -33,33 +31,33 @@ func CreateDataStream(dataStreamDescriptor DataStreamDescriptor) error { logger.Debugf("Write data stream manifest") err = renderResourceFile(dataStreamManifestTemplate, &dataStreamDescriptor, filepath.Join(dataStreamDir, "manifest.yml")) if err != nil { - return errors.Wrap(err, "can't render data stream manifest") + return fmt.Errorf("can't render data stream manifest: %w", err) } logger.Debugf("Write base fields") err = renderResourceFile(dataStreamFieldsBaseTemplate, &dataStreamDescriptor, filepath.Join(dataStreamDir, "fields", "base-fields.yml")) if err != nil { - return errors.Wrap(err, "can't render base fields") + return fmt.Errorf("can't render base fields: %w", err) } logger.Debugf("Write agent stream") err = renderResourceFile(dataStreamAgentStreamTemplate, &dataStreamDescriptor, filepath.Join(dataStreamDir, "agent", "stream", "stream.yml.hbs")) if err != nil { - return errors.Wrap(err, "can't render base fields") + return fmt.Errorf("can't render base fields: %w", err) } if dataStreamDescriptor.Manifest.Type == "logs" { logger.Debugf("Write ingest pipeline") err = renderResourceFile(dataStreamElasticsearchIngestPipelineTemplate, &dataStreamDescriptor, filepath.Join(dataStreamDir, "elasticsearch", "ingest_pipeline", "default.yml")) if err != nil { - return errors.Wrap(err, "can't render ingest pipeline") + return fmt.Errorf("can't render ingest pipeline: %w", err) } } logger.Debugf("Format the entire package") err = formatter.Format(dataStreamDescriptor.PackageRoot, false) if err != nil { - return errors.Wrap(err, "can't format the new package") + return fmt.Errorf("can't format the new package: %w", err) } fmt.Printf("New data stream has been created: %s\n", dataStreamDescriptor.Manifest.Name) diff --git a/internal/packages/archetype/package.go b/internal/packages/archetype/package.go index cdc3f3e6e..9fae2255d 100644 --- a/internal/packages/archetype/package.go +++ b/internal/packages/archetype/package.go @@ -9,8 +9,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/formatter" "github.com/elastic/elastic-package/internal/licenses" "github.com/elastic/elastic-package/internal/logger" @@ -33,49 +31,49 @@ func CreatePackage(packageDescriptor PackageDescriptor) error { logger.Debugf("Write package manifest") err = renderResourceFile(packageManifestTemplate, &packageDescriptor, filepath.Join(baseDir, "manifest.yml")) if err != nil { - return errors.Wrap(err, "can't render package manifest") + return fmt.Errorf("can't render package manifest: %w", err) } logger.Debugf("Write package changelog") err = renderResourceFile(packageChangelogTemplate, &packageDescriptor, filepath.Join(baseDir, "changelog.yml")) if err != nil { - return errors.Wrap(err, "can't render package changelog") + return fmt.Errorf("can't render package changelog: %w", err) } logger.Debugf("Write docs readme") err = renderResourceFile(packageDocsReadme, &packageDescriptor, filepath.Join(baseDir, "docs", "README.md")) if err != nil { - return errors.Wrap(err, "can't render package README") + return fmt.Errorf("can't render package README: %w", err) } if license := packageDescriptor.Manifest.Source.License; license != "" { logger.Debugf("Write license file") err = licenses.WriteTextToFile(license, filepath.Join(baseDir, "LICENSE.txt")) if err != nil { - return errors.Wrap(err, "can't write license file") + return fmt.Errorf("can't write license file: %w", err) } } logger.Debugf("Write sample icon") err = writeRawResourceFile(packageImgSampleIcon, filepath.Join(baseDir, "img", "sample-logo.svg")) if err != nil { - return errors.Wrap(err, "can't render sample icon") + return fmt.Errorf("can't render sample icon: %w", err) } logger.Debugf("Write sample screenshot") decodedSampleScreenshot, err := decodeBase64Resource(packageImgSampleScreenshot) if err != nil { - return errors.Wrap(err, "can't decode sample screenshot") + return fmt.Errorf("can't decode sample screenshot: %w", err) } err = writeRawResourceFile(decodedSampleScreenshot, filepath.Join(baseDir, "img", "sample-screenshot.png")) if err != nil { - return errors.Wrap(err, "can't render sample screenshot") + return fmt.Errorf("can't render sample screenshot: %w", err) } logger.Debugf("Format the entire package") err = formatter.Format(baseDir, false) if err != nil { - return errors.Wrap(err, "can't format the new package") + return fmt.Errorf("can't format the new package: %w", err) } fmt.Printf("New package has been created: %s\n", baseDir) diff --git a/internal/packages/archetype/package_imgs.go b/internal/packages/archetype/package_imgs.go index 4b94dc135..1c4218cd5 100644 --- a/internal/packages/archetype/package_imgs.go +++ b/internal/packages/archetype/package_imgs.go @@ -4,7 +4,9 @@ package archetype -import "strings" +import ( + "strings" +) var packageImgSampleIcon = []byte(``) diff --git a/internal/packages/archetype/package_test.go b/internal/packages/archetype/package_test.go index fa1788148..4d5c6b4a7 100644 --- a/internal/packages/archetype/package_test.go +++ b/internal/packages/archetype/package_test.go @@ -5,12 +5,13 @@ package archetype import ( + "fmt" "os" "path/filepath" "testing" "github.com/elastic/package-spec/v2/code/go/pkg/validator" - "github.com/pkg/errors" + "github.com/stretchr/testify/require" "github.com/elastic/elastic-package/internal/packages" @@ -80,7 +81,7 @@ func createPackageDescriptorForTest() PackageDescriptor { func checkPackage(packageName string) error { wd, err := os.Getwd() if err != nil { - return errors.Wrap(err, "can't get working directory") + return fmt.Errorf("can't get working directory: %w", err) } packageRoot := filepath.Join(wd, packageName) @@ -89,7 +90,7 @@ func checkPackage(packageName string) error { err = validator.ValidateFromPath(packageRoot) if err != nil { - return errors.Wrap(err, "linting package failed") + return fmt.Errorf("linting package failed: %w", err) } return nil } diff --git a/internal/packages/assets.go b/internal/packages/assets.go index 8c8319776..d05c3943f 100644 --- a/internal/packages/assets.go +++ b/internal/packages/assets.go @@ -6,12 +6,11 @@ package packages import ( "encoding/json" + "errors" "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/multierror" ) @@ -46,12 +45,12 @@ func (asset Asset) String() string { func LoadPackageAssets(pkgRootPath string) ([]Asset, error) { assets, err := loadKibanaAssets(pkgRootPath) if err != nil { - return nil, errors.Wrap(err, "could not load kibana assets") + return nil, fmt.Errorf("could not load kibana assets: %w", err) } a, err := loadElasticsearchAssets(pkgRootPath) if err != nil { - return a, errors.Wrap(err, "could not load elasticsearch assets") + return a, fmt.Errorf("could not load elasticsearch assets: %w", err) } assets = append(assets, a...) @@ -78,7 +77,7 @@ func loadKibanaAssets(pkgRootPath string) ([]Asset, error) { for _, assetType := range assetTypes { a, err := loadFileBasedAssets(kibanaAssetsFolderPath, assetType) if err != nil { - errs = append(errs, errors.Wrapf(err, "could not load kibana %s assets", assetType)) + errs = append(errs, fmt.Errorf("could not load kibana %s assets: %w", assetType, err)) continue } @@ -96,19 +95,19 @@ func loadElasticsearchAssets(pkgRootPath string) ([]Asset, error) { packageManifestPath := filepath.Join(pkgRootPath, PackageManifestFile) pkgManifest, err := ReadPackageManifest(packageManifestPath) if err != nil { - return nil, errors.Wrap(err, "reading package manifest file failed") + return nil, fmt.Errorf("reading package manifest file failed: %w", err) } dataStreamManifestPaths, err := filepath.Glob(filepath.Join(pkgRootPath, "data_stream", "*", DataStreamManifestFile)) if err != nil { - return nil, errors.Wrap(err, "could not read data stream manifest file paths") + return nil, fmt.Errorf("could not read data stream manifest file paths: %w", err) } var assets []Asset for _, dsManifestPath := range dataStreamManifestPaths { dsManifest, err := ReadDataStreamManifest(dsManifestPath) if err != nil { - return nil, errors.Wrap(err, "reading data stream manifest failed") + return nil, fmt.Errorf("reading data stream manifest failed: %w", err) } indexTemplateName := dsManifest.IndexTemplateName(pkgManifest.Name) @@ -127,7 +126,7 @@ func loadElasticsearchAssets(pkgRootPath string) ([]Asset, error) { for _, pattern := range []string{"*.json", "*.yml"} { files, err := filepath.Glob(filepath.Join(elasticsearchDirPath, pattern)) if err != nil { - return nil, errors.Wrapf(err, "listing '%s' in '%s'", pattern, elasticsearchDirPath) + return nil, fmt.Errorf("listing '%s' in '%s': %w", pattern, elasticsearchDirPath, err) } pipelineFiles = append(pipelineFiles, files...) } @@ -160,19 +159,19 @@ func loadFileBasedAssets(kibanaAssetsFolderPath string, assetType AssetType) ([] return nil, nil } if err != nil { - return nil, errors.Wrapf(err, "error finding kibana %s assets folder", assetType) + return nil, fmt.Errorf("error finding kibana %s assets folder: %w", assetType, err) } paths, err := filepath.Glob(filepath.Join(assetsFolderPath, "*.json")) if err != nil { - return nil, errors.Wrapf(err, "could not read %s files", assetType) + return nil, fmt.Errorf("could not read %s files: %w", assetType, err) } var assets []Asset for _, assetPath := range paths { assetID, err := readAssetID(assetPath) if err != nil { - return nil, errors.Wrapf(err, "can't read asset ID (path: %s)", assetPath) + return nil, fmt.Errorf("can't read asset ID (path: %s): %w", assetPath, err) } asset := Asset{ @@ -188,7 +187,7 @@ func loadFileBasedAssets(kibanaAssetsFolderPath string, assetType AssetType) ([] func readAssetID(assetPath string) (string, error) { content, err := os.ReadFile(assetPath) if err != nil { - return "", errors.Wrap(err, "can't read file body") + return "", fmt.Errorf("can't read file body: %w", err) } assetBody := struct { @@ -197,7 +196,7 @@ func readAssetID(assetPath string) (string, error) { err = json.Unmarshal(content, &assetBody) if err != nil { - return "", errors.Wrap(err, "can't unmarshal asset") + return "", fmt.Errorf("can't unmarshal asset: %w", err) } if assetBody.ID == "" { diff --git a/internal/packages/buildmanifest/build_manifest.go b/internal/packages/buildmanifest/build_manifest.go index 45f6345d9..09034046a 100644 --- a/internal/packages/buildmanifest/build_manifest.go +++ b/internal/packages/buildmanifest/build_manifest.go @@ -5,11 +5,11 @@ package buildmanifest import ( + "errors" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" ) @@ -48,13 +48,13 @@ func ReadBuildManifest(packageRoot string) (*BuildManifest, bool, error) { return nil, false, nil // ignore not found errors } if err != nil { - return nil, false, errors.Wrapf(err, "reading file failed (path: %s)", path) + return nil, false, fmt.Errorf("reading file failed (path: %s): %w", path, err) } var bm BuildManifest err = cfg.Unpack(&bm) if err != nil { - return nil, true, errors.Wrapf(err, "unpacking build manifest failed (path: %s)", path) + return nil, true, fmt.Errorf("unpacking build manifest failed (path: %s): %w", path, err) } return &bm, true, nil } diff --git a/internal/packages/changelog/changelog.go b/internal/packages/changelog/changelog.go index 8958c1031..eab373fc8 100644 --- a/internal/packages/changelog/changelog.go +++ b/internal/packages/changelog/changelog.go @@ -5,11 +5,11 @@ package changelog import ( + "fmt" "path/filepath" "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" - "github.com/pkg/errors" ) const ( @@ -39,13 +39,13 @@ func ReadChangelogFromPackageRoot(packageRoot string) ([]Revision, error) { func ReadChangelog(path string) ([]Revision, error) { cfg, err := yaml.NewConfigWithFile(path, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "reading file failed (path: %s)", path) + return nil, fmt.Errorf("reading file failed (path: %s): %w", path, err) } var c []Revision err = cfg.Unpack(&c) if err != nil { - return nil, errors.Wrapf(err, "unpacking package changelog failed (path: %s)", path) + return nil, fmt.Errorf("unpacking package changelog failed (path: %s): %w", path, err) } return c, nil } diff --git a/internal/packages/changelog/yaml.go b/internal/packages/changelog/yaml.go index 3ca8f264f..119fb96d2 100644 --- a/internal/packages/changelog/yaml.go +++ b/internal/packages/changelog/yaml.go @@ -5,8 +5,11 @@ package changelog import ( + "errors" + "fmt" + "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" + "gopkg.in/yaml.v3" "github.com/elastic/elastic-package/internal/formatter" @@ -91,7 +94,7 @@ func PatchYAML(d []byte, patch Revision) ([]byte, error) { d, err = formatResult(result) if err != nil { - return nil, errors.Wrap(err, "failed to format manifest") + return nil, fmt.Errorf("failed to format manifest: %w", err) } return d, nil } @@ -100,19 +103,19 @@ func SetManifestVersion(d []byte, version string) ([]byte, error) { var node yaml.Node err := yaml.Unmarshal(d, &node) if err != nil { - return nil, errors.Wrap(err, "failed to decode manifest") + return nil, fmt.Errorf("failed to decode manifest: %w", err) } // Manifest is a document, with a single element, that should be a map. if len(node.Content) == 0 || node.Content[0].Kind != yaml.MappingNode { - return nil, errors.Wrap(err, "unexpected manifest content") + return nil, fmt.Errorf("unexpected manifest content: %w", err) } setYamlMapValue(node.Content[0], "version", version) d, err = formatResult(&node) if err != nil { - return nil, errors.Wrap(err, "failed to format manifest") + return nil, fmt.Errorf("failed to format manifest: %w", err) } return d, nil } diff --git a/internal/packages/conditions.go b/internal/packages/conditions.go index f819f14d3..4b149a13a 100644 --- a/internal/packages/conditions.go +++ b/internal/packages/conditions.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/multierror" @@ -28,19 +27,20 @@ type packageRequirements struct { func CheckConditions(manifest PackageManifest, keyValuePairs []string) error { requirements, err := parsePackageRequirements(keyValuePairs) if err != nil { - return errors.Wrap(err, "can't parse given keyValue pairs as package conditions") + return fmt.Errorf("can't parse given keyValue pairs as package conditions: %w", err) } // So far, Kibana is the only supported constraint if len(manifest.Conditions.Kibana.Version) > 0 && requirements.kibana.version != nil { kibanaConstraint, err := semver.NewConstraint(manifest.Conditions.Kibana.Version) if err != nil { - return errors.Wrap(err, "invalid constraint for Kibana") + return fmt.Errorf("invalid constraint for Kibana: %w", err) } logger.Debugf("Verify Kibana version (constraint: %s, requirement: %s)", manifest.Conditions.Kibana.Version, requirements.kibana.version) if ok, errs := kibanaConstraint.Validate(requirements.kibana.version); !ok { - return errors.Wrap(multierror.Error(errs), "Kibana constraint unsatisfied") + //lint:ignore ST1005 error starting with product name can be capitalized + return fmt.Errorf("Kibana constraint unsatisfied: %w", multierror.Error(errs)) } logger.Debugf("Constraint %s = %s is satisfied", kibanaVersionRequirement, manifest.Conditions.Kibana.Version) } @@ -60,7 +60,7 @@ func parsePackageRequirements(keyValuePairs []string) (*packageRequirements, err case kibanaVersionRequirement: ver, err := semver.NewVersion(s[1]) if err != nil { - return nil, errors.Wrap(err, "can't parse kibana.version as valid semver") + return nil, fmt.Errorf("can't parse kibana.version as valid semver: %w", err) } // Constraint validation doesn't handle prerelease tags. It fails with error: @@ -69,7 +69,7 @@ func parsePackageRequirements(keyValuePairs []string) (*packageRequirements, err // Source code reference: https://github.com/Masterminds/semver/blob/7e314bd12e4aa8ea9742b1e4765f3fe65de38c2d/constraints.go#L89 withoutPrerelease, err := ver.SetPrerelease("") // clean prerelease tag if err != nil { - return nil, errors.Wrap(err, "can't clean prerelease tag from semver") + return nil, fmt.Errorf("can't clean prerelease tag from semver: %w", err) } pr.kibana.version = &withoutPrerelease default: diff --git a/internal/packages/installer/installer.go b/internal/packages/installer/installer.go index d2314c1e0..dcf90ec73 100644 --- a/internal/packages/installer/installer.go +++ b/internal/packages/installer/installer.go @@ -7,8 +7,6 @@ package installer import ( "fmt" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/kibana" "github.com/elastic/elastic-package/internal/packages" ) @@ -41,7 +39,7 @@ func CreateForManifest(kibanaClient *kibana.Client, packageRoot string) (*manife func (i *manifestInstaller) Install() (*InstalledPackage, error) { assets, err := i.kibanaClient.InstallPackage(i.manifest.Name, i.manifest.Version) if err != nil { - return nil, errors.Wrap(err, "can't install the package") + return nil, fmt.Errorf("can't install the package: %w", err) } return &InstalledPackage{ @@ -55,7 +53,7 @@ func (i *manifestInstaller) Install() (*InstalledPackage, error) { func (i *manifestInstaller) Uninstall() error { _, err := i.kibanaClient.RemovePackage(i.manifest.Name, i.manifest.Version) if err != nil { - return errors.Wrap(err, "can't remove the package") + return fmt.Errorf("can't remove the package: %w", err) } return nil } diff --git a/internal/packages/installer/zip_installer.go b/internal/packages/installer/zip_installer.go index 70759fc22..df062bfcc 100644 --- a/internal/packages/installer/zip_installer.go +++ b/internal/packages/installer/zip_installer.go @@ -7,8 +7,6 @@ package installer import ( "fmt" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/kibana" "github.com/elastic/elastic-package/internal/packages" ) @@ -37,7 +35,7 @@ func CreateForZip(kibanaClient *kibana.Client, zipPath string) (*zipInstaller, e func (i *zipInstaller) Install() (*InstalledPackage, error) { assets, err := i.kibanaClient.InstallZipPackage(i.zipPath) if err != nil { - return nil, errors.Wrap(err, "can't install the package") + return nil, fmt.Errorf("can't install the package: %w", err) } return &InstalledPackage{ @@ -51,7 +49,7 @@ func (i *zipInstaller) Install() (*InstalledPackage, error) { func (i *zipInstaller) Uninstall() error { _, err := i.kibanaClient.RemovePackage(i.manifest.Name, i.manifest.Version) if err != nil { - return errors.Wrap(err, "can't remove the package") + return fmt.Errorf("can't remove the package: %w", err) } return nil } diff --git a/internal/packages/packages.go b/internal/packages/packages.go index ff5096239..429243da9 100644 --- a/internal/packages/packages.go +++ b/internal/packages/packages.go @@ -7,13 +7,12 @@ package packages import ( "archive/zip" "encoding/json" + "errors" "fmt" "io/fs" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" ) @@ -162,7 +161,7 @@ type DataStreamManifest struct { func MustFindPackageRoot() (string, error) { root, found, err := FindPackageRoot() if err != nil { - return "", errors.Wrap(err, "locating package root failed") + return "", fmt.Errorf("locating package root failed: %w", err) } if !found { return "", errors.New("package root not found") @@ -174,7 +173,7 @@ func MustFindPackageRoot() (string, error) { func FindPackageRoot() (string, bool, error) { workDir, err := os.Getwd() if err != nil { - return "", false, errors.Wrap(err, "locating working directory failed") + return "", false, fmt.Errorf("locating working directory failed: %w", err) } // VolumeName() will return something like "C:" in Windows, and "" in other OSs @@ -188,7 +187,7 @@ func FindPackageRoot() (string, bool, error) { if err == nil && !fileInfo.IsDir() { ok, err := isPackageManifest(path) if err != nil { - return "", false, errors.Wrapf(err, "verifying manifest file failed (path: %s)", path) + return "", false, fmt.Errorf("verifying manifest file failed (path: %s): %w", path, err) } if ok { return dir, true, nil @@ -212,7 +211,7 @@ func FindDataStreamRootForPath(workDir string) (string, bool, error) { if err == nil && !fileInfo.IsDir() { ok, err := isDataStreamManifest(path) if err != nil { - return "", false, errors.Wrapf(err, "verifying manifest file failed (path: %s)", path) + return "", false, fmt.Errorf("verifying manifest file failed (path: %s): %w", path, err) } if ok { return dir, true, nil @@ -236,13 +235,13 @@ func ReadPackageManifestFromPackageRoot(packageRoot string) (*PackageManifest, e func ReadPackageManifestFromZipPackage(zipPackage string) (*PackageManifest, error) { tempDir, err := os.MkdirTemp("", "elastic-package-") if err != nil { - return nil, errors.Wrap(err, "can't prepare a temporary directory") + return nil, fmt.Errorf("can't prepare a temporary directory: %w", err) } defer os.RemoveAll(tempDir) contents, err := extractPackageManifestZipPackage(zipPackage, PackageManifestFile) if err != nil { - return nil, errors.Wrapf(err, "extracting manifest from zip file failed (path: %s)", zipPackage) + return nil, fmt.Errorf("extracting manifest from zip file failed (path: %s): %w", zipPackage, err) } return ReadPackageManifestBytes(contents) @@ -263,12 +262,12 @@ func extractPackageManifestZipPackage(zipPath, sourcePath string) ([]byte, error } if len(matched) == 0 { - return nil, errors.Errorf("not found package %s in %s", sourcePath, zipPath) + return nil, fmt.Errorf("not found package %s in %s", sourcePath, zipPath) } contents, err := fs.ReadFile(zipReader, matched[0]) if err != nil { - return nil, errors.Wrapf(err, "can't read manifest from zip %s", zipPath) + return nil, fmt.Errorf("can't read manifest from zip %s: %w", zipPath, err) } return contents, nil @@ -278,13 +277,13 @@ func extractPackageManifestZipPackage(zipPath, sourcePath string) ([]byte, error func ReadPackageManifest(path string) (*PackageManifest, error) { cfg, err := yaml.NewConfigWithFile(path, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "reading file failed (path: %s)", path) + return nil, fmt.Errorf("reading file failed (path: %s): %w", path, err) } var m PackageManifest err = cfg.Unpack(&m) if err != nil { - return nil, errors.Wrapf(err, "unpacking package manifest failed (path: %s)", path) + return nil, fmt.Errorf("unpacking package manifest failed (path: %s): %w", path, err) } return &m, nil } @@ -292,13 +291,13 @@ func ReadPackageManifest(path string) (*PackageManifest, error) { func ReadPackageManifestBytes(contents []byte) (*PackageManifest, error) { cfg, err := yaml.NewConfig(contents, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrap(err, "reading manifest file failed") + return nil, fmt.Errorf("reading manifest file failed: %w", err) } var m PackageManifest err = cfg.Unpack(&m) if err != nil { - return nil, errors.Wrapf(err, "unpacking package manifest failed") + return nil, fmt.Errorf("unpacking package manifest failed: %w", err) } return &m, nil } @@ -307,13 +306,13 @@ func ReadPackageManifestBytes(contents []byte) (*PackageManifest, error) { func ReadDataStreamManifest(path string) (*DataStreamManifest, error) { cfg, err := yaml.NewConfigWithFile(path, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "reading file failed (path: %s)", path) + return nil, fmt.Errorf("reading file failed (path: %s): %w", path, err) } var m DataStreamManifest err = cfg.Unpack(&m) if err != nil { - return nil, errors.Wrapf(err, "unpacking data stream manifest failed (path: %s)", path) + return nil, fmt.Errorf("unpacking data stream manifest failed (path: %s): %w", path, err) } m.Name = filepath.Base(filepath.Dir(path)) @@ -367,7 +366,7 @@ func (pt *PolicyTemplate) FindInputByType(inputType string) *Input { func isPackageManifest(path string) (bool, error) { m, err := ReadPackageManifest(path) if err != nil { - return false, errors.Wrapf(err, "reading package manifest failed (path: %s)", path) + return false, fmt.Errorf("reading package manifest failed (path: %s): %w", path, err) } return (m.Type == "integration" || m.Type == "input") && m.Version != "", nil } @@ -375,7 +374,7 @@ func isPackageManifest(path string) (bool, error) { func isDataStreamManifest(path string) (bool, error) { m, err := ReadDataStreamManifest(path) if err != nil { - return false, errors.Wrapf(err, "reading package manifest failed (path: %s)", path) + return false, fmt.Errorf("reading package manifest failed (path: %s): %w", path, err) } return m.Title != "" && (m.Type == dataStreamTypeLogs || m.Type == dataStreamTypeMetrics || m.Type == dataStreamTypeSynthetics || m.Type == dataStreamTypeTraces), diff --git a/internal/packages/status/status.go b/internal/packages/status/status.go index d186606ac..f67641075 100644 --- a/internal/packages/status/status.go +++ b/internal/packages/status/status.go @@ -5,8 +5,9 @@ package status import ( + "fmt" + "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/packages" "github.com/elastic/elastic-package/internal/packages/changelog" @@ -26,11 +27,11 @@ type PackageStatus struct { func LocalPackage(packageRootPath string, options registry.SearchOptions) (*PackageStatus, error) { manifest, err := packages.ReadPackageManifestFromPackageRoot(packageRootPath) if err != nil { - return nil, errors.Wrap(err, "reading package manifest failed") + return nil, fmt.Errorf("reading package manifest failed: %w", err) } changelog, err := changelog.ReadChangelogFromPackageRoot(packageRootPath) if err != nil { - return nil, errors.Wrap(err, "reading package changelog failed") + return nil, fmt.Errorf("reading package changelog failed: %w", err) } status, err := RemotePackage(manifest.Name, options) if err != nil { @@ -45,11 +46,11 @@ func LocalPackage(packageRootPath string, options registry.SearchOptions) (*Pack lastChangelogEntry := changelog[0] pendingVersion, err := semver.NewVersion(lastChangelogEntry.Version) if err != nil { - return nil, errors.Wrap(err, "reading changelog semver failed") + return nil, fmt.Errorf("reading changelog semver failed: %w", err) } currentVersion, err := semver.NewVersion(manifest.Version) if err != nil { - return nil, errors.Wrap(err, "reading manifest semver failed") + return nil, fmt.Errorf("reading manifest semver failed: %w", err) } if currentVersion.LessThan(pendingVersion) { status.PendingChanges = &lastChangelogEntry @@ -61,7 +62,7 @@ func LocalPackage(packageRootPath string, options registry.SearchOptions) (*Pack func RemotePackage(packageName string, options registry.SearchOptions) (*PackageStatus, error) { productionManifests, err := registry.Production.Revisions(packageName, options) if err != nil { - return nil, errors.Wrap(err, "retrieving production deployment failed") + return nil, fmt.Errorf("retrieving production deployment failed: %w", err) } return &PackageStatus{ Name: packageName, diff --git a/internal/profile/profile_json.go b/internal/profile/profile_json.go index edd142099..c08f4a859 100644 --- a/internal/profile/profile_json.go +++ b/internal/profile/profile_json.go @@ -6,13 +6,13 @@ package profile import ( "encoding/json" + "errors" + "fmt" "io" "os" "os/user" "time" - "github.com/pkg/errors" - "github.com/elastic/go-resource" "github.com/elastic/elastic-package/internal/version" @@ -31,7 +31,7 @@ type Metadata struct { func profileMetadataContent(applyCtx resource.Context, w io.Writer) error { currentUser, err := user.Current() if err != nil { - return errors.Wrap(err, "error fetching current user") + return fmt.Errorf("error fetching current user: %w", err) } profileName, found := applyCtx.Fact("profile_name") @@ -56,7 +56,7 @@ func profileMetadataContent(applyCtx resource.Context, w io.Writer) error { enc.SetIndent("", " ") err = enc.Encode(profileData) if err != nil { - return errors.Wrap(err, "error marshalling json") + return fmt.Errorf("error marshalling json: %w", err) } return nil @@ -65,13 +65,13 @@ func profileMetadataContent(applyCtx resource.Context, w io.Writer) error { func loadProfileMetadata(path string) (Metadata, error) { d, err := os.ReadFile(path) if err != nil { - return Metadata{}, errors.Wrap(err, "error reading metadata file") + return Metadata{}, fmt.Errorf("error reading metadata file: %w", err) } metadata := Metadata{} err = json.Unmarshal(d, &metadata) if err != nil { - return Metadata{}, errors.Wrapf(err, "error checking profile metadata file %q", path) + return Metadata{}, fmt.Errorf("error checking profile metadata file %q: %w", path, err) } return metadata, nil } diff --git a/internal/registry/client.go b/internal/registry/client.go index 74c80b9c7..f9a9caa76 100644 --- a/internal/registry/client.go +++ b/internal/registry/client.go @@ -5,11 +5,10 @@ package registry import ( + "fmt" "io" "net/http" "net/url" - - "github.com/pkg/errors" ) const ( @@ -36,12 +35,12 @@ func NewClient(baseURL string) *Client { func (c *Client) get(resourcePath string) (int, []byte, error) { base, err := url.Parse(c.baseURL) if err != nil { - return 0, nil, errors.Wrapf(err, "could not parse base URL: %v", c.baseURL) + return 0, nil, fmt.Errorf("could not parse base URL: %v: %w", c.baseURL, err) } rel, err := url.Parse(resourcePath) if err != nil { - return 0, nil, errors.Wrapf(err, "could not create relative URL from resource path: %v", resourcePath) + return 0, nil, fmt.Errorf("could not create relative URL from resource path: %v: %w", resourcePath, err) } u := base.JoinPath(rel.EscapedPath()) @@ -49,19 +48,19 @@ func (c *Client) get(resourcePath string) (int, []byte, error) { req, err := http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { - return 0, nil, errors.Wrapf(err, "could not create request to Package Registry API resource: %s", resourcePath) + return 0, nil, fmt.Errorf("could not create request to Package Registry API resource: %s: %w", resourcePath, err) } client := http.Client{} resp, err := client.Do(req) if err != nil { - return 0, nil, errors.Wrap(err, "could not send request to Package Registry API") + return 0, nil, fmt.Errorf("could not send request to Package Registry API: %w", err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - return resp.StatusCode, nil, errors.Wrap(err, "could not read response body") + return resp.StatusCode, nil, fmt.Errorf("could not read response body: %w", err) } return resp.StatusCode, body, nil diff --git a/internal/registry/revisions.go b/internal/registry/revisions.go index de5e2c722..83b83bcc1 100644 --- a/internal/registry/revisions.go +++ b/internal/registry/revisions.go @@ -12,7 +12,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/google/go-querystring/query" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/packages" ) @@ -40,13 +39,13 @@ func (c *Client) Revisions(packageName string, options SearchOptions) ([]package Package: packageName, }) if err != nil { - return nil, errors.Wrap(err, "could not encode options as query parameters") + return nil, fmt.Errorf("could not encode options as query parameters: %w", err) } path := searchAPI + "?" + parameters.Encode() statusCode, respBody, err := c.get(path) if err != nil { - return nil, errors.Wrap(err, "could not retrieve package") + return nil, fmt.Errorf("could not retrieve package: %w", err) } if statusCode != http.StatusOK { return nil, fmt.Errorf("could not retrieve package; API status code = %d; response body = %s", statusCode, respBody) @@ -54,7 +53,7 @@ func (c *Client) Revisions(packageName string, options SearchOptions) ([]package var packageManifests []packages.PackageManifest if err := json.Unmarshal(respBody, &packageManifests); err != nil { - return nil, errors.Wrap(err, "could not convert package manifests from JSON") + return nil, fmt.Errorf("could not convert package manifests from JSON: %w", err) } sort.Slice(packageManifests, func(i, j int) bool { firstVersion, err := semver.NewVersion(packageManifests[i].Version) diff --git a/internal/service/boot.go b/internal/service/boot.go index 561541a2d..cd8549d67 100644 --- a/internal/service/boot.go +++ b/internal/service/boot.go @@ -12,8 +12,6 @@ import ( "github.com/elastic/elastic-package/internal/logger" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/testrunner/runners/system" "github.com/elastic/elastic-package/internal/testrunner/runners/system/servicedeployer" @@ -37,14 +35,14 @@ func BootUp(options Options) error { Variant: options.Variant, }) if err != nil { - return errors.Wrap(err, "can't create the service deployer instance") + return fmt.Errorf("can't create the service deployer instance: %w", err) } // Boot up the service logger.Debugf("Boot up the service instance") locationManager, err := locations.NewLocationManager() if err != nil { - return errors.Wrap(err, "reading service logs directory failed") + return fmt.Errorf("reading service logs directory failed: %w", err) } var serviceCtxt servicedeployer.ServiceContext @@ -53,7 +51,7 @@ func BootUp(options Options) error { serviceCtxt.Logs.Folder.Local = locationManager.ServiceLogDir() deployed, err := serviceDeployer.SetUp(serviceCtxt) if err != nil { - return errors.Wrap(err, "can't set up the service deployer") + return fmt.Errorf("can't set up the service deployer: %w", err) } fmt.Println("Service is up, please use ctrl+c to take it down") @@ -65,7 +63,7 @@ func BootUp(options Options) error { fmt.Println("Take down the service") err = deployed.TearDown() if err != nil { - return errors.Wrap(err, "can't tear down the service") + return fmt.Errorf("can't tear down the service: %w", err) } return nil } diff --git a/internal/stack/boot.go b/internal/stack/boot.go index f499a8331..4baacc9e1 100644 --- a/internal/stack/boot.go +++ b/internal/stack/boot.go @@ -10,8 +10,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/builder" "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/files" @@ -37,24 +35,24 @@ func BootUp(options Options) error { buildPackagesPath, found, err := builder.FindBuildPackagesDirectory() if err != nil { - return errors.Wrap(err, "finding build packages directory failed") + return fmt.Errorf("finding build packages directory failed: %w", err) } stackPackagesDir, err := locations.NewLocationManager() if err != nil { - return errors.Wrap(err, "locating stack packages directory failed") + return fmt.Errorf("locating stack packages directory failed: %w", err) } err = files.ClearDir(stackPackagesDir.PackagesDir()) if err != nil { - return errors.Wrap(err, "clearing package contents failed") + return fmt.Errorf("clearing package contents failed: %w", err) } if found { fmt.Printf("Custom build packages directory found: %s\n", buildPackagesPath) err = copyUniquePackages(buildPackagesPath, stackPackagesDir.PackagesDir()) if err != nil { - return errors.Wrap(err, "copying package contents failed") + return fmt.Errorf("copying package contents failed: %w", err) } } @@ -67,12 +65,12 @@ func BootUp(options Options) error { err = applyResources(options.Profile, options.StackVersion) if err != nil { - return errors.Wrap(err, "creating stack files failed") + return fmt.Errorf("creating stack files failed: %w", err) } err = dockerComposeBuild(options) if err != nil { - return errors.Wrap(err, "building docker images failed") + return fmt.Errorf("building docker images failed: %w", err) } err = dockerComposeUp(options) @@ -87,12 +85,14 @@ func BootUp(options Options) error { fmt.Println("Elastic Agent failed to start, trying again.") err = dockerComposeUp(options) } - return errors.Wrap(err, "running docker-compose failed") + if err != nil { + return fmt.Errorf("running docker-compose failed: %w", err) + } } err = storeConfig(options.Profile, config) if err != nil { - return errors.Wrap(err, "failed to store config") + return fmt.Errorf("failed to store config: %w", err) } return nil @@ -121,7 +121,7 @@ func onlyElasticAgentFailed() bool { func TearDown(options Options) error { err := dockerComposeDown(options) if err != nil { - return errors.Wrap(err, "stopping docker containers failed") + return fmt.Errorf("stopping docker containers failed: %w", err) } return nil } @@ -131,7 +131,7 @@ func copyUniquePackages(sourcePath, destinationPath string) error { dirEntries, err := os.ReadDir(sourcePath) if err != nil { - return errors.Wrapf(err, "can't read source dir (sourcePath: %s)", sourcePath) + return fmt.Errorf("can't read source dir (sourcePath: %s): %w", sourcePath, err) } for _, entry := range dirEntries { if entry.IsDir() { diff --git a/internal/stack/compose.go b/internal/stack/compose.go index a1e0bb00e..527519776 100644 --- a/internal/stack/compose.go +++ b/internal/stack/compose.go @@ -8,8 +8,6 @@ import ( "fmt" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/compose" "github.com/elastic/elastic-package/internal/docker" "github.com/elastic/elastic-package/internal/install" @@ -57,12 +55,12 @@ func (eb *envBuilder) build() []string { func dockerComposeBuild(options Options) error { c, err := compose.NewProject(DockerComposeProjectName, options.Profile.Path(profileStackPath, SnapshotFile)) if err != nil { - return errors.Wrap(err, "could not create docker compose project") + return fmt.Errorf("could not create docker compose project: %w", err) } appConfig, err := install.Configuration() if err != nil { - return errors.Wrap(err, "can't read application configuration") + return fmt.Errorf("can't read application configuration: %w", err) } opts := compose.CommandOptions{ @@ -75,7 +73,7 @@ func dockerComposeBuild(options Options) error { } if err := c.Build(opts); err != nil { - return errors.Wrap(err, "running command failed") + return fmt.Errorf("running command failed: %w", err) } return nil } @@ -83,12 +81,12 @@ func dockerComposeBuild(options Options) error { func dockerComposePull(options Options) error { c, err := compose.NewProject(DockerComposeProjectName, options.Profile.Path(profileStackPath, SnapshotFile)) if err != nil { - return errors.Wrap(err, "could not create docker compose project") + return fmt.Errorf("could not create docker compose project: %w", err) } appConfig, err := install.Configuration() if err != nil { - return errors.Wrap(err, "can't read application configuration") + return fmt.Errorf("can't read application configuration: %w", err) } opts := compose.CommandOptions{ @@ -101,7 +99,7 @@ func dockerComposePull(options Options) error { } if err := c.Pull(opts); err != nil { - return errors.Wrap(err, "running command failed") + return fmt.Errorf("running command failed: %w", err) } return nil } @@ -109,7 +107,7 @@ func dockerComposePull(options Options) error { func dockerComposeUp(options Options) error { c, err := compose.NewProject(DockerComposeProjectName, options.Profile.Path(profileStackPath, SnapshotFile)) if err != nil { - return errors.Wrap(err, "could not create docker compose project") + return fmt.Errorf("could not create docker compose project: %w", err) } var args []string @@ -119,7 +117,7 @@ func dockerComposeUp(options Options) error { appConfig, err := install.Configuration() if err != nil { - return errors.Wrap(err, "can't read application configuration") + return fmt.Errorf("can't read application configuration: %w", err) } opts := compose.CommandOptions{ @@ -133,7 +131,7 @@ func dockerComposeUp(options Options) error { } if err := c.Up(opts); err != nil { - return errors.Wrap(err, "running command failed") + return fmt.Errorf("running command failed: %w", err) } return nil } @@ -141,12 +139,12 @@ func dockerComposeUp(options Options) error { func dockerComposeDown(options Options) error { c, err := compose.NewProject(DockerComposeProjectName, options.Profile.Path(profileStackPath, SnapshotFile)) if err != nil { - return errors.Wrap(err, "could not create docker compose project") + return fmt.Errorf("could not create docker compose project: %w", err) } appConfig, err := install.Configuration() if err != nil { - return errors.Wrap(err, "can't read application configuration") + return fmt.Errorf("can't read application configuration: %w", err) } downOptions := compose.CommandOptions{ @@ -159,7 +157,7 @@ func dockerComposeDown(options Options) error { ExtraArgs: []string{"--volumes", "--remove-orphans"}, } if err := c.Down(downOptions); err != nil { - return errors.Wrap(err, "running command failed") + return fmt.Errorf("running command failed: %w", err) } return nil } diff --git a/internal/stack/dump.go b/internal/stack/dump.go index 116cb03a1..cb079ff39 100644 --- a/internal/stack/dump.go +++ b/internal/stack/dump.go @@ -9,8 +9,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/profile" ) @@ -34,7 +32,7 @@ func Dump(options DumpOptions) (string, error) { err := dumpStackLogs(options) if err != nil { - return "", errors.Wrap(err, "can't dump Elastic stack logs") + return "", fmt.Errorf("can't dump Elastic stack logs: %w", err) } return options.Output, nil } @@ -43,13 +41,13 @@ func dumpStackLogs(options DumpOptions) error { logger.Debugf("Dump stack logs (location: %s)", options.Output) err := os.RemoveAll(options.Output) if err != nil { - return errors.Wrap(err, "can't remove output location") + return fmt.Errorf("can't remove output location: %w", err) } logsPath := filepath.Join(options.Output, "logs") err = os.MkdirAll(logsPath, 0755) if err != nil { - return errors.Wrapf(err, "can't create output location (path: %s)", logsPath) + return fmt.Errorf("can't create output location (path: %s): %w", logsPath, err) } for _, serviceName := range observedServices { diff --git a/internal/stack/errors.go b/internal/stack/errors.go index 91a8bad85..3e6a2b9e1 100644 --- a/internal/stack/errors.go +++ b/internal/stack/errors.go @@ -4,7 +4,9 @@ package stack -import "fmt" +import ( + "fmt" +) // UndefinedEnvError formats an error reported for undefined variable. func UndefinedEnvError(envName string) error { diff --git a/internal/stack/logs.go b/internal/stack/logs.go index 41f10c456..084a88676 100644 --- a/internal/stack/logs.go +++ b/internal/stack/logs.go @@ -5,10 +5,9 @@ package stack import ( + "fmt" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/compose" "github.com/elastic/elastic-package/internal/docker" "github.com/elastic/elastic-package/internal/install" @@ -18,14 +17,14 @@ import ( func dockerComposeLogs(serviceName string, profile *profile.Profile) ([]byte, error) { appConfig, err := install.Configuration() if err != nil { - return nil, errors.Wrap(err, "can't read application configuration") + return nil, fmt.Errorf("can't read application configuration: %w", err) } snapshotFile := profile.Path(profileStackPath, SnapshotFile) p, err := compose.NewProject(DockerComposeProjectName, snapshotFile) if err != nil { - return nil, errors.Wrap(err, "could not create docker compose project") + return nil, fmt.Errorf("could not create docker compose project: %w", err) } opts := compose.CommandOptions{ @@ -39,7 +38,7 @@ func dockerComposeLogs(serviceName string, profile *profile.Profile) ([]byte, er out, err := p.Logs(opts) if err != nil { - return nil, errors.Wrap(err, "running command failed") + return nil, fmt.Errorf("running command failed: %w", err) } return out, nil } @@ -53,14 +52,14 @@ func copyDockerInternalLogs(serviceName, outputPath string) error { p, err := compose.NewProject(DockerComposeProjectName) if err != nil { - return errors.Wrap(err, "could not create docker compose project") + return fmt.Errorf("could not create docker compose project: %w", err) } outputPath = filepath.Join(outputPath, serviceName+"-internal") serviceContainer := p.ContainerName(serviceName) err = docker.Copy(serviceContainer, "/usr/share/elastic-agent/state/data/logs/", outputPath) if err != nil { - return errors.Wrap(err, "docker copy failed") + return fmt.Errorf("docker copy failed: %w", err) } return nil } diff --git a/internal/stack/network.go b/internal/stack/network.go index 7e0877b00..d60a8593e 100644 --- a/internal/stack/network.go +++ b/internal/stack/network.go @@ -7,15 +7,16 @@ package stack import ( "fmt" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/docker" ) // EnsureStackNetworkUp function verifies if stack network is up and running. func EnsureStackNetworkUp() error { _, err := docker.InspectNetwork(Network()) - return errors.Wrap(err, "network not available") + if err != nil { + return fmt.Errorf("network not available: %w", err) + } + return nil } // Network function returns the stack network name. diff --git a/internal/stack/options.go b/internal/stack/options.go index a1ed87782..1c8f2827d 100644 --- a/internal/stack/options.go +++ b/internal/stack/options.go @@ -4,7 +4,9 @@ package stack -import "github.com/elastic/elastic-package/internal/profile" +import ( + "github.com/elastic/elastic-package/internal/profile" +) // Options defines available image booting options. type Options struct { diff --git a/internal/stack/update.go b/internal/stack/update.go index 26188d641..924ead0c4 100644 --- a/internal/stack/update.go +++ b/internal/stack/update.go @@ -5,7 +5,7 @@ package stack import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/elastic-package/internal/docker" ) @@ -14,17 +14,17 @@ import ( func Update(options Options) error { err := applyResources(options.Profile, options.StackVersion) if err != nil { - return errors.Wrap(err, "creating stack files failed") + return fmt.Errorf("creating stack files failed: %w", err) } err = docker.Pull(PackageRegistryBaseImage) if err != nil { - return errors.Wrap(err, "pulling package-registry docker image failed") + return fmt.Errorf("pulling package-registry docker image failed: %w", err) } err = dockerComposePull(options) if err != nil { - return errors.Wrap(err, "updating docker images failed") + return fmt.Errorf("updating docker images failed: %w", err) } return nil } diff --git a/internal/storage/signature.go b/internal/storage/signature.go index 8143d244c..6e385cfea 100644 --- a/internal/storage/signature.go +++ b/internal/storage/signature.go @@ -6,6 +6,7 @@ package storage import ( "encoding/hex" + "errors" "fmt" "io" "sort" @@ -15,7 +16,6 @@ import ( "github.com/go-git/go-billy/v5" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" - "github.com/pkg/errors" ) // SignedPackageVersion represents a package version stored in the package-storage with a calculated signature. @@ -62,26 +62,26 @@ func (s SignedPackageVersions) ToPackageVersions() PackageVersions { func CalculatePackageSignatures(r *git.Repository, branch string, packageVersions PackageVersions) (SignedPackageVersions, error) { wt, err := r.Worktree() if err != nil { - return nil, errors.Wrap(err, "fetching worktree reference failed while calculating directory hash") + return nil, fmt.Errorf("fetching worktree reference failed while calculating directory hash: %w", err) } err = wt.Checkout(&git.CheckoutOptions{ Branch: plumbing.NewBranchReferenceName(branch), }) if err != nil { - return nil, errors.Wrapf(err, "changing branch failed (path: %s) while calculating directory hash", branch) + return nil, fmt.Errorf("changing branch failed (path: %s) while calculating directory hash: %w", branch, err) } var signedPackages SignedPackageVersions for _, version := range packageVersions { resources, err := walkPackageResources(wt.Filesystem, version.path()) if err != nil { - return nil, errors.Wrap(err, "failed to retrieve package paths while calculating directory hash") + return nil, fmt.Errorf("failed to retrieve package paths while calculating directory hash: %w", err) } signature, err := calculateFilesSignature(wt.Filesystem, resources) if err != nil { - return nil, errors.Wrapf(err, "failed to calculate the package signature for %s", version.Name) + return nil, fmt.Errorf("failed to calculate the package signature for %s: %w", version.Name, err) } signedPackages = append(signedPackages, NewSignedPackageVersion(version, signature)) } @@ -104,12 +104,12 @@ func calculateFilesSignature(filesystem billy.Filesystem, files []string) (strin f, err := filesystem.Open(file) if err != nil { - return "", errors.Wrapf(err, "reading file failed (path: %s)", file) + return "", fmt.Errorf("reading file failed (path: %s): %w", file, err) } c, err := io.ReadAll(f) if err != nil { - return "", errors.Wrapf(err, "reading file content failed (path: %s)", file) + return "", fmt.Errorf("reading file content failed (path: %s): %w", file, err) } fileHash := xxhash.New() diff --git a/internal/storage/storage.go b/internal/storage/storage.go index c519b62e3..deb45a1e1 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -12,7 +12,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/go-git/go-billy/v5" - "github.com/pkg/errors" ) const packagesDir = "packages" @@ -35,7 +34,7 @@ func NewPackageVersion(name, version string) (*PackageVersion, error) { func NewPackageVersionWithRoot(name, version, root string) (*PackageVersion, error) { packageVersion, err := semver.NewVersion(version) if err != nil { - return nil, errors.Wrapf(err, "reading package version failed (name: %s, version: %s)", name, version) + return nil, fmt.Errorf("reading package version failed (name: %s, version: %s): %w", name, version, err) } return &PackageVersion{ Name: name, @@ -118,7 +117,7 @@ func ParsePackageVersions(packageVersions []string) (PackageVersions, error) { revision, err := NewPackageVersion(s[0], s[1]) if err != nil { - return nil, errors.Wrapf(err, "can't create package version (%s)", s) + return nil, fmt.Errorf("can't create package version (%s): %w", s, err) } parsed = append(parsed, *revision) } @@ -128,7 +127,7 @@ func ParsePackageVersions(packageVersions []string) (PackageVersions, error) { func walkPackageResources(filesystem billy.Filesystem, path string) ([]string, error) { fis, err := filesystem.ReadDir(path) if err != nil { - return nil, errors.Wrapf(err, "reading directory failed (path: %s)", path) + return nil, fmt.Errorf("reading directory failed (path: %s): %w", path, err) } var collected []string @@ -137,7 +136,7 @@ func walkPackageResources(filesystem billy.Filesystem, path string) ([]string, e p := filepath.Join(path, fi.Name()) c, err := walkPackageResources(filesystem, p) if err != nil { - return nil, errors.Wrapf(err, "recursive walking failed (path: %s)", p) + return nil, fmt.Errorf("recursive walking failed (path: %s): %w", p, err) } collected = append(collected, c...) continue diff --git a/internal/surveyext/validators.go b/internal/surveyext/validators.go index abcf45e99..959125b7f 100644 --- a/internal/surveyext/validators.go +++ b/internal/surveyext/validators.go @@ -5,13 +5,13 @@ package surveyext import ( + "errors" "fmt" "os" "path/filepath" "regexp" "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" ) var ( @@ -54,7 +54,7 @@ func SemverValidator(val interface{}) error { } _, err := semver.NewVersion(ver) if err != nil { - return errors.Wrap(err, "can't parse value as proper semver") + return fmt.Errorf("can't parse value as proper semver: %w", err) } return nil } @@ -67,7 +67,7 @@ func ConstraintValidator(val interface{}) error { } _, err := semver.NewConstraint(c) if err != nil { - return errors.Wrap(err, "can't parse value as proper constraint") + return fmt.Errorf("can't parse value as proper constraint: %w", err) } return nil } diff --git a/internal/testrunner/coverageoutput.go b/internal/testrunner/coverageoutput.go index a616f871e..72658ade2 100644 --- a/internal/testrunner/coverageoutput.go +++ b/internal/testrunner/coverageoutput.go @@ -7,14 +7,13 @@ package testrunner import ( "bytes" "encoding/xml" + "errors" "fmt" "os" "path" "path/filepath" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/builder" "github.com/elastic/elastic-package/internal/multierror" ) @@ -48,7 +47,7 @@ func (tcd *testCoverageDetails) withTestResults(results []TestResult) *testCover tcd.dataStreams[result.DataStream] = append(tcd.dataStreams[result.DataStream], result.Name) if tcd.cobertura != nil && result.Coverage != nil { if err := tcd.cobertura.merge(result.Coverage); err != nil { - tcd.errors = append(tcd.errors, errors.Wrapf(err, "can't merge Cobertura coverage for test `%s`", result.Name)) + tcd.errors = append(tcd.errors, fmt.Errorf("can't merge Cobertura coverage for test `%s`: %w", result.Name, err)) } } else if tcd.cobertura == nil { tcd.cobertura = result.Coverage @@ -118,7 +117,7 @@ type CoberturaLine struct { func (c *CoberturaCoverage) bytes() ([]byte, error) { out, err := xml.MarshalIndent(&c, "", " ") if err != nil { - return nil, errors.Wrap(err, "unable to format test results as xUnit") + return nil, fmt.Errorf("unable to format test results as xUnit: %w", err) } var buffer bytes.Buffer @@ -145,7 +144,7 @@ func (c *CoberturaClass) merge(b *CoberturaClass) error { len(c.Methods[idx].Lines) == len(b.Methods[idx].Lines) } if !equal { - return errors.Errorf("merging incompatible classes: %+v != %+v", *c, *b) + return fmt.Errorf("merging incompatible classes: %+v != %+v", *c, *b) } // Update methods for idx := range b.Methods { @@ -238,7 +237,7 @@ func (c *CoberturaCoverage) merge(b *CoberturaCoverage) error { func WriteCoverage(packageRootPath, packageName string, testType TestType, results []TestResult) error { details, err := collectTestCoverageDetails(packageRootPath, packageName, testType, results) if err != nil { - return errors.Wrap(err, "can't collect test coverage details") + return fmt.Errorf("can't collect test coverage details: %w", err) } // Use provided cobertura report, or generate a custom report if not available. @@ -249,7 +248,7 @@ func WriteCoverage(packageRootPath, packageName string, testType TestType, resul err = writeCoverageReportFile(report, packageName) if err != nil { - return errors.Wrap(err, "can't write test coverage report file") + return fmt.Errorf("can't write test coverage report file: %w", err) } return nil } @@ -257,7 +256,7 @@ func WriteCoverage(packageRootPath, packageName string, testType TestType, resul func collectTestCoverageDetails(packageRootPath, packageName string, testType TestType, results []TestResult) (*testCoverageDetails, error) { withoutTests, err := findDataStreamsWithoutTests(packageRootPath, testType) if err != nil { - return nil, errors.Wrap(err, "can't find data streams without tests") + return nil, fmt.Errorf("can't find data streams without tests: %w", err) } details := newTestCoverageDetails(packageName, testType). @@ -277,7 +276,7 @@ func findDataStreamsWithoutTests(packageRootPath string, testType TestType) ([]s if errors.Is(err, os.ErrNotExist) { return noTests, nil // there are packages that don't have any data streams (fleet_server, security_detection_engine) } else if err != nil { - return nil, errors.Wrap(err, "can't list data streams directory") + return nil, fmt.Errorf("can't list data streams directory: %w", err) } for _, dataStream := range dataStreams { @@ -287,7 +286,7 @@ func findDataStreamsWithoutTests(packageRootPath string, testType TestType) ([]s expected, err := verifyTestExpected(packageRootPath, dataStream.Name(), testType) if err != nil { - return nil, errors.Wrap(err, "can't verify if test is expected") + return nil, fmt.Errorf("can't verify if test is expected: %w", err) } if !expected { continue @@ -300,7 +299,7 @@ func findDataStreamsWithoutTests(packageRootPath string, testType TestType) ([]s continue } if err != nil { - return nil, errors.Wrapf(err, "can't stat path: %s", dataStreamTestPath) + return nil, fmt.Errorf("can't stat path: %s: %w", dataStreamTestPath, err) } } return noTests, nil @@ -319,7 +318,7 @@ func verifyTestExpected(packageRootPath string, dataStreamName string, testType return false, nil } if err != nil { - return false, errors.Wrapf(err, "can't stat path: %s", ingestPipelinePath) + return false, fmt.Errorf("can't stat path: %s: %w", ingestPipelinePath, err) } return true, nil } @@ -367,14 +366,14 @@ func transformToCoberturaReport(details *testCoverageDetails) *CoberturaCoverage func writeCoverageReportFile(report *CoberturaCoverage, packageName string) error { dest, err := testCoverageReportsDir() if err != nil { - return errors.Wrap(err, "could not determine test coverage reports folder") + return fmt.Errorf("could not determine test coverage reports folder: %w", err) } // Create test coverage reports folder if it doesn't exist _, err = os.Stat(dest) if err != nil && errors.Is(err, os.ErrNotExist) { if err := os.MkdirAll(dest, 0755); err != nil { - return errors.Wrap(err, "could not create test coverage reports folder") + return fmt.Errorf("could not create test coverage reports folder: %w", err) } } @@ -383,11 +382,11 @@ func writeCoverageReportFile(report *CoberturaCoverage, packageName string) erro b, err := report.bytes() if err != nil { - return errors.Wrap(err, "can't marshal test coverage report") + return fmt.Errorf("can't marshal test coverage report: %w", err) } if err := os.WriteFile(filePath, b, 0644); err != nil { - return errors.Wrap(err, "could not write test coverage report file") + return fmt.Errorf("could not write test coverage report file: %w", err) } return nil } @@ -395,7 +394,7 @@ func writeCoverageReportFile(report *CoberturaCoverage, packageName string) erro func testCoverageReportsDir() (string, error) { buildDir, err := builder.BuildDirectory() if err != nil { - return "", errors.Wrap(err, "locating build directory failed") + return "", fmt.Errorf("locating build directory failed: %w", err) } return filepath.Join(buildDir, "test-coverage"), nil } diff --git a/internal/testrunner/errors.go b/internal/testrunner/errors.go index f96e9fcd3..1f59b86e7 100644 --- a/internal/testrunner/errors.go +++ b/internal/testrunner/errors.go @@ -4,7 +4,9 @@ package testrunner -import "fmt" +import ( + "fmt" +) // ErrTestCaseFailed represents a test case failure result type ErrTestCaseFailed struct { diff --git a/internal/testrunner/report_format.go b/internal/testrunner/report_format.go index 0a014eff5..3e506acb5 100644 --- a/internal/testrunner/report_format.go +++ b/internal/testrunner/report_format.go @@ -4,7 +4,9 @@ package testrunner -import "fmt" +import ( + "fmt" +) // TestReportFormat represents a test report format type TestReportFormat string diff --git a/internal/testrunner/reporters/formats/xunit.go b/internal/testrunner/reporters/formats/xunit.go index e2255b0b5..106e9c256 100644 --- a/internal/testrunner/reporters/formats/xunit.go +++ b/internal/testrunner/reporters/formats/xunit.go @@ -8,8 +8,6 @@ import ( "encoding/xml" "fmt" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/testrunner" ) @@ -138,7 +136,7 @@ func reportXUnitFormat(results []testrunner.TestResult) (string, error) { out, err := xml.MarshalIndent(&ts, "", " ") if err != nil { - return "", errors.Wrap(err, "unable to format test results as xUnit") + return "", fmt.Errorf("unable to format test results as xUnit: %w", err) } return xml.Header + string(out), nil diff --git a/internal/testrunner/reporters/outputs/file.go b/internal/testrunner/reporters/outputs/file.go index 232d71426..3a7a32b4c 100644 --- a/internal/testrunner/reporters/outputs/file.go +++ b/internal/testrunner/reporters/outputs/file.go @@ -5,13 +5,12 @@ package outputs import ( + "errors" "fmt" "os" "path/filepath" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/builder" "github.com/elastic/elastic-package/internal/testrunner" "github.com/elastic/elastic-package/internal/testrunner/reporters/formats" @@ -29,13 +28,13 @@ const ( func reportToFile(pkg, report string, format testrunner.TestReportFormat) error { dest, err := testReportsDir() if err != nil { - return errors.Wrap(err, "could not determine test reports folder") + return fmt.Errorf("could not determine test reports folder: %w", err) } // Create test reports folder if it doesn't exist _, err = os.Stat(dest) if err != nil && errors.Is(err, os.ErrNotExist) { if err := os.MkdirAll(dest, 0755); err != nil { - return errors.Wrap(err, "could not create test reports folder") + return fmt.Errorf("could not create test reports folder: %w", err) } } @@ -48,7 +47,7 @@ func reportToFile(pkg, report string, format testrunner.TestReportFormat) error filePath := filepath.Join(dest, fileName) if err := os.WriteFile(filePath, []byte(report+"\n"), 0644); err != nil { - return errors.Wrap(err, "could not write report file") + return fmt.Errorf("could not write report file: %w", err) } return nil @@ -58,7 +57,7 @@ func reportToFile(pkg, report string, format testrunner.TestReportFormat) error func testReportsDir() (string, error) { buildDir, err := builder.BuildDirectory() if err != nil { - return "", errors.Wrap(err, "locating build directory failed") + return "", fmt.Errorf("locating build directory failed: %w", err) } return filepath.Join(buildDir, "test-results"), nil } diff --git a/internal/testrunner/runners/asset/runner.go b/internal/testrunner/runners/asset/runner.go index 58579c5d3..bbb997d16 100644 --- a/internal/testrunner/runners/asset/runner.go +++ b/internal/testrunner/runners/asset/runner.go @@ -8,8 +8,6 @@ import ( "fmt" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/kibana" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/packages" @@ -66,7 +64,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { testConfig, err := newConfig(r.testFolder.Path) if err != nil { - return result.WithError(errors.Wrap(err, "unable to load asset loading test config file")) + return result.WithError(fmt.Errorf("unable to load asset loading test config file: %w", err)) } @@ -80,7 +78,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { logger.Debug("installing package...") kibanaClient, err := kibana.NewClient() if err != nil { - return result.WithError(errors.Wrap(err, "could not create kibana client")) + return result.WithError(fmt.Errorf("could not create kibana client: %w", err)) } packageInstaller, err := installer.NewForPackage(installer.Options{ Kibana: kibanaClient, @@ -88,11 +86,11 @@ func (r *runner) run() ([]testrunner.TestResult, error) { SkipValidation: true, }) if err != nil { - return result.WithError(errors.Wrap(err, "can't create the package installer")) + return result.WithError(fmt.Errorf("can't create the package installer: %w", err)) } installedPackage, err := packageInstaller.Install() if err != nil { - return result.WithError(errors.Wrap(err, "can't install the package")) + return result.WithError(fmt.Errorf("can't install the package: %w", err)) } r.removePackageHandler = func() error { @@ -114,7 +112,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { expectedAssets, err := packages.LoadPackageAssets(r.packageRootPath) if err != nil { - return result.WithError(errors.Wrap(err, "could not load expected package assets")) + return result.WithError(fmt.Errorf("could not load expected package assets: %w", err)) } results := make([]testrunner.TestResult, 0, len(expectedAssets)) diff --git a/internal/testrunner/runners/asset/test_config.go b/internal/testrunner/runners/asset/test_config.go index 447931fe3..33d67efca 100644 --- a/internal/testrunner/runners/asset/test_config.go +++ b/internal/testrunner/runners/asset/test_config.go @@ -5,12 +5,13 @@ package asset import ( + "errors" + "fmt" "os" "path/filepath" "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/testrunner" ) @@ -30,16 +31,16 @@ func newConfig(assetTestFolderPath string) (*testConfig, error) { data, err := os.ReadFile(configFilePath) if err != nil { - return nil, errors.Wrapf(err, "could not load asset loading test configuration file: %s", configFilePath) + return nil, fmt.Errorf("could not load asset loading test configuration file: %s: %w", configFilePath, err) } var c testConfig cfg, err := yaml.NewConfig(data, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "unable to load asset loading test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to load asset loading test configuration file: %s: %w", configFilePath, err) } if err := cfg.Unpack(&c); err != nil { - return nil, errors.Wrapf(err, "unable to unpack asset loading test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to unpack asset loading test configuration file: %s: %w", configFilePath, err) } return &c, nil diff --git a/internal/testrunner/runners/pipeline/coverage.go b/internal/testrunner/runners/pipeline/coverage.go index b79c07f4a..8735f96b3 100644 --- a/internal/testrunner/runners/pipeline/coverage.go +++ b/internal/testrunner/runners/pipeline/coverage.go @@ -5,12 +5,12 @@ package pipeline import ( + "errors" + "fmt" "path/filepath" "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/elasticsearch/ingest" "github.com/elastic/elastic-package/internal/packages" "github.com/elastic/elastic-package/internal/testrunner" @@ -20,7 +20,7 @@ import ( func GetPipelineCoverage(options testrunner.TestOptions, pipelines []ingest.Pipeline) (*testrunner.CoberturaCoverage, error) { dataStreamPath, found, err := packages.FindDataStreamRootForPath(options.TestFolder.Path) if err != nil { - return nil, errors.Wrap(err, "locating data_stream root failed") + return nil, fmt.Errorf("locating data_stream root failed: %w", err) } if !found { return nil, errors.New("data stream root not found") @@ -30,7 +30,7 @@ func GetPipelineCoverage(options testrunner.TestOptions, pipelines []ingest.Pipe // These stats contain hit counts for all main processors in a pipeline. stats, err := ingest.GetPipelineStats(options.API, pipelines) if err != nil { - return nil, errors.Wrap(err, "error fetching pipeline stats for code coverage calculations") + return nil, fmt.Errorf("error fetching pipeline stats for code coverage calculations: %w", err) } // Construct the Cobertura report. @@ -58,7 +58,7 @@ func GetPipelineCoverage(options testrunner.TestOptions, pipelines []ingest.Pipe for _, pipeline := range pipelines { covered, class, err := coverageForSinglePipeline(pipeline, stats, basePath, dataStreamPath) if err != nil { - return nil, errors.Wrapf(err, "error calculating coverage for pipeline '%s'", pipeline.Filename()) + return nil, fmt.Errorf("error calculating coverage for pipeline '%s': %w", pipeline.Filename(), err) } pkg.Classes = append(pkg.Classes, class) coverage.LinesValid += int64(len(class.Methods)) @@ -76,19 +76,19 @@ func coverageForSinglePipeline(pipeline ingest.Pipeline, stats ingest.PipelineSt pstats, found := stats[pipeline.Name] if !found { - return 0, nil, errors.Errorf("pipeline '%s' not installed in Elasticsearch", pipeline.Name) + return 0, nil, fmt.Errorf("pipeline '%s' not installed in Elasticsearch", pipeline.Name) } // Ensure there is no inconsistency in the list of processors in stats vs obtained from source. if len(src) != len(pstats.Processors) { - return 0, nil, errors.Errorf("processor count mismatch for %s (src:%d stats:%d)", pipeline.Filename(), len(src), len(pstats.Processors)) + return 0, nil, fmt.Errorf("processor count mismatch for %s (src:%d stats:%d)", pipeline.Filename(), len(src), len(pstats.Processors)) } for idx, st := range pstats.Processors { // Check that we have the expected type of processor, except for `compound` processors. // Elasticsearch will return a `compound` processor in the case of `foreach` and // any processor that defines `on_failure` processors. if st.Type != "compound" && st.Type != src[idx].Type { - return 0, nil, errors.Errorf("processor type mismatch for %s processor %d (src:%s stats:%s)", pipeline.Filename(), idx, src[idx].Type, st.Type) + return 0, nil, fmt.Errorf("processor type mismatch for %s processor %d (src:%s stats:%s)", pipeline.Filename(), idx, src[idx].Type, st.Type) } } @@ -104,7 +104,7 @@ func coverageForSinglePipeline(pipeline ingest.Pipeline, stats ingest.PipelineSt pipelinePath := filepath.Join(dataStreamPath, "elasticsearch", "ingest_pipeline", pipeline.Filename()) pipelineRelPath, err := filepath.Rel(basePath, pipelinePath) if err != nil { - return 0, nil, errors.Wrapf(err, "cannot create relative path to pipeline file. Package root: '%s', pipeline path: '%s'", basePath, pipelinePath) + return 0, nil, fmt.Errorf("cannot create relative path to pipeline file. Package root: '%s', pipeline path: '%s': %w", basePath, pipelinePath, err) } // Report every pipeline as a "class". diff --git a/internal/testrunner/runners/pipeline/runner.go b/internal/testrunner/runners/pipeline/runner.go index 8c97da3d3..44d0eed49 100644 --- a/internal/testrunner/runners/pipeline/runner.go +++ b/internal/testrunner/runners/pipeline/runner.go @@ -6,6 +6,7 @@ package pipeline import ( "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -13,8 +14,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/common" "github.com/elastic/elastic-package/internal/elasticsearch/ingest" "github.com/elastic/elastic-package/internal/fields" @@ -63,7 +62,7 @@ func (r *runner) TearDown() error { } if err := ingest.UninstallPipelines(r.options.API, r.pipelines); err != nil { - return errors.Wrap(err, "uninstalling ingest pipelines failed") + return fmt.Errorf("uninstalling ingest pipelines failed: %w", err) } return nil } @@ -77,12 +76,12 @@ func (r *runner) CanRunPerDataStream() bool { func (r *runner) run() ([]testrunner.TestResult, error) { testCaseFiles, err := r.listTestCaseFiles() if err != nil { - return nil, errors.Wrap(err, "listing test case definitions failed") + return nil, fmt.Errorf("listing test case definitions failed: %w", err) } dataStreamPath, found, err := packages.FindDataStreamRootForPath(r.options.TestFolder.Path) if err != nil { - return nil, errors.Wrap(err, "locating data_stream root failed") + return nil, fmt.Errorf("locating data_stream root failed: %w", err) } if !found { return nil, errors.New("data stream root not found") @@ -91,17 +90,17 @@ func (r *runner) run() ([]testrunner.TestResult, error) { var entryPipeline string entryPipeline, r.pipelines, err = ingest.InstallDataStreamPipelines(r.options.API, dataStreamPath) if err != nil { - return nil, errors.Wrap(err, "installing ingest pipelines failed") + return nil, fmt.Errorf("installing ingest pipelines failed: %w", err) } pkgManifest, err := packages.ReadPackageManifestFromPackageRoot(r.options.PackageRootPath) if err != nil { - return nil, errors.Wrap(err, "failed to read manifest") + return nil, fmt.Errorf("failed to read manifest: %w", err) } dsManifest, err := packages.ReadDataStreamManifestFromPackageRoot(r.options.PackageRootPath, r.options.TestFolder.DataStream) if err != nil { - return nil, errors.Wrap(err, "failed to read data stream manifest") + return nil, fmt.Errorf("failed to read data stream manifest: %w", err) } expectedDataset := dsManifest.Dataset @@ -122,7 +121,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { // See https://github.com/elastic/elastic-package/pull/717. tc, err := r.loadTestCaseFile(testCaseFile) if err != nil { - err := errors.Wrap(err, "loading test case failed") + err := fmt.Errorf("loading test case failed: %w", err) tr.ErrorMsg = err.Error() results = append(results, tr) continue @@ -141,7 +140,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { processedEvents, err := ingest.SimulatePipeline(r.options.API, entryPipeline, tc.events) if err != nil { - err := errors.Wrap(err, "simulating pipeline processing failed") + err := fmt.Errorf("simulating pipeline processing failed: %w", err) tr.ErrorMsg = err.Error() results = append(results, tr) continue @@ -160,7 +159,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { fields.WithEnabledImportAllECSSChema(true), ) if err != nil { - return nil, errors.Wrapf(err, "creating fields validator for data stream failed (path: %s, test case file: %s)", dataStreamPath, testCaseFile) + return nil, fmt.Errorf("creating fields validator for data stream failed (path: %s, test case file: %s): %w", dataStreamPath, testCaseFile, err) } // TODO: Add tests to cover regressive use of json.Unmarshal in verifyResults. @@ -174,7 +173,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { continue } if err != nil { - err := errors.Wrap(err, "verifying test result failed") + err := fmt.Errorf("verifying test result failed: %w", err) tr.ErrorMsg = err.Error() results = append(results, tr) continue @@ -183,7 +182,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { if r.options.WithCoverage { tr.Coverage, err = GetPipelineCoverage(r.options, r.pipelines) if err != nil { - return nil, errors.Wrap(err, "error calculating pipeline coverage") + return nil, fmt.Errorf("error calculating pipeline coverage: %w", err) } } results = append(results, tr) @@ -195,7 +194,7 @@ func (r *runner) run() ([]testrunner.TestResult, error) { func (r *runner) listTestCaseFiles() ([]string, error) { fis, err := os.ReadDir(r.options.TestFolder.Path) if err != nil { - return nil, errors.Wrapf(err, "reading pipeline tests failed (path: %s)", r.options.TestFolder.Path) + return nil, fmt.Errorf("reading pipeline tests failed (path: %s): %w", r.options.TestFolder.Path, err) } var files []string @@ -213,12 +212,12 @@ func (r *runner) loadTestCaseFile(testCaseFile string) (*testCase, error) { testCasePath := filepath.Join(r.options.TestFolder.Path, testCaseFile) testCaseData, err := os.ReadFile(testCasePath) if err != nil { - return nil, errors.Wrapf(err, "reading input file failed (testCasePath: %s)", testCasePath) + return nil, fmt.Errorf("reading input file failed (testCasePath: %s): %w", testCasePath, err) } config, err := readConfigForTestCase(testCasePath) if err != nil { - return nil, errors.Wrapf(err, "reading config for test case failed (testCasePath: %s)", testCasePath) + return nil, fmt.Errorf("reading config for test case failed (testCasePath: %s): %w", testCasePath, err) } if config.Skip != nil { @@ -235,12 +234,12 @@ func (r *runner) loadTestCaseFile(testCaseFile string) (*testCase, error) { case ".json": entries, err = readTestCaseEntriesForEvents(testCaseData) if err != nil { - return nil, errors.Wrapf(err, "reading test case entries for events failed (testCasePath: %s)", testCasePath) + return nil, fmt.Errorf("reading test case entries for events failed (testCasePath: %s): %w", testCasePath, err) } case ".log": entries, err = readTestCaseEntriesForRawInput(testCaseData, config) if err != nil { - return nil, errors.Wrapf(err, "creating test case entries for raw input failed (testCasePath: %s)", testCasePath) + return nil, fmt.Errorf("creating test case entries for raw input failed (testCasePath: %s): %w", testCasePath, err) } default: return nil, fmt.Errorf("unsupported extension for test case file (ext: %s)", ext) @@ -248,7 +247,7 @@ func (r *runner) loadTestCaseFile(testCaseFile string) (*testCase, error) { tc, err := createTestCase(testCaseFile, entries, config) if err != nil { - return nil, errors.Wrapf(err, "can't create test case (testCasePath: %s)", testCasePath) + return nil, fmt.Errorf("can't create test case (testCasePath: %s): %w", testCasePath, err) } return tc, nil } @@ -261,7 +260,7 @@ func (r *runner) verifyResults(testCaseFile string, config *testConfig, result * // See https://github.com/elastic/elastic-package/pull/717. err := writeTestResult(testCasePath, result) if err != nil { - return errors.Wrap(err, "writing test result failed") + return fmt.Errorf("writing test result failed: %w", err) } } @@ -270,7 +269,7 @@ func (r *runner) verifyResults(testCaseFile string, config *testConfig, result * return err } if err != nil { - return errors.Wrap(err, "comparing test results failed") + return fmt.Errorf("comparing test results failed: %w", err) } result = stripEmptyTestResults(result) @@ -310,13 +309,13 @@ func verifyDynamicFields(result *testResult, config *testConfig) error { var m common.MapStr err := jsonUnmarshalUsingNumber(event, &m) if err != nil { - return errors.Wrap(err, "can't unmarshal event") + return fmt.Errorf("can't unmarshal event: %w", err) } for key, pattern := range config.DynamicFields { val, err := m.GetValue(key) if err != nil && err != common.ErrKeyNotFound { - return errors.Wrap(err, "can't remove dynamic field") + return fmt.Errorf("can't remove dynamic field: %w", err) } valStr, ok := val.(string) @@ -326,7 +325,7 @@ func verifyDynamicFields(result *testResult, config *testConfig) error { matched, err := regexp.MatchString(pattern, valStr) if err != nil { - return errors.Wrap(err, "pattern matching for dynamic field failed") + return fmt.Errorf("pattern matching for dynamic field failed: %w", err) } if !matched { @@ -377,7 +376,7 @@ func checkErrorMessage(event json.RawMessage) error { } err := jsonUnmarshalUsingNumber(event, &pipelineError) if err != nil { - return errors.Wrapf(err, "can't unmarshal event to check pipeline error: %#q", event) + return fmt.Errorf("can't unmarshal event to check pipeline error: %#q: %w", event, err) } switch m := pipelineError.Error.Message.(type) { diff --git a/internal/testrunner/runners/pipeline/test_case.go b/internal/testrunner/runners/pipeline/test_case.go index 296b4d5bd..3b261a4b7 100644 --- a/internal/testrunner/runners/pipeline/test_case.go +++ b/internal/testrunner/runners/pipeline/test_case.go @@ -8,12 +8,11 @@ import ( "bufio" "bytes" "encoding/json" + "fmt" "regexp" "strings" "github.com/elastic/elastic-package/internal/common" - - "github.com/pkg/errors" ) type testCase struct { @@ -30,7 +29,7 @@ func readTestCaseEntriesForEvents(inputData []byte) ([]json.RawMessage, error) { var tcd testCaseDefinition err := jsonUnmarshalUsingNumber(inputData, &tcd) if err != nil { - return nil, errors.Wrap(err, "unmarshalling input data failed") + return nil, fmt.Errorf("unmarshalling input data failed: %w", err) } return tcd.Events, nil } @@ -38,7 +37,7 @@ func readTestCaseEntriesForEvents(inputData []byte) ([]json.RawMessage, error) { func readTestCaseEntriesForRawInput(inputData []byte, config *testConfig) ([]json.RawMessage, error) { entries, err := readRawInputEntries(inputData, config) if err != nil { - return nil, errors.Wrap(err, "reading raw input entries failed") + return nil, fmt.Errorf("reading raw input entries failed: %w", err) } var events []json.RawMessage @@ -48,7 +47,7 @@ func readTestCaseEntriesForRawInput(inputData []byte, config *testConfig) ([]jso m, err := json.Marshal(&event) if err != nil { - return nil, errors.Wrap(err, "marshalling mocked event failed") + return nil, fmt.Errorf("marshalling mocked event failed: %w", err) } events = append(events, m) } @@ -61,19 +60,19 @@ func createTestCase(filename string, entries []json.RawMessage, config *testConf var m common.MapStr err := jsonUnmarshalUsingNumber(entry, &m) if err != nil { - return nil, errors.Wrap(err, "can't unmarshal test case entry") + return nil, fmt.Errorf("can't unmarshal test case entry: %w", err) } for k, v := range config.Fields { _, err = m.Put(k, v) if err != nil { - return nil, errors.Wrap(err, "can't set custom field") + return nil, fmt.Errorf("can't set custom field: %w", err) } } event, err := json.Marshal(&m) if err != nil { - return nil, errors.Wrap(err, "marshalling event failed") + return nil, fmt.Errorf("marshalling event failed: %w", err) } events = append(events, event) } @@ -96,7 +95,7 @@ func readRawInputEntries(inputData []byte, c *testConfig) ([]string, error) { if c.Multiline != nil && c.Multiline.FirstLinePattern != "" { matched, err := regexp.MatchString(c.Multiline.FirstLinePattern, line) if err != nil { - return nil, errors.Wrapf(err, "regexp matching failed (pattern: %s)", c.Multiline.FirstLinePattern) + return nil, fmt.Errorf("regexp matching failed (pattern: %s): %w", c.Multiline.FirstLinePattern, err) } if matched { @@ -118,7 +117,7 @@ func readRawInputEntries(inputData []byte, c *testConfig) ([]string, error) { } err := scanner.Err() if err != nil { - return nil, errors.Wrap(err, "reading raw input test file failed") + return nil, fmt.Errorf("reading raw input test file failed: %w", err) } lastEntry := builder.String() diff --git a/internal/testrunner/runners/pipeline/test_config.go b/internal/testrunner/runners/pipeline/test_config.go index e3f46f9a3..84f6029ef 100644 --- a/internal/testrunner/runners/pipeline/test_config.go +++ b/internal/testrunner/runners/pipeline/test_config.go @@ -5,12 +5,12 @@ package pipeline import ( + "errors" "fmt" "os" "path/filepath" "github.com/elastic/go-ucfg/yaml" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/testrunner" ) @@ -44,24 +44,24 @@ func readConfigForTestCase(testCasePath string) (*testConfig, error) { var c testConfig cfg, err := yaml.NewConfigWithFile(commonConfigPath) if err != nil && !errors.Is(err, os.ErrNotExist) { - return nil, errors.Wrapf(err, "can't load common configuration: %s", commonConfigPath) + return nil, fmt.Errorf("can't load common configuration: %s: %w", commonConfigPath, err) } if err == nil { if err := cfg.Unpack(&c); err != nil { - return nil, errors.Wrapf(err, "can't unpack test configuration: %s", commonConfigPath) + return nil, fmt.Errorf("can't unpack test configuration: %s: %w", commonConfigPath, err) } } configPath := filepath.Join(testCaseDir, expectedTestConfigFile(testCaseFile, configTestSuffixYAML)) cfg, err = yaml.NewConfigWithFile(configPath) if err != nil && !errors.Is(err, os.ErrNotExist) { - return nil, errors.Wrapf(err, "can't load test configuration: %s", configPath) + return nil, fmt.Errorf("can't load test configuration: %s: %w", configPath, err) } if err == nil { if err := cfg.Unpack(&c); err != nil { - return nil, errors.Wrapf(err, "can't unpack test configuration: %s", configPath) + return nil, fmt.Errorf("can't unpack test configuration: %s: %w", configPath, err) } } return &c, nil diff --git a/internal/testrunner/runners/pipeline/test_result.go b/internal/testrunner/runners/pipeline/test_result.go index f8bd1488c..29c9fb838 100644 --- a/internal/testrunner/runners/pipeline/test_result.go +++ b/internal/testrunner/runners/pipeline/test_result.go @@ -7,13 +7,14 @@ package pipeline import ( "bytes" "encoding/json" + "errors" "fmt" "io" "os" "path/filepath" "github.com/google/go-cmp/cmp" - "github.com/pkg/errors" + "github.com/pmezard/go-difflib/difflib" "github.com/elastic/elastic-package/internal/common" @@ -36,11 +37,11 @@ func writeTestResult(testCasePath string, result *testResult) error { data, err := marshalTestResultDefinition(result) if err != nil { - return errors.Wrap(err, "marshalling test result failed") + return fmt.Errorf("marshalling test result failed: %w", err) } err = os.WriteFile(filepath.Join(testCaseDir, expectedTestResultFile(testCaseFile)), data, 0644) if err != nil { - return errors.Wrap(err, "writing test result failed") + return fmt.Errorf("writing test result failed: %w", err) } return nil } @@ -48,27 +49,27 @@ func writeTestResult(testCasePath string, result *testResult) error { func compareResults(testCasePath string, config *testConfig, result *testResult) error { resultsWithoutDynamicFields, err := adjustTestResult(result, config) if err != nil { - return errors.Wrap(err, "can't adjust test results") + return fmt.Errorf("can't adjust test results: %w", err) } actual, err := marshalTestResultDefinition(resultsWithoutDynamicFields) if err != nil { - return errors.Wrap(err, "marshalling actual test results failed") + return fmt.Errorf("marshalling actual test results failed: %w", err) } expectedResults, err := readExpectedTestResult(testCasePath, config) if err != nil { - return errors.Wrap(err, "reading expected test result failed") + return fmt.Errorf("reading expected test result failed: %w", err) } expected, err := marshalTestResultDefinition(expectedResults) if err != nil { - return errors.Wrap(err, "marshalling expected test results failed") + return fmt.Errorf("marshalling expected test results failed: %w", err) } report, err := diffJson(expected, actual) if err != nil { - return errors.Wrap(err, "comparing expected test result") + return fmt.Errorf("comparing expected test result: %w", err) } if report != "" { return testrunner.ErrTestCaseFailed{ @@ -144,17 +145,17 @@ func readExpectedTestResult(testCasePath string, config *testConfig) (*testResul path := filepath.Join(testCaseDir, expectedTestResultFile(testCaseFile)) data, err := os.ReadFile(path) if err != nil { - return nil, errors.Wrap(err, "reading test result file failed") + return nil, fmt.Errorf("reading test result file failed: %w", err) } u, err := unmarshalTestResult(data) if err != nil { - return nil, errors.Wrap(err, "unmarshalling expected test result failed") + return nil, fmt.Errorf("unmarshalling expected test result failed: %w", err) } adjusted, err := adjustTestResult(u, config) if err != nil { - return nil, errors.Wrap(err, "adjusting test result failed") + return nil, fmt.Errorf("adjusting test result failed: %w", err) } return adjusted, nil } @@ -175,19 +176,19 @@ func adjustTestResult(result *testResult, config *testConfig) (*testResult, erro var m common.MapStr err := jsonUnmarshalUsingNumber(event, &m) if err != nil { - return nil, errors.Wrapf(err, "can't unmarshal event: %s", string(event)) + return nil, fmt.Errorf("can't unmarshal event: %s: %w", string(event), err) } for key := range config.DynamicFields { err := m.Delete(key) if err != nil && err != common.ErrKeyNotFound { - return nil, errors.Wrap(err, "can't remove dynamic field") + return nil, fmt.Errorf("can't remove dynamic field: %w", err) } } b, err := json.Marshal(&m) if err != nil { - return nil, errors.Wrap(err, "can't marshal event") + return nil, fmt.Errorf("can't marshal event: %w", err) } stripped.events = append(stripped.events, b) @@ -199,7 +200,7 @@ func unmarshalTestResult(body []byte) (*testResult, error) { var trd testResultDefinition err := jsonUnmarshalUsingNumber(body, &trd) if err != nil { - return nil, errors.Wrap(err, "unmarshalling test result failed") + return nil, fmt.Errorf("unmarshalling test result failed: %w", err) } var tr testResult @@ -234,7 +235,7 @@ func marshalTestResultDefinition(result *testResult) ([]byte, error) { trd.Expected = result.events body, err := marshalNormalizedJSON(trd) if err != nil { - return nil, errors.Wrap(err, "marshalling test result definition failed") + return nil, fmt.Errorf("marshalling test result definition failed: %w", err) } return body, nil } diff --git a/internal/testrunner/runners/runners.go b/internal/testrunner/runners/runners.go index c0e129dc9..c1870d201 100644 --- a/internal/testrunner/runners/runners.go +++ b/internal/testrunner/runners/runners.go @@ -5,6 +5,7 @@ package runners import ( + // Registered test runners _ "github.com/elastic/elastic-package/internal/testrunner/runners/asset" _ "github.com/elastic/elastic-package/internal/testrunner/runners/pipeline" diff --git a/internal/testrunner/runners/static/runner.go b/internal/testrunner/runners/static/runner.go index 762b5f4c0..c9a917a92 100644 --- a/internal/testrunner/runners/static/runner.go +++ b/internal/testrunner/runners/static/runner.go @@ -5,11 +5,11 @@ package static import ( + "errors" + "fmt" "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/fields" "github.com/elastic/elastic-package/internal/logger" "github.com/elastic/elastic-package/internal/packages" @@ -55,7 +55,7 @@ func (r runner) run() ([]testrunner.TestResult, error) { testConfig, err := newConfig(r.options.TestFolder.Path) if err != nil { - return result.WithError(errors.Wrap(err, "unable to load asset loading test config file")) + return result.WithError(fmt.Errorf("unable to load asset loading test config file: %w", err)) } if testConfig != nil && testConfig.Skip != nil { @@ -67,7 +67,7 @@ func (r runner) run() ([]testrunner.TestResult, error) { pkgManifest, err := packages.ReadPackageManifestFromPackageRoot(r.options.PackageRootPath) if err != nil { - return result.WithError(errors.Wrap(err, "failed to read manifest")) + return result.WithError(fmt.Errorf("failed to read manifest: %w", err)) } return r.verifySampleEvent(pkgManifest), nil @@ -103,13 +103,13 @@ func (r runner) verifySampleEvent(pkgManifest *packages.PackageManifest) []testr fields.WithEnabledImportAllECSSChema(true), ) if err != nil { - results, _ := resultComposer.WithError(errors.Wrap(err, "creating fields validator for data stream failed")) + results, _ := resultComposer.WithError(fmt.Errorf("creating fields validator for data stream failed: %w", err)) return results } content, err := os.ReadFile(sampleEventPath) if err != nil { - results, _ := resultComposer.WithError(errors.Wrap(err, "can't read file")) + results, _ := resultComposer.WithError(fmt.Errorf("can't read file: %w", err)) return results } @@ -142,7 +142,7 @@ func (r runner) getSampleEventPath() (string, bool, error) { return "", false, nil } if err != nil { - return "", false, errors.Wrap(err, "stat file failed") + return "", false, fmt.Errorf("stat file failed: %w", err) } return sampleEventPath, true, nil } @@ -158,7 +158,7 @@ func (r runner) getExpectedDataset(pkgManifest *packages.PackageManifest) (strin dataStreamManifest, err := packages.ReadDataStreamManifestFromPackageRoot(r.options.PackageRootPath, dsName) if err != nil { - return "", errors.Wrap(err, "failed to read data stream manifest") + return "", fmt.Errorf("failed to read data stream manifest: %w", err) } if ds := dataStreamManifest.Dataset; ds != "" { return ds, nil diff --git a/internal/testrunner/runners/static/test_config.go b/internal/testrunner/runners/static/test_config.go index 3dae5ef4e..8110724ab 100644 --- a/internal/testrunner/runners/static/test_config.go +++ b/internal/testrunner/runners/static/test_config.go @@ -5,12 +5,13 @@ package static import ( + "errors" + "fmt" "os" "path/filepath" "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" - "github.com/pkg/errors" "github.com/elastic/elastic-package/internal/testrunner" ) @@ -30,17 +31,17 @@ func newConfig(staticTestFolderPath string) (*testConfig, error) { data, err := os.ReadFile(configFilePath) if err != nil { - return nil, errors.Wrapf(err, "could not load static test configuration file: %s", configFilePath) + return nil, fmt.Errorf("could not load static test configuration file: %s: %w", configFilePath, err) } cfg, err := yaml.NewConfig(data, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "unable to load static test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to load static test configuration file: %s: %w", configFilePath, err) } var c testConfig if err := cfg.Unpack(&c); err != nil { - return nil, errors.Wrapf(err, "unable to unpack static test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to unpack static test configuration file: %s: %w", configFilePath, err) } return &c, nil diff --git a/internal/testrunner/runners/system/servicedeployer/compose.go b/internal/testrunner/runners/system/servicedeployer/compose.go index 69c10fb36..4801d518e 100644 --- a/internal/testrunner/runners/system/servicedeployer/compose.go +++ b/internal/testrunner/runners/system/servicedeployer/compose.go @@ -10,8 +10,6 @@ import ( "path/filepath" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/builder" "github.com/elastic/elastic-package/internal/compose" "github.com/elastic/elastic-package/internal/docker" @@ -57,19 +55,19 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer p, err := compose.NewProject(service.project, service.ymlPaths...) if err != nil { - return nil, errors.Wrap(err, "could not create Docker Compose project for service") + return nil, fmt.Errorf("could not create Docker Compose project for service: %w", err) } // Verify the Elastic stack network err = stack.EnsureStackNetworkUp() if err != nil { - return nil, errors.Wrap(err, "Elastic stack network is not ready") + return nil, fmt.Errorf("stack network is not ready: %w", err) } // Clean service logs err = files.RemoveContent(outCtxt.Logs.Folder.Local) if err != nil { - return nil, errors.Wrap(err, "removing service logs failed") + return nil, fmt.Errorf("removing service logs failed: %w", err) } // Boot up service @@ -86,7 +84,7 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer } err = p.Up(opts) if err != nil { - return nil, errors.Wrap(err, "could not boot up service using Docker Compose") + return nil, fmt.Errorf("could not boot up service using Docker Compose: %w", err) } err = p.WaitForHealthy(opts) @@ -94,7 +92,7 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer processServiceContainerLogs(p, compose.CommandOptions{ Env: opts.Env, }, outCtxt.Name) - return nil, errors.Wrap(err, "service is unhealthy") + return nil, fmt.Errorf("service is unhealthy: %w", err) } // Build service container name @@ -103,7 +101,7 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer // Connect service network with stack network (for the purpose of metrics collection) err = docker.ConnectToNetwork(p.ContainerName(serviceName), stack.Network()) if err != nil { - return nil, errors.Wrapf(err, "can't attach service container to the stack network") + return nil, fmt.Errorf("can't attach service container to the stack network: %w", err) } logger.Debugf("adding service container %s internal ports to context", p.ContainerName(serviceName)) @@ -111,7 +109,7 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer Env: []string{fmt.Sprintf("%s=%s", serviceLogsDirEnv, outCtxt.Logs.Folder.Local)}, }) if err != nil { - return nil, errors.Wrap(err, "could not get Docker Compose configuration for service") + return nil, fmt.Errorf("could not get Docker Compose configuration for service: %w", err) } s := serviceComposeConfig.Services[serviceName] @@ -134,7 +132,7 @@ func (d *DockerComposeServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedSer func (s *dockerComposeDeployedService) Signal(signal string) error { p, err := compose.NewProject(s.project, s.ymlPaths...) if err != nil { - return errors.Wrap(err, "could not create Docker Compose project for service") + return fmt.Errorf("could not create Docker Compose project for service: %w", err) } opts := compose.CommandOptions{ @@ -147,7 +145,11 @@ func (s *dockerComposeDeployedService) Signal(signal string) error { opts.Services = append(opts.Services, s.ctxt.Name) } - return errors.Wrapf(p.Kill(opts), "could not send %q signal", signal) + err = p.Kill(opts) + if err != nil { + return fmt.Errorf("could not send %q signal: %w", signal, err) + } + return nil } // TearDown tears down the service. @@ -166,7 +168,7 @@ func (s *dockerComposeDeployedService) TearDown() error { p, err := compose.NewProject(s.project, s.ymlPaths...) if err != nil { - return errors.Wrap(err, "could not create Docker Compose project for service") + return fmt.Errorf("could not create Docker Compose project for service: %w", err) } opts := compose.CommandOptions{ @@ -180,7 +182,7 @@ func (s *dockerComposeDeployedService) TearDown() error { Env: opts.Env, ExtraArgs: []string{"--volumes"}, // Remove associated volumes. }); err != nil { - return errors.Wrap(err, "could not shut down service using Docker Compose") + return fmt.Errorf("could not shut down service using Docker Compose: %w", err) } return nil } @@ -217,20 +219,20 @@ func processServiceContainerLogs(p *compose.Project, opts compose.CommandOptions func writeServiceContainerLogs(serviceName string, content []byte) error { buildDir, err := builder.BuildDirectory() if err != nil { - return errors.Wrap(err, "locating build directory failed") + return fmt.Errorf("locating build directory failed: %w", err) } containerLogsDir := filepath.Join(buildDir, "container-logs") err = os.MkdirAll(containerLogsDir, 0755) if err != nil { - return errors.Wrapf(err, "can't create directory for service container logs (path: %s)", containerLogsDir) + return fmt.Errorf("can't create directory for service container logs (path: %s): %w", containerLogsDir, err) } containerLogsFilepath := filepath.Join(containerLogsDir, fmt.Sprintf("%s-%d.log", serviceName, time.Now().UnixNano())) logger.Infof("Write container logs to file: %s", containerLogsFilepath) err = os.WriteFile(containerLogsFilepath, content, 0644) if err != nil { - return errors.Wrapf(err, "can't write container logs to file (path: %s)", containerLogsFilepath) + return fmt.Errorf("can't write container logs to file (path: %s): %w", containerLogsFilepath, err) } return nil } diff --git a/internal/testrunner/runners/system/servicedeployer/custom_agent.go b/internal/testrunner/runners/system/servicedeployer/custom_agent.go index 02165d0e0..ff7c885a2 100644 --- a/internal/testrunner/runners/system/servicedeployer/custom_agent.go +++ b/internal/testrunner/runners/system/servicedeployer/custom_agent.go @@ -10,8 +10,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/compose" "github.com/elastic/elastic-package/internal/configuration/locations" "github.com/elastic/elastic-package/internal/docker" @@ -50,22 +48,22 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err appConfig, err := install.Configuration() if err != nil { - return nil, errors.Wrap(err, "can't read application configuration") + return nil, fmt.Errorf("can't read application configuration: %w", err) } kibanaClient, err := kibana.NewClient() if err != nil { - return nil, errors.Wrap(err, "can't create Kibana client") + return nil, fmt.Errorf("can't create Kibana client: %w", err) } stackVersion, err := kibanaClient.Version() if err != nil { - return nil, errors.Wrap(err, "can't read Kibana injected metadata") + return nil, fmt.Errorf("can't read Kibana injected metadata: %w", err) } caCertPath, ok := os.LookupEnv(stack.CACertificateEnv) if !ok { - return nil, errors.Wrapf(err, "can't locate CA certificate: %s environment variable not set", stack.CACertificateEnv) + return nil, fmt.Errorf("can't locate CA certificate: %s environment variable not set", stack.CACertificateEnv) } env := append( @@ -76,7 +74,7 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err configDir, err := d.installDockerfile() if err != nil { - return nil, errors.Wrap(err, "could not create resources for custom agent") + return nil, fmt.Errorf("could not create resources for custom agent: %w", err) } ymlPaths := []string{ @@ -97,19 +95,19 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err p, err := compose.NewProject(service.project, service.ymlPaths...) if err != nil { - return nil, errors.Wrap(err, "could not create Docker Compose project for service") + return nil, fmt.Errorf("could not create Docker Compose project for service: %w", err) } // Verify the Elastic stack network err = stack.EnsureStackNetworkUp() if err != nil { - return nil, errors.Wrap(err, "Elastic stack network is not ready") + return nil, fmt.Errorf("stack network is not ready: %w", err) } // Clean service logs err = files.RemoveContent(outCtxt.Logs.Folder.Local) if err != nil { - return nil, errors.Wrap(err, "removing service logs failed") + return nil, fmt.Errorf("removing service logs failed: %w", err) } inCtxt.Name = dockerCustomAgentName @@ -120,13 +118,13 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err } err = p.Up(opts) if err != nil { - return nil, errors.Wrap(err, "could not boot up service using Docker Compose") + return nil, fmt.Errorf("could not boot up service using Docker Compose: %w", err) } // Connect service network with stack network (for the purpose of metrics collection) err = docker.ConnectToNetwork(p.ContainerName(serviceName), stack.Network()) if err != nil { - return nil, errors.Wrapf(err, "can't attach service container to the stack network") + return nil, fmt.Errorf("can't attach service container to the stack network: %w", err) } err = p.WaitForHealthy(opts) @@ -134,7 +132,7 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err processServiceContainerLogs(p, compose.CommandOptions{ Env: opts.Env, }, outCtxt.Name) - return nil, errors.Wrap(err, "service is unhealthy") + return nil, fmt.Errorf("service is unhealthy: %w", err) } // Build service container name @@ -143,7 +141,7 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err logger.Debugf("adding service container %s internal ports to context", p.ContainerName(serviceName)) serviceComposeConfig, err := p.Config(compose.CommandOptions{Env: env}) if err != nil { - return nil, errors.Wrap(err, "could not get Docker Compose configuration for service") + return nil, fmt.Errorf("could not get Docker Compose configuration for service: %w", err) } s := serviceComposeConfig.Services[serviceName] @@ -167,19 +165,19 @@ func (d *CustomAgentDeployer) SetUp(inCtxt ServiceContext) (DeployedService, err func (d *CustomAgentDeployer) installDockerfile() (string, error) { locationManager, err := locations.NewLocationManager() if err != nil { - return "", errors.Wrap(err, "failed to find the configuration directory") + return "", fmt.Errorf("failed to find the configuration directory: %w", err) } customAgentDir := filepath.Join(locationManager.DeployerDir(), dockerCustomAgentDir) err = os.MkdirAll(customAgentDir, 0755) if err != nil { - return "", errors.Wrap(err, "failed to create directory for custom agent files") + return "", fmt.Errorf("failed to create directory for custom agent files: %w", err) } customAgentDockerfile := filepath.Join(customAgentDir, dockerCustomAgentDockerfile) err = os.WriteFile(customAgentDockerfile, dockerCustomAgentDockerfileContent, 0644) if err != nil { - return "", errors.Wrap(err, "failed to create docker compose file for custom agent") + return "", fmt.Errorf("failed to create docker compose file for custom agent: %w", err) } return customAgentDir, nil diff --git a/internal/testrunner/runners/system/servicedeployer/factory.go b/internal/testrunner/runners/system/servicedeployer/factory.go index bbd4ae02d..27f8f5e11 100644 --- a/internal/testrunner/runners/system/servicedeployer/factory.go +++ b/internal/testrunner/runners/system/servicedeployer/factory.go @@ -5,11 +5,10 @@ package servicedeployer import ( + "errors" "fmt" "os" "path/filepath" - - "github.com/pkg/errors" ) const devDeployDir = "_dev/deploy" @@ -27,12 +26,12 @@ type FactoryOptions struct { func Factory(options FactoryOptions) (ServiceDeployer, error) { devDeployPath, err := FindDevDeployPath(options) if err != nil { - return nil, errors.Wrapf(err, "can't find \"%s\" directory", devDeployDir) + return nil, fmt.Errorf("can't find \"%s\" directory: %w", devDeployDir, err) } serviceDeployerName, err := findServiceDeployer(devDeployPath) if err != nil { - return nil, errors.Wrap(err, "can't find any valid service deployer") + return nil, fmt.Errorf("can't find any valid service deployer: %w", err) } serviceDeployerPath := filepath.Join(devDeployPath, serviceDeployerName) @@ -47,14 +46,14 @@ func Factory(options FactoryOptions) (ServiceDeployer, error) { if _, err := os.Stat(dockerComposeYMLPath); err == nil { sv, err := useServiceVariant(devDeployPath, options.Variant) if err != nil { - return nil, errors.Wrap(err, "can't use service variant") + return nil, fmt.Errorf("can't use service variant: %w", err) } return NewDockerComposeServiceDeployer([]string{dockerComposeYMLPath}, sv) } case "agent": customAgentCfgYMLPath := filepath.Join(serviceDeployerPath, "custom-agent.yml") if _, err := os.Stat(customAgentCfgYMLPath); err != nil { - return nil, errors.Wrap(err, "can't find expected file custom-agent.yml") + return nil, fmt.Errorf("can't find expected file custom-agent.yml: %w", err) } return NewCustomAgentDeployer(customAgentCfgYMLPath) @@ -73,7 +72,7 @@ func FindDevDeployPath(options FactoryOptions) (string, error) { if err == nil { return dataStreamDevDeployPath, nil } else if !errors.Is(err, os.ErrNotExist) { - return "", errors.Wrapf(err, "stat failed for data stream (path: %s)", dataStreamDevDeployPath) + return "", fmt.Errorf("stat failed for data stream (path: %s): %w", dataStreamDevDeployPath, err) } packageDevDeployPath := filepath.Join(options.PackageRootPath, devDeployDir) @@ -81,7 +80,7 @@ func FindDevDeployPath(options FactoryOptions) (string, error) { if err == nil { return packageDevDeployPath, nil } else if !errors.Is(err, os.ErrNotExist) { - return "", errors.Wrapf(err, "stat failed for package (path: %s)", packageDevDeployPath) + return "", fmt.Errorf("stat failed for package (path: %s): %w", packageDevDeployPath, err) } return "", fmt.Errorf("\"%s\" directory doesn't exist", devDeployDir) } @@ -89,7 +88,7 @@ func FindDevDeployPath(options FactoryOptions) (string, error) { func findServiceDeployer(devDeployPath string) (string, error) { fis, err := os.ReadDir(devDeployPath) if err != nil { - return "", errors.Wrapf(err, "can't read directory (path: %s)", devDeployDir) + return "", fmt.Errorf("can't read directory (path: %s): %w", devDeployDir, err) } var folders []os.DirEntry diff --git a/internal/testrunner/runners/system/servicedeployer/kubernetes.go b/internal/testrunner/runners/system/servicedeployer/kubernetes.go index fcaf61e28..b43ac06dc 100644 --- a/internal/testrunner/runners/system/servicedeployer/kubernetes.go +++ b/internal/testrunner/runners/system/servicedeployer/kubernetes.go @@ -8,13 +8,13 @@ import ( "bytes" _ "embed" "encoding/base64" + "errors" + "fmt" "os" "path/filepath" "strings" "text/template" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/install" "github.com/elastic/elastic-package/internal/kibana" "github.com/elastic/elastic-package/internal/kind" @@ -39,7 +39,7 @@ func (s kubernetesDeployedService) TearDown() error { definitionPaths, err := findKubernetesDefinitions(s.definitionsDir) if err != nil { - return errors.Wrapf(err, "can't find Kubernetes definitions in given directory (path: %s)", s.definitionsDir) + return fmt.Errorf("can't find Kubernetes definitions in given directory (path: %s): %w", s.definitionsDir, err) } if len(definitionPaths) == 0 { @@ -49,7 +49,7 @@ func (s kubernetesDeployedService) TearDown() error { err = kubectl.Delete(definitionPaths) if err != nil { - return errors.Wrapf(err, "can't uninstall Kubernetes resources (path: %s)", s.definitionsDir) + return fmt.Errorf("can't uninstall Kubernetes resources (path: %s): %w", s.definitionsDir, err) } return nil } @@ -81,22 +81,22 @@ func NewKubernetesServiceDeployer(definitionsPath string) (*KubernetesServiceDep func (ksd KubernetesServiceDeployer) SetUp(ctxt ServiceContext) (DeployedService, error) { err := kind.VerifyContext() if err != nil { - return nil, errors.Wrap(err, "kind context verification failed") + return nil, fmt.Errorf("kind context verification failed: %w", err) } err = kind.ConnectToElasticStackNetwork() if err != nil { - return nil, errors.Wrap(err, "can't connect control plane to Elastic stack network") + return nil, fmt.Errorf("can't connect control plane to Elastic stack network: %w", err) } err = installElasticAgentInCluster() if err != nil { - return nil, errors.Wrap(err, "can't install Elastic-Agent in the Kubernetes cluster") + return nil, fmt.Errorf("can't install Elastic-Agent in the Kubernetes cluster: %w", err) } err = ksd.installCustomDefinitions() if err != nil { - return nil, errors.Wrap(err, "can't install custom definitions in the Kubernetes cluster") + return nil, fmt.Errorf("can't install custom definitions in the Kubernetes cluster: %w", err) } ctxt.Name = kind.ControlPlaneContainerName @@ -115,7 +115,7 @@ func (ksd KubernetesServiceDeployer) installCustomDefinitions() error { definitionPaths, err := findKubernetesDefinitions(ksd.definitionsDir) if err != nil { - return errors.Wrapf(err, "can't find Kubernetes definitions in given path: %s", ksd.definitionsDir) + return fmt.Errorf("can't find Kubernetes definitions in given path: %s: %w", ksd.definitionsDir, err) } if len(definitionPaths) == 0 { @@ -125,7 +125,7 @@ func (ksd KubernetesServiceDeployer) installCustomDefinitions() error { err = kubectl.Apply(definitionPaths) if err != nil { - return errors.Wrap(err, "can't install custom definitions") + return fmt.Errorf("can't install custom definitions: %w", err) } return nil } @@ -135,7 +135,7 @@ var _ ServiceDeployer = new(KubernetesServiceDeployer) func findKubernetesDefinitions(definitionsDir string) ([]string, error) { files, err := filepath.Glob(filepath.Join(definitionsDir, "*.yaml")) if err != nil { - return nil, errors.Wrapf(err, "can't read definitions directory (path: %s)", definitionsDir) + return nil, fmt.Errorf("can't read definitions directory (path: %s): %w", definitionsDir, err) } var definitionPaths []string @@ -148,22 +148,22 @@ func installElasticAgentInCluster() error { kibanaClient, err := kibana.NewClient() if err != nil { - return errors.Wrap(err, "can't create Kibana client") + return fmt.Errorf("can't create Kibana client: %w", err) } stackVersion, err := kibanaClient.Version() if err != nil { - return errors.Wrap(err, "can't read Kibana injected metadata") + return fmt.Errorf("can't read Kibana injected metadata: %w", err) } elasticAgentManagedYaml, err := getElasticAgentYAML(stackVersion.Version()) if err != nil { - return errors.Wrap(err, "can't retrieve Kubernetes file for Elastic Agent") + return fmt.Errorf("can't retrieve Kubernetes file for Elastic Agent: %w", err) } err = kubectl.ApplyStdin(elasticAgentManagedYaml) if err != nil { - return errors.Wrap(err, "can't install Elastic-Agent in Kubernetes cluster") + return fmt.Errorf("can't install Elastic-Agent in Kubernetes cluster: %w", err) } return nil } @@ -176,12 +176,12 @@ func getElasticAgentYAML(stackVersion string) ([]byte, error) { appConfig, err := install.Configuration() if err != nil { - return nil, errors.Wrap(err, "can't read application configuration") + return nil, fmt.Errorf("can't read application configuration: %w", err) } caCert, err := readCACertBase64() if err != nil { - return nil, errors.Wrap(err, "can't read certificate authority file") + return nil, fmt.Errorf("can't read certificate authority file: %w", err) } tmpl := template.Must(template.New("elastic-agent.yml").Parse(elasticAgentManagedYamlTmpl)) @@ -195,7 +195,7 @@ func getElasticAgentYAML(stackVersion string) ([]byte, error) { "elasticAgentTokenPolicyName": getTokenPolicyName(stackVersion), }) if err != nil { - return nil, errors.Wrap(err, "can't generate elastic agent manifest") + return nil, fmt.Errorf("can't generate elastic agent manifest: %w", err) } return elasticAgentYaml.Bytes(), nil @@ -204,7 +204,7 @@ func getElasticAgentYAML(stackVersion string) ([]byte, error) { func readCACertBase64() (string, error) { caCertPath, ok := os.LookupEnv(stack.CACertificateEnv) if !ok { - return "", errors.Errorf("%s not defined", stack.CACertificateEnv) + return "", fmt.Errorf("%s not defined", stack.CACertificateEnv) } d, err := os.ReadFile(caCertPath) diff --git a/internal/testrunner/runners/system/servicedeployer/terraform.go b/internal/testrunner/runners/system/servicedeployer/terraform.go index d64d40e45..1a6112522 100644 --- a/internal/testrunner/runners/system/servicedeployer/terraform.go +++ b/internal/testrunner/runners/system/servicedeployer/terraform.go @@ -12,8 +12,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/elastic/go-resource" "github.com/elastic/elastic-package/internal/compose" @@ -95,7 +93,7 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic configDir, err := tsd.installDockerfile() if err != nil { - return nil, errors.Wrap(err, "can't install Docker Compose definitions") + return nil, fmt.Errorf("can't install Docker Compose definitions: %w", err) } ymlPaths := []string{filepath.Join(configDir, terraformDeployerYml)} @@ -116,13 +114,13 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic p, err := compose.NewProject(service.project, service.ymlPaths...) if err != nil { - return nil, errors.Wrap(err, "could not create Docker Compose project for service") + return nil, fmt.Errorf("could not create Docker Compose project for service: %w", err) } // Clean service logs err = files.RemoveContent(outCtxt.Logs.Folder.Local) if err != nil { - return nil, errors.Wrap(err, "removing service logs failed") + return nil, fmt.Errorf("removing service logs failed: %w", err) } opts := compose.CommandOptions{ @@ -131,11 +129,11 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic // Set custom aliases, which may be used in agent policies. serviceComposeConfig, err := p.Config(opts) if err != nil { - return nil, errors.Wrap(err, "could not get Docker Compose configuration for service") + return nil, fmt.Errorf("could not get Docker Compose configuration for service: %w", err) } outCtxt.CustomProperties, err = buildTerraformAliases(serviceComposeConfig) if err != nil { - return nil, errors.Wrap(err, "can't build Terraform aliases") + return nil, fmt.Errorf("can't build Terraform aliases: %w", err) } // Boot up service @@ -145,7 +143,7 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic } err = p.Up(opts) if err != nil { - return nil, errors.Wrap(err, "could not boot up service using Docker Compose") + return nil, fmt.Errorf("could not boot up service using Docker Compose: %w", err) } err = p.WaitForHealthy(opts) @@ -153,7 +151,8 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic processServiceContainerLogs(p, compose.CommandOptions{ Env: opts.Env, }, outCtxt.Name) - return nil, errors.Wrap(err, "Terraform deployer is unhealthy") + //lint:ignore ST1005 error starting with product name can be capitalized + return nil, fmt.Errorf("Terraform deployer is unhealthy: %w", err) } outCtxt.Agent.Host.NamePrefix = "docker-fleet-agent" @@ -169,7 +168,7 @@ func (tsd TerraformServiceDeployer) SetUp(inCtxt ServiceContext) (DeployedServic func (tsd TerraformServiceDeployer) installDockerfile() (string, error) { locationManager, err := locations.NewLocationManager() if err != nil { - return "", errors.Wrap(err, "failed to find the configuration directory") + return "", fmt.Errorf("failed to find the configuration directory: %w", err) } tfDir := filepath.Join(locationManager.DeployerDir(), terraformDeployerDir) diff --git a/internal/testrunner/runners/system/servicedeployer/variants.go b/internal/testrunner/runners/system/servicedeployer/variants.go index 9b66e1b32..14fd1cec2 100644 --- a/internal/testrunner/runners/system/servicedeployer/variants.go +++ b/internal/testrunner/runners/system/servicedeployer/variants.go @@ -5,12 +5,12 @@ package servicedeployer import ( + "errors" "fmt" "os" "path/filepath" "strings" - "github.com/pkg/errors" "gopkg.in/yaml.v3" ) @@ -46,18 +46,18 @@ func ReadVariantsFile(devDeployPath string) (*VariantsFile, error) { return nil, os.ErrNotExist } if err != nil { - return nil, errors.Wrap(err, "can't stat variants file") + return nil, fmt.Errorf("can't stat variants file: %w", err) } content, err := os.ReadFile(variantsYmlPath) if err != nil { - return nil, errors.Wrap(err, "can't read variants file") + return nil, fmt.Errorf("can't read variants file: %w", err) } var f VariantsFile err = yaml.Unmarshal(content, &f) if err != nil { - return nil, errors.Wrap(err, "can't unmarshal variants file") + return nil, fmt.Errorf("can't unmarshal variants file: %w", err) } return &f, nil } diff --git a/internal/testrunner/runners/system/test_config.go b/internal/testrunner/runners/system/test_config.go index 07e81b962..63c374ba3 100644 --- a/internal/testrunner/runners/system/test_config.go +++ b/internal/testrunner/runners/system/test_config.go @@ -5,6 +5,8 @@ package system import ( + "errors" + "fmt" "os" "path/filepath" "regexp" @@ -12,7 +14,6 @@ import ( "time" "github.com/aymerick/raymond" - "github.com/pkg/errors" "github.com/elastic/go-ucfg" "github.com/elastic/go-ucfg/yaml" @@ -71,25 +72,25 @@ func (t testConfig) Name() string { func newConfig(configFilePath string, ctxt servicedeployer.ServiceContext, serviceVariantName string) (*testConfig, error) { data, err := os.ReadFile(configFilePath) if err != nil && errors.Is(err, os.ErrNotExist) { - return nil, errors.Wrapf(err, "unable to find system test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to find system test configuration file: %s: %w", configFilePath, err) } if err != nil { - return nil, errors.Wrapf(err, "could not load system test configuration file: %s", configFilePath) + return nil, fmt.Errorf("could not load system test configuration file: %s: %w", configFilePath, err) } data, err = applyContext(data, ctxt) if err != nil { - return nil, errors.Wrapf(err, "could not apply context to test configuration file: %s", configFilePath) + return nil, fmt.Errorf("could not apply context to test configuration file: %s: %w", configFilePath, err) } var c testConfig cfg, err := yaml.NewConfig(data, ucfg.PathSep(".")) if err != nil { - return nil, errors.Wrapf(err, "unable to load system test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to load system test configuration file: %s: %w", configFilePath, err) } if err := cfg.Unpack(&c); err != nil { - return nil, errors.Wrapf(err, "unable to unpack system test configuration file: %s", configFilePath) + return nil, fmt.Errorf("unable to unpack system test configuration file: %s: %w", configFilePath, err) } // Save path c.Path = configFilePath @@ -121,13 +122,13 @@ func listConfigFiles(systemTestFolderPath string) (files []string, err error) { func applyContext(data []byte, ctxt servicedeployer.ServiceContext) ([]byte, error) { tmpl, err := raymond.Parse(string(data)) if err != nil { - return data, errors.Wrap(err, "parsing template body failed") + return data, fmt.Errorf("parsing template body failed: %w", err) } tmpl.RegisterHelpers(ctxt.Aliases()) result, err := tmpl.Exec(ctxt) if err != nil { - return data, errors.Wrap(err, "could not render data with context") + return data, fmt.Errorf("could not render data with context: %w", err) } return []byte(result), nil } diff --git a/internal/testrunner/testrunner.go b/internal/testrunner/testrunner.go index 937a53c06..b9549bd04 100644 --- a/internal/testrunner/testrunner.go +++ b/internal/testrunner/testrunner.go @@ -5,6 +5,7 @@ package testrunner import ( + "errors" "fmt" "os" "path/filepath" @@ -12,8 +13,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/internal/elasticsearch" "github.com/elastic/elastic-package/internal/profile" ) @@ -162,7 +161,7 @@ func AssumeTestFolders(packageRootPath string, dataStreams []string, testType Te return []TestFolder{}, nil // data streams defined } if err != nil { - return nil, errors.Wrapf(err, "can't read directory (path: %s)", dataStreamsPath) + return nil, fmt.Errorf("can't read directory (path: %s): %w", dataStreamsPath, err) } for _, fi := range fileInfos { @@ -271,10 +270,10 @@ func Run(testType TestType, options TestOptions) ([]TestResult, error) { results, err := runner.Run(options) tdErr := runner.TearDown() if err != nil { - return nil, errors.Wrap(err, "could not complete test run") + return nil, fmt.Errorf("could not complete test run: %w", err) } if tdErr != nil { - return results, errors.Wrap(tdErr, "could not teardown test runner") + return results, fmt.Errorf("could not teardown test runner: %w", tdErr) } return results, nil } @@ -290,7 +289,7 @@ func findDataStreamTestFolderPaths(packageRootPath, dataStreamGlob, testTypeGlob testFoldersGlob := filepath.Join(packageRootPath, "data_stream", dataStreamGlob, "_dev", "test", testTypeGlob) paths, err := filepath.Glob(testFoldersGlob) if err != nil { - return nil, errors.Wrap(err, "error finding test folders") + return nil, fmt.Errorf("error finding test folders: %w", err) } return paths, err } @@ -300,7 +299,7 @@ func findPackageTestFolderPaths(packageRootPath, testTypeGlob string) ([]string, testFoldersGlob := filepath.Join(packageRootPath, "_dev", "test", testTypeGlob) paths, err := filepath.Glob(testFoldersGlob) if err != nil { - return nil, errors.Wrap(err, "error finding test folders") + return nil, fmt.Errorf("error finding test folders: %w", err) } return paths, err } diff --git a/main.go b/main.go index f2895e852..2ca1012e0 100644 --- a/main.go +++ b/main.go @@ -8,8 +8,6 @@ import ( "log" "os" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/cmd" "github.com/elastic/elastic-package/internal/install" ) @@ -19,7 +17,7 @@ func main() { err := install.EnsureInstalled() if err != nil { - log.Fatal(errors.Wrap(err, "validating installation failed")) + log.Fatalf("Validating installation failed: %v", err) } err = rootCmd.Execute() diff --git a/tools/readme/main.go b/tools/readme/main.go index 0c6e895d3..4349618a6 100644 --- a/tools/readme/main.go +++ b/tools/readme/main.go @@ -12,8 +12,6 @@ import ( "strings" "text/template" - "github.com/pkg/errors" - "github.com/elastic/elastic-package/cmd" ) @@ -36,7 +34,7 @@ type readmeVars struct { func loadCommandTemplate() *template.Template { cmdTmpl, err := template.ParseFiles("./cmd.md.tmpl") if err != nil { - log.Fatal(errors.Wrap(err, "loading command template failed")) + log.Fatalf("Loading command template failed: %v", err) } return cmdTmpl } @@ -44,7 +42,7 @@ func loadCommandTemplate() *template.Template { func loadSubCommandTemplate() *template.Template { subCmdTmpl, err := template.ParseFiles("./subcmd.md.tmpl") if err != nil { - log.Fatal(errors.Wrap(err, "loading subcommand template failed")) + log.Fatalf("Loading subcommand template failed: %v", err) } return subCmdTmpl } @@ -54,10 +52,10 @@ func generateCommandsDoc(cmdTmpl *template.Template, subCommandTemplate *templat for _, cmd := range cmd.Commands() { log.Printf("generating command doc for %s...\n", cmd.Name()) if err := cmdTmpl.Execute(&cmdsDoc, cmd); err != nil { - log.Fatal(errors.Wrapf(err, "writing documentation for command '%s' failed", cmd.Name())) + log.Fatalf("Writing documentation for command '%s' failed: %v", cmd.Name(), err) } for _, subCommand := range cmd.Commands() { - log.Printf("generating command doc for %s %s...\n", cmd.Name(), subCommand.Name()) + log.Printf("Generating command doc for %s %s...\n", cmd.Name(), subCommand.Name()) description := subCommand.Long if description == "" { description = subCommand.Short @@ -72,7 +70,7 @@ func generateCommandsDoc(cmdTmpl *template.Template, subCommandTemplate *templat "Description": description, } if err := subCommandTemplate.Execute(&cmdsDoc, templateData); err != nil { - log.Fatal(errors.Wrapf(err, "writing documentation for command '%s %s' failed", cmd.Name(), subCommand.Name())) + log.Fatalf("Writing documentation for command '%s %s' failed: %v", cmd.Name(), subCommand.Name(), err) } } } @@ -82,7 +80,7 @@ func generateCommandsDoc(cmdTmpl *template.Template, subCommandTemplate *templat func loadReadmeTemplate() *template.Template { readmeTmpl, err := template.ParseFiles("./readme.md.tmpl") if err != nil { - log.Fatal(errors.Wrap(err, "loading README template failed")) + log.Fatalf("Loading README template failed: %v", err) } return readmeTmpl } @@ -90,17 +88,17 @@ func loadReadmeTemplate() *template.Template { func generateReadme(readmeTmpl *template.Template, cmdsDoc string) { readmePath, err := filepath.Abs("../../README.md") if err != nil { - log.Fatal(errors.Wrap(err, "creating README absolute file path failed")) + log.Fatalf("Creating README absolute file path failed: %v", err) } readme, err := os.OpenFile(readmePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { - log.Fatal(errors.Wrapf(err, "opening README file %s failed", readmePath)) + log.Fatalf("Opening README file %s failed: %v", readmePath, err) } defer readme.Close() r := readmeVars{cmdsDoc} if err := readmeTmpl.Execute(readme, r); err != nil { - log.Fatal(errors.Wrapf(err, "writing README file %s failed", readmePath)) + log.Fatalf("Writing README file %s failed: %v", readmePath, err) } }