diff --git a/.github/workflows/parse_integration_test_list.go b/.github/workflows/parse_integration_test_list.go index aa66338e3..22a297cc7 100644 --- a/.github/workflows/parse_integration_test_list.go +++ b/.github/workflows/parse_integration_test_list.go @@ -4,8 +4,9 @@ import ( "encoding/json" "flag" "fmt" - "github.com/ghodss/yaml" "os" + + "github.com/ghodss/yaml" ) func main() { diff --git a/cmd/abapAddonAssemblyKitCheckCVs.go b/cmd/abapAddonAssemblyKitCheckCVs.go index e51574230..d8628efdf 100644 --- a/cmd/abapAddonAssemblyKitCheckCVs.go +++ b/cmd/abapAddonAssemblyKitCheckCVs.go @@ -1,12 +1,13 @@ package cmd import ( + "fmt" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitCheckCVs(config abapAddonAssemblyKitCheckCVsOptions, telemetryData *telemetry.CustomData, cpe *abapAddonAssemblyKitCheckCVsCommonPipelineEnvironment) { @@ -50,7 +51,7 @@ func runAbapAddonAssemblyKitCheckCVs(config *abapAddonAssemblyKitCheckCVsOptions log.Entry().Infof("CommitId %s", repo.CommitID) if !repo.UseClassicCTS && repo.CommitID == "" { - return errors.Errorf("CommitID missing in repo '%s' of the addon.yml", repo.Name) + return fmt.Errorf("CommitID missing in repo '%s' of the addon.yml", repo.Name) } } diff --git a/cmd/abapAddonAssemblyKitCreateTargetVector.go b/cmd/abapAddonAssemblyKitCreateTargetVector.go index 6d7a7bf31..75f0523c9 100644 --- a/cmd/abapAddonAssemblyKitCreateTargetVector.go +++ b/cmd/abapAddonAssemblyKitCreateTargetVector.go @@ -1,6 +1,8 @@ package cmd import ( + "fmt" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" @@ -8,7 +10,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitCreateTargetVector(config abapAddonAssemblyKitCreateTargetVectorOptions, telemetryData *telemetry.CustomData, cpe *abapAddonAssemblyKitCreateTargetVectorCommonPipelineEnvironment) { @@ -37,7 +38,7 @@ func runAbapAddonAssemblyKitCreateTargetVector(config *abapAddonAssemblyKitCreat addonDescriptor := new(abaputils.AddonDescriptor) if err := addonDescriptor.InitFromJSONstring(config.AddonDescriptor); err != nil { - return errors.Wrap(err, "Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]") + return fmt.Errorf("Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]: %w", err) } var tv aakaas.TargetVector diff --git a/cmd/abapAddonAssemblyKitCreateTargetVector_test.go b/cmd/abapAddonAssemblyKitCreateTargetVector_test.go index 0174024ec..0deb5208b 100644 --- a/cmd/abapAddonAssemblyKitCreateTargetVector_test.go +++ b/cmd/abapAddonAssemblyKitCreateTargetVector_test.go @@ -7,8 +7,9 @@ import ( "encoding/json" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/abapAddonAssemblyKitPublishTargetVector.go b/cmd/abapAddonAssemblyKitPublishTargetVector.go index a77a47ffa..37af8e37d 100644 --- a/cmd/abapAddonAssemblyKitPublishTargetVector.go +++ b/cmd/abapAddonAssemblyKitPublishTargetVector.go @@ -1,14 +1,16 @@ package cmd import ( + "fmt" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitPublishTargetVector(config abapAddonAssemblyKitPublishTargetVectorOptions, telemetryData *telemetry.CustomData) { @@ -32,7 +34,7 @@ func runAbapAddonAssemblyKitPublishTargetVector(config *abapAddonAssemblyKitPubl addonDescriptor := new(abaputils.AddonDescriptor) if err := addonDescriptor.InitFromJSONstring(config.AddonDescriptor); err != nil { - return errors.Wrap(err, "Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]") + return fmt.Errorf("Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]: %w", err) } if addonDescriptor.TargetVectorID == "" { diff --git a/cmd/abapAddonAssemblyKitRegisterPackages.go b/cmd/abapAddonAssemblyKitRegisterPackages.go index 07b15edcf..1f75ff503 100644 --- a/cmd/abapAddonAssemblyKitRegisterPackages.go +++ b/cmd/abapAddonAssemblyKitRegisterPackages.go @@ -5,6 +5,8 @@ import ( "os" "path/filepath" + "errors" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" @@ -12,7 +14,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitRegisterPackages(config abapAddonAssemblyKitRegisterPackagesOptions, telemetryData *telemetry.CustomData, cpe *abapAddonAssemblyKitRegisterPackagesCommonPipelineEnvironment) { diff --git a/cmd/abapAddonAssemblyKitRegisterPackages_test.go b/cmd/abapAddonAssemblyKitRegisterPackages_test.go index 5f6aee0f3..80234ef76 100644 --- a/cmd/abapAddonAssemblyKitRegisterPackages_test.go +++ b/cmd/abapAddonAssemblyKitRegisterPackages_test.go @@ -7,10 +7,11 @@ import ( "encoding/json" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/abapAddonAssemblyKitReleasePackages.go b/cmd/abapAddonAssemblyKitReleasePackages.go index 98811b0de..d7916339c 100644 --- a/cmd/abapAddonAssemblyKitReleasePackages.go +++ b/cmd/abapAddonAssemblyKitReleasePackages.go @@ -2,14 +2,16 @@ package cmd import ( "encoding/json" + "fmt" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitReleasePackages(config abapAddonAssemblyKitReleasePackagesOptions, telemetryData *telemetry.CustomData, cpe *abapAddonAssemblyKitReleasePackagesCommonPipelineEnvironment) { @@ -47,7 +49,7 @@ func runAbapAddonAssemblyKitReleasePackages(config *abapAddonAssemblyKitReleaseP } } if numberOfReleasedPackages == 0 { - return errors.Wrap(err, "Release of all packages failed/timed out - Aborting as abapEnvironmentAssembleConfirm step is not needed") + return fmt.Errorf("Release of all packages failed/timed out - Aborting as abapEnvironmentAssembleConfirm step is not needed: %w", err) } else { log.Entry().WithError(err).Warn("Release of at least one package failed/timed out - Continuing anyway to enable abapEnvironmentAssembleConfirm to run") } diff --git a/cmd/abapAddonAssemblyKitReserveNextPackages.go b/cmd/abapAddonAssemblyKitReserveNextPackages.go index fdfb4be3d..51f4fc03d 100644 --- a/cmd/abapAddonAssemblyKitReserveNextPackages.go +++ b/cmd/abapAddonAssemblyKitReserveNextPackages.go @@ -8,9 +8,10 @@ import ( abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapAddonAssemblyKitReserveNextPackages(config abapAddonAssemblyKitReserveNextPackagesOptions, telemetryData *telemetry.CustomData, cpe *abapAddonAssemblyKitReserveNextPackagesCommonPipelineEnvironment) { @@ -39,7 +40,7 @@ func runAbapAddonAssemblyKitReserveNextPackages(config *abapAddonAssemblyKitRese log.Entry().Info("... reading AddonDescriptor (Software Component, Version) from CommonPipelineEnvironment") addonDescriptor := new(abaputils.AddonDescriptor) if err := addonDescriptor.InitFromJSONstring(config.AddonDescriptor); err != nil { - return errors.Wrap(err, "Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]") + return fmt.Errorf("Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV steps have been run before]: %w", err) } log.Entry().Info("╭────────────────────────────────┬──────────────────────╮") diff --git a/cmd/abapAddonAssemblyKitReserveNextPackages_test.go b/cmd/abapAddonAssemblyKitReserveNextPackages_test.go index 732122c5f..9f2ad1829 100644 --- a/cmd/abapAddonAssemblyKitReserveNextPackages_test.go +++ b/cmd/abapAddonAssemblyKitReserveNextPackages_test.go @@ -8,10 +8,11 @@ import ( "testing" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abap/aakaas" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/abapEnvironmentAssembleConfirm.go b/cmd/abapEnvironmentAssembleConfirm.go index 1ee9a70a9..ec8891cc6 100644 --- a/cmd/abapEnvironmentAssembleConfirm.go +++ b/cmd/abapEnvironmentAssembleConfirm.go @@ -2,15 +2,17 @@ package cmd import ( "encoding/json" + "fmt" "time" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentAssembleConfirm(config abapEnvironmentAssembleConfirmOptions, telemetryData *telemetry.CustomData, cpe *abapEnvironmentAssembleConfirmCommonPipelineEnvironment) { @@ -98,7 +100,7 @@ func startingConfirm(repos []abaputils.Repository, conn abapbuild.Connector, del if releasePackagesFailed == nil { releasePackagesFailed = errors.New(errormessage) } else { - releasePackagesFailed = errors.Wrap(releasePackagesFailed, errormessage) + releasePackagesFailed = fmt.Errorf("%s: %w", errormessage, releasePackagesFailed) } } else { log.Entry().Infof("Packages %s was not assembled in this pipeline run, thus no need to confirm", repo.PackageName) diff --git a/cmd/abapEnvironmentAssemblePackages.go b/cmd/abapEnvironmentAssemblePackages.go index b51c238ab..ac5fdcbf4 100644 --- a/cmd/abapEnvironmentAssemblePackages.go +++ b/cmd/abapEnvironmentAssemblePackages.go @@ -6,6 +6,8 @@ import ( "path/filepath" "time" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" @@ -13,7 +15,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type buildWithRepository struct { @@ -50,7 +51,7 @@ func runAbapEnvironmentAssemblePackages(config *abapEnvironmentAssemblePackagesO addonDescriptor := new(abaputils.AddonDescriptor) if err := addonDescriptor.InitFromJSONstring(config.AddonDescriptor); err != nil { - return errors.Wrap(err, "Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV|ReserveNextPackages steps have been run before]") + return fmt.Errorf("Reading AddonDescriptor failed [Make sure abapAddonAssemblyKit...CheckCVs|CheckPV|ReserveNextPackages steps have been run before]: %w", err) } builds, assembleError := runAssemblePackages(config, com, utils, client, addonDescriptor) @@ -88,21 +89,21 @@ func runAssemblePackages(config *abapEnvironmentAssemblePackagesOptions, com aba builds, err := executeBuilds(addonDescriptor, *connBuild, time.Duration(config.MaxRuntimeInMinutes)*time.Minute, time.Duration(config.PollIntervalsInMilliseconds)*time.Millisecond, config.AlternativePhaseName) if err != nil { - return builds, errors.Wrap(err, "Starting Builds for Repositories with reserved AAKaaS packages failed") + return builds, fmt.Errorf("Starting Builds for Repositories with reserved AAKaaS packages failed: %w", err) } if err := checkIfFailedAndPrintLogs(builds); err != nil { - return builds, errors.Wrap(err, "Checking for failed Builds and Printing Build Logs failed") + return builds, fmt.Errorf("Checking for failed Builds and Printing Build Logs failed: %w", err) } if _, err := downloadResultToFile(builds, "SAR_XML", false); err != nil { - return builds, errors.Wrap(err, "Download of Build Artifact SAR_XML failed") + return builds, fmt.Errorf("Download of Build Artifact SAR_XML failed: %w", err) } var filesToPublish []piperutils.Path filesToPublish, err = downloadResultToFile(builds, "DELIVERY_LOGS.ZIP", true) if err != nil { - return builds, errors.Wrap(err, "Download of Build Artifact DELIVERY_LOGS.ZIP failed") + return builds, fmt.Errorf("Download of Build Artifact DELIVERY_LOGS.ZIP failed: %w", err) } log.Entry().Infof("Publishing %v files", len(filesToPublish)) @@ -155,7 +156,7 @@ func (br *buildWithRepository) waitToBeFinished(maxRuntimeInMinutes time.Duratio for { select { case <-timeout: - return errors.Errorf("Timed out: (max Runtime %v reached)", maxRuntimeInMinutes) + return fmt.Errorf("Timed out: (max Runtime %v reached)", maxRuntimeInMinutes) case <-ticker: if err := br.build.Get(); err != nil { return err @@ -327,7 +328,7 @@ func initAssemblePackagesConnection(conn *abapbuild.Connector, config *abapEnvir err := conn.InitBuildFramework(connConfig, com, client) if err != nil { - return errors.Wrap(err, "Connector initialization for communication with the ABAP system failed") + return fmt.Errorf("Connector initialization for communication with the ABAP system failed: %w", err) } return nil diff --git a/cmd/abapEnvironmentBuild.go b/cmd/abapEnvironmentBuild.go index aa25dc63c..612122f27 100644 --- a/cmd/abapEnvironmentBuild.go +++ b/cmd/abapEnvironmentBuild.go @@ -2,11 +2,14 @@ package cmd import ( "encoding/json" + "fmt" "net/url" "reflect" "strings" "time" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" @@ -14,7 +17,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type abapEnvironmentBuildUtils interface { @@ -112,12 +114,12 @@ func runAbapEnvironmentBuild(config *abapEnvironmentBuildOptions, utils abapEnvi conn := new(abapbuild.Connector) if err := initConnection(conn, config, utils); err != nil { - return errors.Wrap(err, "Connector initialization for communication with the ABAP system failed") + return fmt.Errorf("Connector initialization for communication with the ABAP system failed: %w", err) } valuesList, err := evaluateAddonDescriptor(config) if err != nil { - return errors.Wrap(err, "Error during the evaluation of the AddonDescriptor") + return fmt.Errorf("Error during the evaluation of the AddonDescriptor: %w", err) } finalValues, err := runBuilds(conn, config, utils, valuesList) @@ -129,7 +131,7 @@ func runAbapEnvironmentBuild(config *abapEnvironmentBuildOptions, utils abapEnvi cpe.abap.buildValues, err = convertValuesForCPE(finalValues) if err != nil { - return errors.Wrap(err, "Error during the conversion of the values for the commonPipelineenvironment") + return fmt.Errorf("Error during the conversion of the values for the commonPipelineenvironment: %w", err) } return nil } @@ -140,11 +142,11 @@ func runBuilds(conn *abapbuild.Connector, config *abapEnvironmentBuildOptions, u if len(valuesList) == 0 { values, err := generateValuesOnlyFromConfig(config) if err != nil { - return finalValues, errors.Wrap(err, "Generating the values from config failed") + return finalValues, fmt.Errorf("Generating the values from config failed: %w", err) } finalValues, err = runBuild(conn, config, utils, values) if err != nil { - return finalValues, errors.Wrap(err, "Error during execution of build framework") + return finalValues, fmt.Errorf("Error during execution of build framework: %w", err) } } else { // Run several times for each repository in the addonDescriptor @@ -154,11 +156,11 @@ func runBuilds(conn *abapbuild.Connector, config *abapEnvironmentBuildOptions, u for _, values := range valuesList { cummulatedValues, err := generateValuesWithAddonDescriptor(config, values) if err != nil { - return finalValues, errors.Wrap(err, "Error generating input values") + return finalValues, fmt.Errorf("Error generating input values: %w", err) } finalValuesForOneBuild, err := runBuild(conn, config, utils, cummulatedValues) if err != nil { - err = errors.Wrapf(err, "Build with input values %s failed", values2string(values)) + err = fmt.Errorf("Build with input values %s failed: %w", values2string(values), err) if config.StopOnFirstError { return finalValues, err } @@ -172,7 +174,7 @@ func runBuilds(conn *abapbuild.Connector, config *abapEnvironmentBuildOptions, u } finalValues = vE.generateValueSlice() if len(errstrings) > 0 { - finalError := errors.Errorf("%d out %d build runs failed:\n%s", len(errstrings), len(valuesList), (strings.Join(errstrings, "\n"))) + finalError := fmt.Errorf("%d out %d build runs failed:\n%s", len(errstrings), len(valuesList), (strings.Join(errstrings, "\n"))) return finalValues, finalError } } @@ -222,18 +224,18 @@ func runBuild(conn *abapbuild.Connector, config *abapEnvironmentBuildOptions, ut } if err := build.Poll(); err != nil { - return finalValues, errors.Wrap(err, "Error during the polling for the final state of the build run") + return finalValues, fmt.Errorf("Error during the polling for the final state of the build run: %w", err) } if err := build.PrintLogs(); err != nil { - return finalValues, errors.Wrap(err, "Error printing the logs") + return finalValues, fmt.Errorf("Error printing the logs: %w", err) } errBuildRun := build.EvaluteIfBuildSuccessful() if err := build.Download(); err != nil { if errBuildRun != nil { - errWraped := errors.Errorf("Download failed after execution of build failed: %v. Build error: %v", err, errBuildRun) + errWraped := fmt.Errorf("Download failed after execution of build failed: %v. Build error: %v", err, errBuildRun) return finalValues, errWraped } return finalValues, err @@ -256,14 +258,14 @@ type myBuild struct { func (b *myBuild) Start(values abapbuild.Values) error { if err := b.Build.Start(b.abapEnvironmentBuildOptions.Phase, values); err != nil { - return errors.Wrap(err, "Error starting the build framework") + return fmt.Errorf("Error starting the build framework: %w", err) } return nil } func (b *myBuild) EvaluteIfBuildSuccessful() error { if err := b.Build.EvaluteIfBuildSuccessful(b.TreatWarningsAsError); err != nil { - return errors.Wrap(err, "Build ended without success") + return fmt.Errorf("Build ended without success: %w", err) } return nil } @@ -271,11 +273,11 @@ func (b *myBuild) EvaluteIfBuildSuccessful() error { func (b *myBuild) Download() error { if b.DownloadAllResultFiles { if err := b.DownloadAllResults(b.SubDirectoryForDownload, b.FilenamePrefixForDownload); err != nil { - return errors.Wrap(err, "Error during the download of the result files") + return fmt.Errorf("Error during the download of the result files: %w", err) } } else { if err := b.DownloadResults(b.DownloadResultFilenames, b.SubDirectoryForDownload, b.FilenamePrefixForDownload); err != nil { - return errors.Wrapf(err, "Error during the download of the result files %s", b.DownloadResultFilenames) + return fmt.Errorf("Error during the download of the result files %s: %w", b.DownloadResultFilenames, err) } } return nil @@ -286,7 +288,7 @@ func (b *myBuild) Publish(utils abapEnvironmentBuildUtils) error { b.PublishAllDownloadedResults("abapEnvironmentBuild", utils) } else { if err := b.PublishDownloadedResults("abapEnvironmentBuild", b.PublishResultFilenames, utils); err != nil { - return errors.Wrapf(err, "Error during the publish of the result files %s", b.PublishResultFilenames) + return fmt.Errorf("Error during the publish of the result files %s: %w", b.PublishResultFilenames, err) } } return nil @@ -295,7 +297,7 @@ func (b *myBuild) Publish(utils abapEnvironmentBuildUtils) error { func (b *myBuild) GetFinalValues() ([]abapbuild.Value, error) { var values []abapbuild.Value if err := b.GetValues(); err != nil { - return values, errors.Wrapf(err, "Error getting the values from build framework") + return values, fmt.Errorf("Error getting the values from build framework: %w", err) } return b.Build.Values, nil } @@ -309,14 +311,14 @@ func convertValuesForCPE(values []abapbuild.Value) (string, error) { var cpeValues []cpeValue byt, err := json.Marshal(&values) if err != nil { - return "", errors.Wrapf(err, "Error converting the values from the build framework") + return "", fmt.Errorf("Error converting the values from the build framework: %w", err) } if err := json.Unmarshal(byt, &cpeValues); err != nil { - return "", errors.Wrapf(err, "Error converting the values from the build framework into the structure for the commonPipelineEnvironment") + return "", fmt.Errorf("Error converting the values from the build framework into the structure for the commonPipelineEnvironment: %w", err) } jsonBytes, err := json.Marshal(cpeValues) if err != nil { - return "", errors.Wrapf(err, "Error converting the converted values") + return "", fmt.Errorf("Error converting the converted values: %w", err) } return string(jsonBytes), nil } @@ -364,7 +366,7 @@ func generateValuesFromString(stringValues string) ([]abapbuild.Value, error) { if len(stringValues) > 0 { if err := json.Unmarshal([]byte(stringValues), &values); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return values, errors.Wrapf(err, "Could not convert the values %s", stringValues) + return values, fmt.Errorf("Could not convert the values %s: %w", stringValues, err) } } return values, nil @@ -377,18 +379,18 @@ type valuesEvaluator struct { func (vE *valuesEvaluator) initialize(stringValues string) error { values, err := generateValuesFromString(stringValues) if err != nil { - return errors.Wrapf(err, "Error converting the vales from the config") + return fmt.Errorf("Error converting the vales from the config: %w", err) } vE.m = make(map[string]string) for _, value := range values { if (len(value.ValueID) == 0) || (len(value.Value) == 0) { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("Values %s from config have not the right format", stringValues) + return fmt.Errorf("Values %s from config have not the right format", stringValues) } _, present := vE.m[value.ValueID] if present { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("Value_id %s is not unique in the config", value.ValueID) + return fmt.Errorf("Value_id %s is not unique in the config", value.ValueID) } vE.m[value.ValueID] = value.Value } @@ -399,7 +401,7 @@ func (vE *valuesEvaluator) appendStringValuesIfNotPresent(stringValues string, t var values []abapbuild.Value values, err := generateValuesFromString(stringValues) if err != nil { - return errors.Wrapf(err, "Error converting the vales from the commonPipelineEnvironment") + return fmt.Errorf("Error converting the vales from the commonPipelineEnvironment: %w", err) } if err := vE.appendValuesIfNotPresent(values, throwErrorIfPresent); err != nil { return err @@ -415,7 +417,7 @@ func (vE *valuesEvaluator) appendValuesIfNotPresent(values []abapbuild.Value, th _, present := vE.m[value.ValueID] if present { if throwErrorIfPresent { - return errors.Errorf("Value_id %s already existed in the config", value.ValueID) + return fmt.Errorf("Value_id %s already existed in the config", value.ValueID) } log.Entry().Infof("Value '%s':'%s' already existed -> discard this value", value.ValueID, value.Value) } else { @@ -461,7 +463,7 @@ func evaluateAddonDescriptor(config *abapEnvironmentBuildOptions) ([][]abapbuild addonDescriptor := new(abaputils.AddonDescriptor) if err := addonDescriptor.InitFromJSONstring(config.AddonDescriptor); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return listOfValuesList, errors.Wrap(err, "Error during the conversion of the AddonDescriptor") + return listOfValuesList, fmt.Errorf("Error during the conversion of the AddonDescriptor: %w", err) } for _, repo := range addonDescriptor.Repositories { myRepo := myRepo{ @@ -469,12 +471,12 @@ func evaluateAddonDescriptor(config *abapEnvironmentBuildOptions) ([][]abapbuild } use, err := myRepo.checkCondition(config) if err != nil { - return listOfValuesList, errors.Wrapf(err, "Checking of ConditionOnAddonDescriptor failed") + return listOfValuesList, fmt.Errorf("Checking of ConditionOnAddonDescriptor failed: %w", err) } if use { values, err := myRepo.generateValues(config) if err != nil { - return listOfValuesList, errors.Wrap(err, "Error generating values from AddonDescriptor") + return listOfValuesList, fmt.Errorf("Error generating values from AddonDescriptor: %w", err) } if len(values) > 0 { listOfValuesList = append(listOfValuesList, values) @@ -490,16 +492,16 @@ func (mR *myRepo) checkCondition(config *abapEnvironmentBuildOptions) (bool, err if len(config.ConditionOnAddonDescriptor) > 0 { if err := json.Unmarshal([]byte(config.ConditionOnAddonDescriptor), &conditions); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return false, errors.Wrapf(err, "Conversion of ConditionOnAddonDescriptor in the config failed") + return false, fmt.Errorf("Conversion of ConditionOnAddonDescriptor in the config failed: %w", err) } for _, cond := range conditions { if cond.Field == "" || cond.Operator == "" || cond.Value == "" { log.SetErrorCategory(log.ErrorConfiguration) - return false, errors.Errorf("Invalid condition for field %s with operator %s and value %s", cond.Field, cond.Operator, cond.Value) + return false, fmt.Errorf("Invalid condition for field %s with operator %s and value %s", cond.Field, cond.Operator, cond.Value) } use, err := mR.amI(cond.Field, cond.Operator, cond.Value) if err != nil { - return false, errors.Wrapf(err, "Checking the field %s failed", cond.Field) + return false, fmt.Errorf("Checking the field %s failed: %w", cond.Field, err) } if !use { log.Entry().Infof("addonDescriptor with the name %s does not fulfil the requierement %s%s%s from the ConditionOnAddonDescriptor, therefore it is not used", mR.Name, cond.Field, cond.Operator, cond.Value) @@ -519,13 +521,13 @@ func (mR *myRepo) generateValues(config *abapEnvironmentBuildOptions) ([]abapbui } else { if err := json.Unmarshal([]byte(config.UseFieldsOfAddonDescriptor), &useFields); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return values, errors.Wrapf(err, "Conversion of UseFieldsOfAddonDescriptor in the config failed") + return values, fmt.Errorf("Conversion of UseFieldsOfAddonDescriptor in the config failed: %w", err) } m := make(map[string]string) for _, uF := range useFields { if uF.Use == "" || uF.Rename == "" { log.SetErrorCategory(log.ErrorConfiguration) - return values, errors.Errorf("Invalid UseFieldsOfAddonDescriptor for use %s and renameTo %s", uF.Use, uF.Rename) + return values, fmt.Errorf("Invalid UseFieldsOfAddonDescriptor for use %s and renameTo %s", uF.Use, uF.Rename) } m[uF.Use] = uF.Rename } @@ -545,7 +547,7 @@ func (mR *myRepo) generateValues(config *abapEnvironmentBuildOptions) ([]abapbui } if len(values) != len(useFields) { log.SetErrorCategory(log.ErrorConfiguration) - return values, errors.Errorf("Not all fields in UseFieldsOfAddonDescriptor have been found. Probably a 'use' was used which does not exist") + return values, fmt.Errorf("Not all fields in UseFieldsOfAddonDescriptor have been found. Probably a 'use' was used which does not exist") } } return values, nil @@ -567,7 +569,7 @@ func (mR *myRepo) amI(field string, operator string, comp string) (bool, error) return fn(name, comp), nil } log.SetErrorCategory(log.ErrorConfiguration) - return false, errors.Errorf("Invalid operator %s", operator) + return false, fmt.Errorf("Invalid operator %s", operator) } type OperatorCallback map[string]func(string, string) bool diff --git a/cmd/abapEnvironmentCheckoutBranch.go b/cmd/abapEnvironmentCheckoutBranch.go index 17804ec21..6c6378297 100644 --- a/cmd/abapEnvironmentCheckoutBranch.go +++ b/cmd/abapEnvironmentCheckoutBranch.go @@ -5,13 +5,14 @@ import ( "reflect" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentCheckoutBranch(options abapEnvironmentCheckoutBranchOptions, _ *telemetry.CustomData) { @@ -62,11 +63,11 @@ func runAbapEnvironmentCheckoutBranch(options *abapEnvironmentCheckoutBranchOpti repositories := []abaputils.Repository{} err = checkCheckoutBranchRepositoryConfiguration(*options) if err != nil { - return errors.Wrap(err, "Configuration is not consistent") + return fmt.Errorf("Configuration is not consistent: %w", err) } repositories, err = abaputils.GetRepositories(&abaputils.RepositoriesConfig{BranchName: options.BranchName, RepositoryName: options.RepositoryName, Repositories: options.Repositories}, true) if err != nil { - return errors.Wrap(err, "Could not read repositories") + return fmt.Errorf("Could not read repositories: %w", err) } err = checkoutBranches(repositories, connectionDetails, apiManager, logOutputManager) @@ -120,7 +121,7 @@ func handleCheckout(repo abaputils.Repository, checkoutConnectionDetails abaputi api, errGetAPI := apiManager.GetAPI(checkoutConnectionDetails, repo) if errGetAPI != nil { - return errors.Wrap(errGetAPI, "Could not initialize the connection to the system") + return fmt.Errorf("Could not initialize the connection to the system: %w", errGetAPI) } err = api.CheckoutBranch() diff --git a/cmd/abapEnvironmentCloneGitRepo.go b/cmd/abapEnvironmentCloneGitRepo.go index 3135d8f24..5338665e2 100644 --- a/cmd/abapEnvironmentCloneGitRepo.go +++ b/cmd/abapEnvironmentCloneGitRepo.go @@ -1,15 +1,17 @@ package cmd import ( + "fmt" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentCloneGitRepo(config abapEnvironmentCloneGitRepoOptions, _ *telemetry.CustomData) { @@ -49,18 +51,18 @@ func runAbapEnvironmentCloneGitRepo(config *abapEnvironmentCloneGitRepoOptions, errConfig := checkConfiguration(config) if errConfig != nil { - return errors.Wrap(errConfig, "The provided configuration is not allowed") + return fmt.Errorf("The provided configuration is not allowed: %w", errConfig) } repositories, errGetRepos := abaputils.GetRepositories(&abaputils.RepositoriesConfig{BranchName: config.BranchName, RepositoryName: config.RepositoryName, Repositories: config.Repositories, ByogUsername: config.ByogUsername, ByogPassword: config.ByogPassword, ByogAuthMethod: config.ByogAuthMethod}, false) if errGetRepos != nil { - return errors.Wrap(errGetRepos, "Could not read repositories") + return fmt.Errorf("Could not read repositories: %w", errGetRepos) } // Determine the host, user and password, either via the input parameters or via a cloud foundry service key connectionDetails, errorGetInfo := com.GetAbapCommunicationArrangementInfo(subOptions, "") if errorGetInfo != nil { - return errors.Wrap(errorGetInfo, "Parameters for the ABAP Connection not available") + return fmt.Errorf("Parameters for the ABAP Connection not available: %w", errorGetInfo) } connectionDetails.CertificateNames = config.CertificateNames @@ -89,7 +91,7 @@ func cloneSingleRepo(apiManager abaputils.SoftwareComponentApiManagerInterface, // If the repository had been cloned already, as checkout/pull has been done - polling the status is not necessary anymore api, errGetAPI := apiManager.GetAPI(connectionDetails, repo) if errGetAPI != nil { - return errors.Wrap(errGetAPI, "Could not initialize the connection to the system") + return fmt.Errorf("Could not initialize the connection to the system: %w", errGetAPI) } logString := repo.GetCloneLogString() @@ -101,7 +103,7 @@ func cloneSingleRepo(apiManager abaputils.SoftwareComponentApiManagerInterface, alreadyCloned, activeBranch, errCheckCloned, isByog := api.GetRepository() if errCheckCloned != nil { - return errors.Wrap(errCheckCloned, errorString) + return fmt.Errorf("%s: %w", errorString, errCheckCloned) } if !alreadyCloned { @@ -110,13 +112,13 @@ func cloneSingleRepo(apiManager abaputils.SoftwareComponentApiManagerInterface, } errClone := api.Clone() if errClone != nil { - return errors.Wrap(errClone, errorString) + return fmt.Errorf("%s: %w", errorString, errClone) } // set correct filename for archive file logOutputManager.FileNameStep = "clone" status, errorPollEntity := abaputils.PollEntity(api, apiManager.GetPollIntervall(), logOutputManager) if errorPollEntity != nil { - return errors.Wrap(errorPollEntity, errorString) + return fmt.Errorf("%s: %w", errorString, errorPollEntity) } if status == "E" { return errors.New("Clone of " + logString + " failed on the ABAP System") diff --git a/cmd/abapEnvironmentCreateTag.go b/cmd/abapEnvironmentCreateTag.go index 7e989de1c..f1ea73d98 100644 --- a/cmd/abapEnvironmentCreateTag.go +++ b/cmd/abapEnvironmentCreateTag.go @@ -5,12 +5,13 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentCreateTag(config abapEnvironmentCreateTagOptions, _ *telemetry.CustomData) { @@ -38,7 +39,7 @@ func runAbapEnvironmentCreateTag(config *abapEnvironmentCreateTagOptions, com ab connectionDetails, errorGetInfo := com.GetAbapCommunicationArrangementInfo(convertTagConfig(config), "") if errorGetInfo != nil { - return errors.Wrap(errorGetInfo, "Parameters for the ABAP Connection not available") + return fmt.Errorf("Parameters for the ABAP Connection not available: %w", errorGetInfo) } connectionDetails.CertificateNames = config.CertificateNames @@ -89,12 +90,12 @@ func createSingleTag(item abaputils.CreateTagBacklog, index int, con abaputils.C api, errGetAPI := apiManager.GetAPI(con, abaputils.Repository{Name: item.RepositoryName, CommitID: item.CommitID}) if errGetAPI != nil { - return errors.Wrap(errGetAPI, "Could not initialize the connection to the system") + return fmt.Errorf("Could not initialize the connection to the system: %w", errGetAPI) } createTagError := api.CreateTag(item.Tags[index]) if createTagError != nil { - return errors.Wrap(err, "Creation of Tag failed on the ABAP system") + return fmt.Errorf("Creation of Tag failed on the ABAP system: %w", err) } logOutputManager := abaputils.LogOutputManager{ diff --git a/cmd/abapEnvironmentPullGitRepo.go b/cmd/abapEnvironmentPullGitRepo.go index 890d6fbdb..77adf88bb 100644 --- a/cmd/abapEnvironmentPullGitRepo.go +++ b/cmd/abapEnvironmentPullGitRepo.go @@ -4,13 +4,14 @@ import ( "fmt" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentPullGitRepo(options abapEnvironmentPullGitRepoOptions, _ *telemetry.CustomData) { @@ -51,7 +52,7 @@ func runAbapEnvironmentPullGitRepo(options *abapEnvironmentPullGitRepoOptions, c // Determine the host, user and password, either via the input parameters or via a cloud foundry service key connectionDetails, err := com.GetAbapCommunicationArrangementInfo(subOptions, "") if err != nil { - return errors.Wrap(err, "Parameters for the ABAP Connection not available") + return fmt.Errorf("Parameters for the ABAP Connection not available: %w", err) } connectionDetails.CertificateNames = options.CertificateNames @@ -101,12 +102,12 @@ func handlePull(repo abaputils.Repository, con abaputils.ConnectionDetailsHTTP, api, errGetAPI := apiManager.GetAPI(con, repo) if errGetAPI != nil { - return errors.Wrap(errGetAPI, "Could not initialize the connection to the system") + return fmt.Errorf("Could not initialize the connection to the system: %w", errGetAPI) } err = api.Pull() if err != nil { - return errors.Wrap(err, errorString) + return fmt.Errorf("%s: %w", errorString, err) } // set correct filename for archive file @@ -114,7 +115,7 @@ func handlePull(repo abaputils.Repository, con abaputils.ConnectionDetailsHTTP, // Polling the status of the repository import on the ABAP Environment system status, errorPollEntity := abaputils.PollEntity(api, apiManager.GetPollIntervall(), logOutputManager) if errorPollEntity != nil { - return errors.Wrap(errorPollEntity, errorString) + return fmt.Errorf("%s: %w", errorString, errorPollEntity) } if status == "E" { return errors.New(errorString) diff --git a/cmd/abapEnvironmentPushATCSystemConfig.go b/cmd/abapEnvironmentPushATCSystemConfig.go index f7043fc23..b1d5a4df0 100644 --- a/cmd/abapEnvironmentPushATCSystemConfig.go +++ b/cmd/abapEnvironmentPushATCSystemConfig.go @@ -14,12 +14,13 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentPushATCSystemConfig(config abapEnvironmentPushATCSystemConfigOptions, telemetryData *telemetry.CustomData) { @@ -48,12 +49,12 @@ func runAbapEnvironmentPushATCSystemConfig(config *abapEnvironmentPushATCSystemC // Determine the host, user and password, either via the input parameters or via a cloud foundry service key. connectionDetails, err := autils.GetAbapCommunicationArrangementInfo(subOptions, "/sap/opu/odata4/sap/satc_ci_cf_api/srvd_a2x/sap/satc_ci_cf_sv_api/0001") if err != nil { - return errors.Errorf("Parameters for the ABAP Connection not available: %v", err) + return fmt.Errorf("Parameters for the ABAP Connection not available: %v", err) } cookieJar, err := cookiejar.New(nil) if err != nil { - return errors.Errorf("could not create a Cookie Jar: %v", err) + return fmt.Errorf("could not create a Cookie Jar: %v", err) } clientOptions := piperhttp.ClientOptions{ MaxRequestDuration: 180 * time.Second, @@ -127,7 +128,7 @@ func checkATCSystemConfigurationFile(config *abapEnvironmentPushATCSystemConfigO //check if parsedConfigurationJson is not initial or Configuration Name not supplied if reflect.DeepEqual(parsedConfigurationJson, emptyConfigurationJson) || parsedConfigurationJson.ConfName == "" { - return parsedConfigurationJson, atcSystemConfiguartionJsonFile, errors.Errorf("pushing ATC System Configuration failed. Reason: Configured File does not contain required ATC System Configuration attributes (File: %s)", config.AtcSystemConfigFilePath) + return parsedConfigurationJson, atcSystemConfiguartionJsonFile, fmt.Errorf("pushing ATC System Configuration failed. Reason: Configured File does not contain required ATC System Configuration attributes (File: %s)", config.AtcSystemConfigFilePath) } return parsedConfigurationJson, atcSystemConfiguartionJsonFile, nil @@ -145,7 +146,7 @@ func readATCSystemConfigurationFile(config *abapEnvironmentPushATCSystemConfigOp } if len(filelocation) == 0 { - return parsedConfigurationJson, atcSystemConfiguartionJsonFile, errors.Errorf("pushing ATC System Configuration failed. Reason: Configured Filelocation is empty (File: %s)", config.AtcSystemConfigFilePath) + return parsedConfigurationJson, atcSystemConfiguartionJsonFile, fmt.Errorf("pushing ATC System Configuration failed. Reason: Configured Filelocation is empty (File: %s)", config.AtcSystemConfigFilePath) } filename, err = filepath.Abs(filelocation[0]) @@ -157,12 +158,12 @@ func readATCSystemConfigurationFile(config *abapEnvironmentPushATCSystemConfigOp return parsedConfigurationJson, atcSystemConfiguartionJsonFile, err } if len(atcSystemConfiguartionJsonFile) == 0 { - return parsedConfigurationJson, atcSystemConfiguartionJsonFile, errors.Errorf("pushing ATC System Configuration failed. Reason: Configured File is empty (File: %s)", config.AtcSystemConfigFilePath) + return parsedConfigurationJson, atcSystemConfiguartionJsonFile, fmt.Errorf("pushing ATC System Configuration failed. Reason: Configured File is empty (File: %s)", config.AtcSystemConfigFilePath) } err = json.Unmarshal(atcSystemConfiguartionJsonFile, &parsedConfigurationJson) if err != nil { - return emptyConfigurationJson, atcSystemConfiguartionJsonFile, errors.Errorf("pushing ATC System Configuration failed. Unmarshal Error of ATC Configuration File ("+config.AtcSystemConfigFilePath+"): %v", err) + return emptyConfigurationJson, atcSystemConfiguartionJsonFile, fmt.Errorf("pushing ATC System Configuration failed. Unmarshal Error of ATC Configuration File ("+config.AtcSystemConfigFilePath+"): %v", err) } return parsedConfigurationJson, atcSystemConfiguartionJsonFile, err @@ -200,7 +201,7 @@ func fetchXcsrfTokenFromHead(connectionDetails abaputils.ConnectionDetailsHTTP, resp, err := abaputils.GetHTTPResponse("HEAD", connectionDetails, nil, client) if err != nil { _, err = abaputils.HandleHTTPError(resp, err, "authentication on the ABAP system failed", connectionDetails) - return connectionDetails.XCsrfToken, errors.Errorf("X-Csrf-Token fetch failed for Service ATC System Configuration: %v", err) + return connectionDetails.XCsrfToken, fmt.Errorf("X-Csrf-Token fetch failed for Service ATC System Configuration: %v", err) } defer resp.Body.Close() @@ -286,14 +287,14 @@ func buildParsedATCSystemConfigBaseJsonBody(confUUID string, atcSystemConfiguart var outputString string = `` if err := json.Unmarshal([]byte(atcSystemConfiguartionJsonFile), &i); err != nil { - return outputString, errors.Errorf("problem with unmarshall input "+atcSystemConfiguartionJsonFile+": %v", err) + return outputString, fmt.Errorf("problem with unmarshall input "+atcSystemConfiguartionJsonFile+": %v", err) } if m, ok := i.(map[string]interface{}); ok { delete(m, "_priorities") } if output, err := json.Marshal(i); err != nil { - return outputString, errors.Errorf("problem with marshall output "+atcSystemConfiguartionJsonFile+": %v", err) + return outputString, fmt.Errorf("problem with marshall output "+atcSystemConfiguartionJsonFile+": %v", err) } else { output = output[1:] // remove leading '{' outputString = string(output) diff --git a/cmd/abapEnvironmentRunATCCheck.go b/cmd/abapEnvironmentRunATCCheck.go index 779f91dd2..cc62c3faf 100644 --- a/cmd/abapEnvironmentRunATCCheck.go +++ b/cmd/abapEnvironmentRunATCCheck.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "encoding/xml" + "fmt" "io" "net/http" "net/http/cookiejar" @@ -13,13 +14,14 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentRunATCCheck(options abapEnvironmentRunATCCheckOptions, _ *telemetry.CustomData) { @@ -100,10 +102,10 @@ func fetchAndPersistATCResults(resp *http.Response, details abaputils.Connection err, failStep = logAndPersistAndEvaluateATCResults(utils, body, atcResultFileName, generateHTML, failOnSeverityLevel) } if err != nil { - return errors.Errorf("Handling ATC result failed: %v", err) + return fmt.Errorf("Handling ATC result failed: %v", err) } if failStep { - return errors.Errorf("Step execution failed due to at least one ATC finding with severity equal to or higher than the failOnSeverity parameter of this step (see config.yml)") + return fmt.Errorf("Step execution failed due to at least one ATC finding with severity equal to or higher than the failOnSeverity parameter of this step (see config.yml)") } return nil } @@ -151,7 +153,7 @@ func buildATCRequestBody(config abapEnvironmentRunATCCheckOptions) (bodyString s } if objectSetString == "" { - return objectSetString, errors.Errorf("Error while parsing ATC test run object set config. No object set has been provided. Please configure the objects you want to be checked for the respective test run") + return objectSetString, fmt.Errorf("Error while parsing ATC test run object set config. No object set has been provided. Please configure the objects you want to be checked for the respective test run") } bodyString = `` + objectSetString + `` @@ -217,7 +219,7 @@ func getATCObjectSet(ATCConfig ATCConfiguration) (objectSet string, err error) { func logAndPersistAndEvaluateATCResults(utils piperutils.FileUtils, body []byte, atcResultFileName string, generateHTML bool, failOnSeverityLevel string) (error, bool) { var failStep bool if len(body) == 0 { - return errors.Errorf("Parsing ATC result failed: %v", errors.New("Body is empty, can't parse empty body")), failStep + return fmt.Errorf("Parsing ATC result failed: %v", errors.New("Body is empty, can't parse empty body")), failStep } responseBody := string(body) @@ -260,7 +262,7 @@ func logAndPersistAndEvaluateATCResults(utils piperutils.FileUtils, body []byte, piperutils.PersistReportsAndLinks("abapEnvironmentRunATCCheck", "", utils, reports, nil) } if err != nil { - return errors.Errorf("Writing results failed: %v", err), failStep + return fmt.Errorf("Writing results failed: %v", err), failStep } return nil, failStep } @@ -316,7 +318,7 @@ func runATC(requestType string, details abaputils.ConnectionDetailsHTTP, body [] if err != nil || (resp != nil && resp.StatusCode == 400) { // send request does not seem to produce error with StatusCode 400!!! _, err = abaputils.HandleHTTPError(resp, err, "triggering ATC run failed with Status: "+resp.Status, details) log.SetErrorCategory(log.ErrorService) - return resp, errors.Errorf("triggering ATC run failed: %v", err) + return resp, fmt.Errorf("triggering ATC run failed: %v", err) } defer resp.Body.Close() return resp, err @@ -346,7 +348,7 @@ func fetchXcsrfToken(requestType string, details abaputils.ConnectionDetailsHTTP req, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil) if err != nil { log.SetErrorCategory(log.ErrorInfrastructure) - return "", errors.Errorf("Fetching Xcsrf-Token failed: %v", err) + return "", fmt.Errorf("Fetching Xcsrf-Token failed: %v", err) } defer req.Body.Close() @@ -360,11 +362,11 @@ func pollATCRun(details abaputils.ConnectionDetailsHTTP, body []byte, client pip for { resp, err := getHTTPResponseATCRun("GET", details, nil, client) if err != nil { - return "", errors.Errorf("Getting HTTP response failed: %v", err) + return "", fmt.Errorf("Getting HTTP response failed: %v", err) } bodyText, err := io.ReadAll(resp.Body) if err != nil { - return "", errors.Errorf("Reading response body failed: %v", err) + return "", fmt.Errorf("Reading response body failed: %v", err) } x := new(Run) @@ -380,7 +382,7 @@ func pollATCRun(details abaputils.ConnectionDetailsHTTP, body []byte, client pip return x.Link[0].Key, err } if x.Status == "" { - return "", errors.Errorf("Could not get any response from ATC poll: %v", errors.New("Status from ATC run is empty. Either it's not an ABAP system or ATC run hasn't started")) + return "", fmt.Errorf("Could not get any response from ATC poll: %v", errors.New("Status from ATC run is empty. Either it's not an ABAP system or ATC run hasn't started")) } time.Sleep(5 * time.Second) } @@ -392,7 +394,7 @@ func getHTTPResponseATCRun(requestType string, details abaputils.ConnectionDetai resp, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil) if err != nil { - return resp, errors.Errorf("Getting ATC run status failed: %v", err) + return resp, fmt.Errorf("Getting ATC run status failed: %v", err) } return resp, err } @@ -406,7 +408,7 @@ func getResultATCRun(requestType string, details abaputils.ConnectionDetailsHTTP resp, err := client.SendRequest(requestType, details.URL, bytes.NewBuffer(body), header, nil) if err != nil { - return resp, errors.Errorf("Getting ATC run results failed: %v", err) + return resp, fmt.Errorf("Getting ATC run results failed: %v", err) } return resp, err } diff --git a/cmd/abapEnvironmentRunAUnitTest.go b/cmd/abapEnvironmentRunAUnitTest.go index fa309fc04..b714195a9 100644 --- a/cmd/abapEnvironmentRunAUnitTest.go +++ b/cmd/abapEnvironmentRunAUnitTest.go @@ -14,13 +14,14 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func abapEnvironmentRunAUnitTest(config abapEnvironmentRunAUnitTestOptions, telemetryData *telemetry.CustomData) { diff --git a/cmd/ansSendEvent_test.go b/cmd/ansSendEvent_test.go index 027acd343..2966929d2 100644 --- a/cmd/ansSendEvent_test.go +++ b/cmd/ansSendEvent_test.go @@ -5,11 +5,12 @@ package cmd import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/ans" "github.com/SAP/jenkins-library/pkg/xsuaa" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) const testTimestamp = 1651585103 diff --git a/cmd/apiKeyValueMapDownload.go b/cmd/apiKeyValueMapDownload.go index 25980c17a..49b7105a8 100644 --- a/cmd/apiKeyValueMapDownload.go +++ b/cmd/apiKeyValueMapDownload.go @@ -10,7 +10,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiKeyValueMapDownload(config apiKeyValueMapDownloadOptions, telemetryData *telemetry.CustomData) { @@ -43,17 +42,17 @@ func runApiKeyValueMapDownload(config *apiKeyValueMapDownloadOptions, telemetryD Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := http.MethodGet downloadResp, httpErr := httpClient.SendRequest(httpMethod, downloadkeyValueMapArtifactURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, downloadkeyValueMapArtifactURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, downloadkeyValueMapArtifactURL, httpErr) } if downloadResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if downloadResp != nil && downloadResp.Body != nil { defer downloadResp.Body.Close() @@ -62,7 +61,7 @@ func runApiKeyValueMapDownload(config *apiKeyValueMapDownloadOptions, telemetryD csvFilePath := config.DownloadPath file, err := os.Create(csvFilePath) if err != nil { - return errors.Wrap(err, "Failed to create api key value map CSV file") + return fmt.Errorf("Failed to create api key value map CSV file: %w", err) } _, err = io.Copy(file, downloadResp.Body) if err != nil { @@ -73,8 +72,8 @@ func runApiKeyValueMapDownload(config *apiKeyValueMapDownloadOptions, telemetryD responseBody, readErr := io.ReadAll(downloadResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code : %v", downloadResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code : %v: %w", downloadResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", responseBody, downloadResp.StatusCode) - return errors.Errorf("api Key value map download failed, Response Status code: %v", downloadResp.StatusCode) + return fmt.Errorf("api Key value map download failed, Response Status code: %v", downloadResp.StatusCode) } diff --git a/cmd/apiKeyValueMapUpload.go b/cmd/apiKeyValueMapUpload.go index 70d90a300..9fb47942a 100644 --- a/cmd/apiKeyValueMapUpload.go +++ b/cmd/apiKeyValueMapUpload.go @@ -12,7 +12,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiKeyValueMapUpload(config apiKeyValueMapUploadOptions, telemetryData *telemetry.CustomData) { @@ -42,7 +41,7 @@ func runApiKeyValueMapUpload(config *apiKeyValueMapUploadOptions, telemetryData tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, tokenErr := cpi.CommonUtils.GetBearerToken(tokenParameters) if tokenErr != nil { - return errors.Wrap(tokenErr, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", tokenErr) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -59,7 +58,7 @@ func runApiKeyValueMapUpload(config *apiKeyValueMapUploadOptions, telemetryData apiProxyUploadStatusResp, httpErr := httpClient.SendRequest(httpMethod, uploadApiKeyValueMapStatusURL, payload, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %q request to %q failed with error", httpMethod, uploadApiKeyValueMapStatusURL) + return fmt.Errorf("HTTP %q request to %q failed with error: %w", httpMethod, uploadApiKeyValueMapStatusURL, httpErr) } if apiProxyUploadStatusResp != nil && apiProxyUploadStatusResp.Body != nil { @@ -67,7 +66,7 @@ func runApiKeyValueMapUpload(config *apiKeyValueMapUploadOptions, telemetryData } if apiProxyUploadStatusResp == nil { - return errors.Errorf("did not retrieve a HTTP response") + return fmt.Errorf("did not retrieve a HTTP response") } if apiProxyUploadStatusResp.StatusCode == http.StatusCreated { @@ -79,11 +78,11 @@ func runApiKeyValueMapUpload(config *apiKeyValueMapUploadOptions, telemetryData response, readErr := io.ReadAll(apiProxyUploadStatusResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", apiProxyUploadStatusResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", apiProxyUploadStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(response), apiProxyUploadStatusResp.StatusCode) - return errors.Errorf("Failed to upload API key value map artefact, Response Status code: %v", apiProxyUploadStatusResp.StatusCode) + return fmt.Errorf("Failed to upload API key value map artefact, Response Status code: %v", apiProxyUploadStatusResp.StatusCode) } // createJSONPayload -return http payload as byte array @@ -99,7 +98,7 @@ func createJSONPayload(config *apiKeyValueMapUploadOptions) (*bytes.Buffer, erro jsonRootObj.ArrayAppend(jsonObj, "keyMapEntryValues") jsonBody, jsonErr := json.Marshal(jsonRootObj) if jsonErr != nil { - return nil, errors.Wrapf(jsonErr, "json payload is invalid for key value map %q", config.KeyValueMapName) + return nil, fmt.Errorf("json payload is invalid for key value map %q: %w", config.KeyValueMapName, jsonErr) } payload := bytes.NewBuffer([]byte(jsonBody)) return payload, nil diff --git a/cmd/apiProviderDownload.go b/cmd/apiProviderDownload.go index 9b2fee28d..1762bfc94 100644 --- a/cmd/apiProviderDownload.go +++ b/cmd/apiProviderDownload.go @@ -12,7 +12,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type apiProviderDownloadUtils interface { @@ -58,17 +57,17 @@ func runApiProviderDownload(config *apiProviderDownloadOptions, telemetryData *t Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := http.MethodGet downloadResp, httpErr := httpClient.SendRequest(httpMethod, downloadArtifactURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, downloadArtifactURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, downloadArtifactURL, httpErr) } if downloadResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if downloadResp != nil && downloadResp.Body != nil { defer downloadResp.Body.Close() diff --git a/cmd/apiProviderList.go b/cmd/apiProviderList.go index 8c7decc82..a61ed42e5 100644 --- a/cmd/apiProviderList.go +++ b/cmd/apiProviderList.go @@ -9,7 +9,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiProviderList(config apiProviderListOptions, telemetryData *telemetry.CustomData, commonPipelineEnvironment *apiProviderListCommonPipelineEnvironment) { @@ -37,7 +36,7 @@ func getApiProviderList(config *apiProviderListOptions, apistruct apim.Bundle, c Select: config.Select, Expand: config.Expand} odataFilters, urlErr := apim.OdataUtils.MakeOdataQuery(&odataFilterInputs) if urlErr != nil { - return errors.Wrap(urlErr, "failed to create odata filter") + return fmt.Errorf("failed to create odata filter: %w", urlErr) } getApiProviderListURL := fmt.Sprintf("%s/apiportal/api/1.0/Management.svc/APIProviders%s", apistruct.Host, odataFilters) header := make(http.Header) diff --git a/cmd/apiProviderUpload.go b/cmd/apiProviderUpload.go index 811358b00..8225aff2c 100644 --- a/cmd/apiProviderUpload.go +++ b/cmd/apiProviderUpload.go @@ -6,13 +6,14 @@ import ( "net/http" "os" + "errors" + "github.com/SAP/jenkins-library/pkg/apim" "github.com/SAP/jenkins-library/pkg/cpi" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiProviderUpload(config apiProviderUploadOptions, telemetryData *telemetry.CustomData) { diff --git a/cmd/apiProxyDownload.go b/cmd/apiProxyDownload.go index 216483d30..bb3df592f 100644 --- a/cmd/apiProxyDownload.go +++ b/cmd/apiProxyDownload.go @@ -8,7 +8,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiProxyDownload(config apiProxyDownloadOptions, telemetryData *telemetry.CustomData) { @@ -41,17 +40,17 @@ func runApiProxyDownload(config *apiProxyDownloadOptions, telemetryData *telemet Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := http.MethodGet downloadResp, httpErr := httpClient.SendRequest(httpMethod, downloadArtifactURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, downloadArtifactURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, downloadArtifactURL, httpErr) } if downloadResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } failureMessage := "Failed to download API Proxy artefact" httpFileDownloadRequestParameters := cpi.HttpFileDownloadRequestParameters{ErrMessage: failureMessage, FileDownloadPath: config.DownloadPath, Response: downloadResp} diff --git a/cmd/apiProxyList.go b/cmd/apiProxyList.go index 704ca41c6..0d33ce79a 100644 --- a/cmd/apiProxyList.go +++ b/cmd/apiProxyList.go @@ -9,7 +9,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiProxyList(config apiProxyListOptions, telemetryData *telemetry.CustomData, commonPipelineEnvironment *apiProxyListCommonPipelineEnvironment) { @@ -37,7 +36,7 @@ func getApiProxyList(config *apiProxyListOptions, apistruct apim.Bundle, commonP Select: config.Select, Expand: config.Expand} odataFilters, urlErr := apim.OdataUtils.MakeOdataQuery(&odataFilterInputs) if urlErr != nil { - return errors.Wrap(urlErr, "failed to create odata filter") + return fmt.Errorf("failed to create odata filter: %w", urlErr) } getApiProxyListURL := fmt.Sprintf("%s/apiportal/api/1.0/Management.svc/APIProxies%s", apistruct.Host, odataFilters) header := make(http.Header) diff --git a/cmd/apiProxyUpload.go b/cmd/apiProxyUpload.go index 9f6883c5b..058caf28c 100644 --- a/cmd/apiProxyUpload.go +++ b/cmd/apiProxyUpload.go @@ -7,12 +7,13 @@ import ( "net/http" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/cpi" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func apiProxyUpload(config apiProxyUploadOptions, telemetryData *telemetry.CustomData) { @@ -42,7 +43,7 @@ func runApiProxyUpload(config *apiProxyUploadOptions, telemetryData *telemetry.C tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, tokenErr := cpi.CommonUtils.GetBearerToken(tokenParameters) if tokenErr != nil { - return errors.Wrap(tokenErr, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", tokenErr) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -53,7 +54,7 @@ func runApiProxyUpload(config *apiProxyUploadOptions, telemetryData *telemetry.C header.Add("Accept", "application/zip") fileContent, readError := fileUtils.FileRead(config.FilePath) if readError != nil { - return errors.Wrap(readError, "Error reading file") + return fmt.Errorf("Error reading file: %w", readError) } if !strings.Contains(config.FilePath, "zip") { return errors.New("not valid zip archive") diff --git a/cmd/artifactPrepareVersion.go b/cmd/artifactPrepareVersion.go index d31f57242..dd2cb2b82 100644 --- a/cmd/artifactPrepareVersion.go +++ b/cmd/artifactPrepareVersion.go @@ -21,7 +21,6 @@ import ( "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/versioning" - "github.com/pkg/errors" "github.com/go-git/go-git/v5" gitConfig "github.com/go-git/go-git/v5/config" @@ -133,7 +132,7 @@ func runArtifactPrepareVersion(config *artifactPrepareVersionOptions, telemetryD artifact, err = versioning.GetArtifact(config.BuildTool, config.FilePath, &artifactOpts, utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to retrieve artifact") + return fmt.Errorf("failed to retrieve artifact: %w", err) } } @@ -145,7 +144,7 @@ func runArtifactPrepareVersion(config *artifactPrepareVersionOptions, telemetryD version, err := artifact.GetVersion() if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to retrieve version") + return fmt.Errorf("failed to retrieve version: %w", err) } else if len(version) == 0 { log.SetErrorCategory(log.ErrorConfiguration) return fmt.Errorf("version is empty - please check versioning configuration") @@ -182,7 +181,7 @@ func runArtifactPrepareVersion(config *artifactPrepareVersionOptions, telemetryD worktree, err := getWorktree(repository) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to retrieve git worktree") + return fmt.Errorf("failed to retrieve git worktree: %w", err) } // opening repository does not seem to consider already existing files properly @@ -198,7 +197,7 @@ func runArtifactPrepareVersion(config *artifactPrepareVersionOptions, telemetryD err = artifact.SetVersion(newVersion) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to write version") + return fmt.Errorf("failed to write version: %w", err) } } @@ -222,7 +221,7 @@ func runArtifactPrepareVersion(config *artifactPrepareVersionOptions, telemetryD if strings.Contains(fmt.Sprint(err), "reference already exists") { log.SetErrorCategory(log.ErrorCustom) } - return errors.Wrapf(err, "failed to push changes for version '%v'", newVersion) + return fmt.Errorf("failed to push changes for version '%v': %w", newVersion, err) } } } else { @@ -280,13 +279,13 @@ func openGit() (gitRepository, error) { func getGitCommitID(repository gitRepository) (plumbing.Hash, string, error) { commitID, err := repository.ResolveRevision(plumbing.Revision("HEAD")) if err != nil { - return plumbing.Hash{}, "", errors.Wrap(err, "failed to retrieve git commit ID") + return plumbing.Hash{}, "", fmt.Errorf("failed to retrieve git commit ID: %w", err) } // ToDo not too elegant to retrieve the commit message here, must be refactored sooner than later // but to quickly address https://github.com/SAP/jenkins-library/pull/1515 let's revive this commitObject, err := repository.CommitObject(*commitID) if err != nil { - return *commitID, "", errors.Wrap(err, "failed to retrieve git commit message") + return *commitID, "", fmt.Errorf("failed to retrieve git commit message: %w", err) } return *commitID, commitObject.Message, nil } @@ -315,7 +314,7 @@ func versioningTemplate(scheme string) (string, error) { func calculateNewVersion(versioningTemplate, currentVersion, commitID string, includeCommitID, shortCommitID, unixTimestamp bool, t time.Time) (string, error) { tmpl, err := template.New("version").Parse(versioningTemplate) if err != nil { - return "", errors.Wrapf(err, "failed to create version template: %v", versioningTemplate) + return "", fmt.Errorf("failed to create version template: %v: %w", versioningTemplate, err) } timestamp := t.Format("20060102150405") @@ -342,7 +341,7 @@ func calculateNewVersion(versioningTemplate, currentVersion, commitID string, in err = tmpl.Execute(buf, versionParts) if err != nil { - return "", errors.Wrapf(err, "failed to execute versioning template: %v", versioningTemplate) + return "", fmt.Errorf("failed to execute versioning template: %v: %w", versioningTemplate, err) } newVersion := buf.String() @@ -356,7 +355,7 @@ func initializeWorktree(gitCommit plumbing.Hash, worktree gitWorktree) error { // checkout current revision in order to work on that err := worktree.Checkout(&git.CheckoutOptions{Hash: gitCommit, Keep: true}) if err != nil { - return errors.Wrap(err, "failed to initialize worktree") + return fmt.Errorf("failed to initialize worktree: %w", err) } return nil @@ -388,7 +387,7 @@ func pushChanges(config *artifactPrepareVersionOptions, newVersion string, repos currentRemoteOrigin, err := repository.Remote("origin") if err != nil { - return commitID, errors.Wrap(err, "failed to retrieve current remote origin") + return commitID, fmt.Errorf("failed to retrieve current remote origin: %w", err) } var updatedRemoteOrigin *git.Remote @@ -407,17 +406,17 @@ func pushChanges(config *artifactPrepareVersionOptions, newVersion string, repos // update remote origin url to point to ssh url instead of http(s) url err = repository.DeleteRemote("origin") if err != nil { - return commitID, errors.Wrap(err, "failed to update remote origin - remove") + return commitID, fmt.Errorf("failed to update remote origin - remove: %w", err) } updatedRemoteOrigin, err = repository.CreateRemote(&gitConfig.RemoteConfig{Name: "origin", URLs: []string{remoteURL}}) if err != nil { - return commitID, errors.Wrap(err, "failed to update remote origin - create") + return commitID, fmt.Errorf("failed to update remote origin - create: %w", err) } pushOptions.Auth, err = sshAgentAuth("git") if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return commitID, errors.Wrap(err, "failed to retrieve ssh authentication") + return commitID, fmt.Errorf("failed to retrieve ssh authentication: %w", err) } log.Entry().Infof("using remote '%v'", remoteURL) } else { @@ -427,7 +426,7 @@ func pushChanges(config *artifactPrepareVersionOptions, newVersion string, repos pushOptions.Auth, err = sshAgentAuth("git") if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return commitID, errors.Wrap(err, "failed to retrieve ssh authentication") + return commitID, fmt.Errorf("failed to retrieve ssh authentication: %w", err) } } @@ -444,7 +443,7 @@ func pushChanges(config *artifactPrepareVersionOptions, newVersion string, repos case strings.Contains(errText, "authentication required"): log.SetErrorCategory(log.ErrorConfiguration) case strings.Contains(errText, "knownhosts:"): - err = errors.Wrap(err, "known_hosts file seems invalid") + err = fmt.Errorf("known_hosts file seems invalid: %w", err) log.SetErrorCategory(log.ErrorConfiguration) case strings.Contains(errText, "unable to find any valid known_hosts file"): log.SetErrorCategory(log.ErrorConfiguration) @@ -457,11 +456,11 @@ func pushChanges(config *artifactPrepareVersionOptions, newVersion string, repos if updatedRemoteOrigin != currentRemoteOrigin { err = repository.DeleteRemote("origin") if err != nil { - return commitID, errors.Wrap(err, "failed to restore remote origin - remove") + return commitID, fmt.Errorf("failed to restore remote origin - remove: %w", err) } _, err := repository.CreateRemote(currentRemoteOrigin.Config()) if err != nil { - return commitID, errors.Wrap(err, "failed to restore remote origin - create") + return commitID, fmt.Errorf("failed to restore remote origin - create: %w", err) } } @@ -475,7 +474,7 @@ func addAndCommit(config *artifactPrepareVersionOptions, worktree gitWorktree, n st, err := worktree.Status() if err != nil { log.Entry().Debug("error checking commit status") - return plumbing.ZeroHash, errors.Wrap(err, "failed to read worktree status") + return plumbing.ZeroHash, fmt.Errorf("failed to read worktree status: %w", err) } log.Entry().Debug("ranging through commit status") @@ -500,7 +499,7 @@ func addAndCommit(config *artifactPrepareVersionOptions, worktree gitWorktree, n Author: &object.Signature{Name: config.CommitUserName, When: t}, }) if err != nil { - return commit, errors.Wrap(err, "failed to commit new version") + return commit, fmt.Errorf("failed to commit new version: %w", err) } return commit, nil } @@ -550,12 +549,12 @@ func calculateCloudVersion(artifact versioning.Artifact, config *artifactPrepare versioningTempl, err := versioningTemplate(artifact.VersioningScheme()) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return "", errors.Wrapf(err, "failed to get versioning template for scheme '%v'", artifact.VersioningScheme()) + return "", fmt.Errorf("failed to get versioning template for scheme '%v': %w", artifact.VersioningScheme(), err) } newVersion, err := calculateNewVersion(versioningTempl, version, gitCommitID, config.IncludeCommitID, config.ShortCommitID, config.UnixTimestamp, timestamp) if err != nil { - return "", errors.Wrap(err, "failed to calculate new version") + return "", fmt.Errorf("failed to calculate new version: %w", err) } return newVersion, nil } diff --git a/cmd/artifactPrepareVersion_test.go b/cmd/artifactPrepareVersion_test.go index b1ecb6593..929471c32 100644 --- a/cmd/artifactPrepareVersion_test.go +++ b/cmd/artifactPrepareVersion_test.go @@ -5,12 +5,13 @@ package cmd import ( "fmt" - gitHttp "github.com/go-git/go-git/v5/plumbing/transport/http" - "github.com/go-git/go-git/v5/plumbing/transport/ssh" "net/http" "testing" "time" + gitHttp "github.com/go-git/go-git/v5/plumbing/transport/http" + "github.com/go-git/go-git/v5/plumbing/transport/ssh" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/telemetry" diff --git a/cmd/ascAppUpload.go b/cmd/ascAppUpload.go index 5848ba695..5b4090d61 100644 --- a/cmd/ascAppUpload.go +++ b/cmd/ascAppUpload.go @@ -1,13 +1,15 @@ package cmd import ( + "errors" + "fmt" + "github.com/SAP/jenkins-library/pkg/asc" "github.com/SAP/jenkins-library/pkg/command" piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type ascAppUploadUtils interface { @@ -57,7 +59,7 @@ func runAscAppUpload(config *ascAppUploadOptions, telemetryData *telemetry.Custo app, err := ascClient.GetAppById(config.AppID) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to get app information") + return fmt.Errorf("failed to get app information: %w", err) } log.Entry().Debugf("Found App with name %v", app.AppName) @@ -68,7 +70,7 @@ func runAscAppUpload(config *ascAppUploadOptions, telemetryData *telemetry.Custo if err != nil { log.SetErrorCategory(log.ErrorService) - return errors.Wrap(err, "failed to create release") + return fmt.Errorf("failed to create release: %w", err) } if releaseResponse.Status != "success" { @@ -81,13 +83,13 @@ func runAscAppUpload(config *ascAppUploadOptions, telemetryData *telemetry.Custo jamfAppInformationResponse, err := ascClient.GetJamfAppInfo(app.BundleId, config.JamfTargetSystem) if err != nil { log.SetErrorCategory(log.ErrorService) - return errors.Wrap(err, "failed to get jamf app info") + return fmt.Errorf("failed to get jamf app info: %w", err) } jamfAppId := jamfAppInformationResponse.MobileDeviceApplication.General.Id if jamfAppId == 0 { - return errors.Errorf("failed to get jamf app id") + return fmt.Errorf("failed to get jamf app id") } log.Entry().Debugf("Got Jamf info for app %v, jamfId: %v", app.AppName, jamfAppId) @@ -97,7 +99,7 @@ func runAscAppUpload(config *ascAppUploadOptions, telemetryData *telemetry.Custo err = ascClient.UploadIpa(config.FilePath, jamfAppId, config.JamfTargetSystem, app.BundleId, releaseResponse.Data) if err != nil { log.SetErrorCategory(log.ErrorService) - return errors.Wrap(err, "failed to upload ipa") + return fmt.Errorf("failed to upload ipa: %w", err) } log.Entry().Infof("Successfully uploaded %v to ASC (AppId %v) & Jamf (Id %v)", config.FilePath, app.AppId, jamfAppId) diff --git a/cmd/ascAppUpload_test.go b/cmd/ascAppUpload_test.go index fd4e5cc4f..3360187cd 100644 --- a/cmd/ascAppUpload_test.go +++ b/cmd/ascAppUpload_test.go @@ -4,13 +4,14 @@ package cmd import ( + "errors" "fmt" - "github.com/SAP/jenkins-library/pkg/asc" - "github.com/SAP/jenkins-library/pkg/mock" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "testing" "time" + + "github.com/SAP/jenkins-library/pkg/asc" + "github.com/SAP/jenkins-library/pkg/mock" + "github.com/stretchr/testify/assert" ) type ascAppUploadMockUtils struct { diff --git a/cmd/batsExecuteTests.go b/cmd/batsExecuteTests.go index 4bdfbbaeb..0a0cf1fa9 100644 --- a/cmd/batsExecuteTests.go +++ b/cmd/batsExecuteTests.go @@ -2,6 +2,7 @@ package cmd import ( "bytes" + "errors" "fmt" "io" "os" @@ -12,7 +13,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/go-git/go-git/v5" - "github.com/pkg/errors" ) type batsExecuteTestsUtils interface { diff --git a/cmd/batsExecuteTests_test.go b/cmd/batsExecuteTests_test.go index 3956b3124..0fb721539 100644 --- a/cmd/batsExecuteTests_test.go +++ b/cmd/batsExecuteTests_test.go @@ -7,9 +7,10 @@ import ( "fmt" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/go-git/go-git/v5" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/checkIfStepActive.go b/cmd/checkIfStepActive.go index 9a10fd43a..5eea37dd5 100644 --- a/cmd/checkIfStepActive.go +++ b/cmd/checkIfStepActive.go @@ -6,7 +6,8 @@ import ( "io" "os" - "github.com/pkg/errors" + "errors" + "github.com/spf13/cobra" "github.com/SAP/jenkins-library/pkg/config" @@ -72,12 +73,12 @@ func checkIfStepActive(utils piperutils.FileUtils) error { projectConfig, err := initializeConfig(&pConfig) if err != nil { log.Entry().Errorf("Failed to load project config: %v", err) - return errors.Wrap(err, "Failed to load project config failed") + return fmt.Errorf("Failed to load project config failed: %w", err) } stageConfigFile, err := checkStepActiveOptions.openFile(checkStepActiveOptions.stageConfigFile, GeneralConfig.GitHubAccessTokens) if err != nil { - return errors.Wrapf(err, "config: open stage configuration file '%v' failed", checkStepActiveOptions.stageConfigFile) + return fmt.Errorf("config: open stage configuration file '%v' failed: %w", checkStepActiveOptions.stageConfigFile, err) } defer stageConfigFile.Close() @@ -124,7 +125,7 @@ func checkIfStepActive(utils piperutils.FileUtils) error { } if !runSteps[checkStepActiveOptions.stageName][checkStepActiveOptions.stepName] { - return errors.Errorf("Step %s in stage %s is not active", checkStepActiveOptions.stepName, checkStepActiveOptions.stageName) + return fmt.Errorf("Step %s in stage %s is not active", checkStepActiveOptions.stepName, checkStepActiveOptions.stageName) } log.Entry().Infof("Step %s in stage %s is active", checkStepActiveOptions.stepName, checkStepActiveOptions.stageName) @@ -151,7 +152,7 @@ func initializeConfig(pConfig *config.Config) (*config.Config, error) { log.Entry().Infof("Project config: '%s'", projectConfigFile) customConfig, err = checkStepActiveOptions.openFile(projectConfigFile, GeneralConfig.GitHubAccessTokens) if err != nil { - return nil, errors.Wrapf(err, "config: open configuration file '%v' failed", projectConfigFile) + return nil, fmt.Errorf("config: open configuration file '%v' failed: %w", projectConfigFile, err) } defer customConfig.Close() } else { @@ -163,7 +164,7 @@ func initializeConfig(pConfig *config.Config) (*config.Config, error) { fc, err := checkStepActiveOptions.openFile(f, GeneralConfig.GitHubAccessTokens) // only create error for non-default values if err != nil && f != ".pipeline/defaults.yaml" { - return nil, errors.Wrapf(err, "config: getting defaults failed: '%v'", f) + return nil, fmt.Errorf("config: getting defaults failed: '%v': %w", f, err) } if err == nil { defaultConfig = append(defaultConfig, fc) @@ -180,7 +181,7 @@ func initializeConfig(pConfig *config.Config) (*config.Config, error) { _, err = pConfig.GetStepConfig(flags, "", customConfig, defaultConfig, GeneralConfig.IgnoreCustomDefaults, filter, config.StepData{}, nil, "", "") if err != nil { - return nil, errors.Wrap(err, "getting step config failed") + return nil, fmt.Errorf("getting step config failed: %w", err) } return pConfig, nil } diff --git a/cmd/checkmarxExecuteScan.go b/cmd/checkmarxExecuteScan.go index dd1865d6f..13d25222c 100644 --- a/cmd/checkmarxExecuteScan.go +++ b/cmd/checkmarxExecuteScan.go @@ -16,6 +16,8 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/checkmarx" piperGithub "github.com/SAP/jenkins-library/pkg/github" piperHttp "github.com/SAP/jenkins-library/pkg/http" @@ -25,7 +27,6 @@ import ( "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/toolrecord" "github.com/bmatcuk/doublestar" - "github.com/pkg/errors" "github.com/google/go-github/v68/github" ) @@ -132,7 +133,7 @@ func runScan(ctx context.Context, config checkmarxExecuteScanOptions, sys checkm } project, projectName, err := loadExistingProject(sys, config.ProjectName, config.PullRequestName, teamID) if err != nil { - return errors.Wrap(err, "error when trying to load project") + return fmt.Errorf("error when trying to load project: %w", err) } if strings.EqualFold(project.Name, projectName) { // case insensitive string comparison err = presetExistingProject(config, sys, projectName, project) @@ -141,7 +142,7 @@ func runScan(ctx context.Context, config checkmarxExecuteScanOptions, sys checkm } } else { if len(teamID) == 0 { - return errors.Wrap(err, "TeamName or TeamID is required to create a new project") + return fmt.Errorf("TeamName or TeamID is required to create a new project: %w", err) } project, err = createNewProject(config, sys, projectName, teamID) if err != nil { @@ -151,7 +152,7 @@ func runScan(ctx context.Context, config checkmarxExecuteScanOptions, sys checkm err = uploadAndScan(ctx, config, sys, project, influx, utils) if err != nil { - return errors.Wrap(err, "scan, upload, and result validation returned an error") + return fmt.Errorf("scan, upload, and result validation returned an error: %w", err) } return nil } @@ -159,7 +160,7 @@ func runScan(ctx context.Context, config checkmarxExecuteScanOptions, sys checkm func loadTeamIDByTeamName(config checkmarxExecuteScanOptions, sys checkmarx.System, teamID string) (string, error) { team, err := loadTeam(sys, config.TeamName) if err != nil { - return "", errors.Wrap(err, "failed to load team") + return "", fmt.Errorf("failed to load team: %w", err) } teamIDBytes, _ := team.ID.MarshalJSON() err = json.Unmarshal(teamIDBytes, &teamID) @@ -167,7 +168,7 @@ func loadTeamIDByTeamName(config checkmarxExecuteScanOptions, sys checkmarx.Syst var teamIDInt int err = json.Unmarshal(teamIDBytes, &teamIDInt) if err != nil { - return "", errors.Wrap(err, "failed to unmarshall team.ID") + return "", fmt.Errorf("failed to unmarshall team.ID: %w", err) } teamID = strconv.Itoa(teamIDInt) } @@ -179,7 +180,7 @@ func createNewProject(config checkmarxExecuteScanOptions, sys checkmarx.System, presetID, _ := strconv.Atoi(config.Preset) project, err := createAndConfigureNewProject(sys, projectName, teamID, presetID, config.Preset, config.EngineConfigurationID) if err != nil { - return checkmarx.Project{}, errors.Wrapf(err, "failed to create and configure new project %v", projectName) + return checkmarx.Project{}, fmt.Errorf("failed to create and configure new project %v: %w", projectName, err) } return project, nil } @@ -190,7 +191,7 @@ func presetExistingProject(config checkmarxExecuteScanOptions, sys checkmarx.Sys presetID, _ := strconv.Atoi(config.Preset) err := setPresetForProject(sys, project.ID, presetID, projectName, config.Preset, config.EngineConfigurationID) if err != nil { - return errors.Wrapf(err, "failed to set preset %v for project %v", config.Preset, projectName) + return fmt.Errorf("failed to set preset %v for project %v: %w", config.Preset, projectName, err) } } return nil @@ -222,7 +223,7 @@ func loadExistingProject(sys checkmarx.System, initialProjectName, pullRequestNa if err != nil || len(projects) == 0 { projects, err = sys.GetProjectsByNameAndTeam(initialProjectName, teamID) if err != nil { - return project, projectName, errors.Wrap(err, "failed getting projects") + return project, projectName, fmt.Errorf("failed getting projects: %w", err) } if len(projects) == 0 { return checkmarx.Project{}, projectName, nil @@ -239,7 +240,7 @@ func loadExistingProject(sys checkmarx.System, initialProjectName, pullRequestNa } else { projects, err := sys.GetProjectsByNameAndTeam(projectName, teamID) if err != nil { - return project, projectName, errors.Wrap(err, "failed getting projects") + return project, projectName, fmt.Errorf("failed getting projects: %w", err) } if len(projects) == 0 { return checkmarx.Project{}, projectName, nil @@ -268,12 +269,12 @@ func zipWorkspaceFiles(filterPattern string, utils checkmarxExecuteScanUtils) (* sort.Strings(patterns) zipFile, err := os.Create(zipFileName) if err != nil { - return zipFile, errors.Wrap(err, "failed to create archive of project sources") + return zipFile, fmt.Errorf("failed to create archive of project sources: %w", err) } defer zipFile.Close() err = zipFolder(utils.GetWorkspace(), zipFile, patterns, utils) if err != nil { - return nil, errors.Wrap(err, "failed to compact folder") + return nil, fmt.Errorf("failed to compact folder: %w", err) } return zipFile, nil } @@ -287,16 +288,16 @@ func uploadAndScan(ctx context.Context, config checkmarxExecuteScanOptions, sys err := verifyCxProjectCompliance(ctx, config, sys, previousScans[0].ID, influx, utils) if err != nil { log.SetErrorCategory(log.ErrorCompliance) - return errors.Wrapf(err, "project %v not compliant", project.Name) + return fmt.Errorf("project %v not compliant: %w", project.Name, err) } } else { zipFile, err := zipWorkspaceFiles(config.FilterPattern, utils) if err != nil { - return errors.Wrap(err, "failed to zip workspace files") + return fmt.Errorf("failed to zip workspace files: %w", err) } err = sys.UploadProjectSourceCode(project.ID, zipFile.Name()) if err != nil { - return errors.Wrapf(err, "failed to upload source code for project %v", project.Name) + return fmt.Errorf("failed to upload source code for project %v: %w", project.Name, err) } log.Entry().Debugf("Source code uploaded for project %v", project.Name) @@ -309,7 +310,7 @@ func uploadAndScan(ctx context.Context, config checkmarxExecuteScanOptions, sys fullScanCycle, err := strconv.Atoi(config.FullScanCycle) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "invalid configuration value for fullScanCycle %v, must be a positive int", config.FullScanCycle) + return fmt.Errorf("invalid configuration value for fullScanCycle %v, must be a positive int: %w", config.FullScanCycle, err) } if config.IsOptimizedAndScheduled { @@ -342,13 +343,13 @@ func isLastScanFailedIncremental(scans []checkmarx.ScanStatus) bool { func triggerScan(ctx context.Context, config checkmarxExecuteScanOptions, sys checkmarx.System, project checkmarx.Project, incremental bool, influx *checkmarxExecuteScanInflux, utils checkmarxExecuteScanUtils) error { scan, err := sys.ScanProject(project.ID, incremental, true, !config.AvoidDuplicateProjectScans) if err != nil { - return errors.Wrapf(err, "cannot scan project %v", project.Name) + return fmt.Errorf("cannot scan project %v: %w", project.Name, err) } log.Entry().Debugf("Scanning project %v ", project.Name) err = pollScanStatus(sys, scan) if err != nil { - return errors.Wrap(err, "polling scan status failed") + return fmt.Errorf("polling scan status failed: %w", err) } log.Entry().Debugln("Scan finished") @@ -372,7 +373,7 @@ func verifyCxProjectCompliance(ctx context.Context, config checkmarxExecuteScanO xmlReportName := createReportName(utils.GetWorkspace(), "CxSASTResults_%v.xml") results, err := getDetailedResults(config, sys, xmlReportName, scanID, utils) if err != nil { - return errors.Wrap(err, "failed to get detailed results") + return fmt.Errorf("failed to get detailed results: %w", err) } reports = append(reports, piperutils.Path{Target: xmlReportName}) @@ -552,7 +553,7 @@ func reportToInflux(results map[string]interface{}, influx *checkmarxExecuteScan func downloadAndSaveReport(sys checkmarx.System, reportFileName string, scanID int, utils checkmarxExecuteScanUtils) error { report, err := generateAndDownloadReport(sys, scanID, "PDF") if err != nil { - return errors.Wrap(err, "failed to download the report") + return fmt.Errorf("failed to download the report: %w", err) } log.Entry().Debugf("Saving report to file %v...", reportFileName) return utils.WriteFile(reportFileName, report, 0o700) @@ -684,16 +685,16 @@ func createAndConfigureNewProject(sys checkmarx.System, projectName, teamID stri projectCreateResult, err := sys.CreateProject(projectName, teamID) if err != nil { - return checkmarx.Project{}, errors.Wrapf(err, "cannot create project %v", projectName) + return checkmarx.Project{}, fmt.Errorf("cannot create project %v: %w", projectName, err) } if err := setPresetForProject(sys, projectCreateResult.ID, presetIDValue, projectName, presetValue, engineConfiguration); err != nil { - return checkmarx.Project{}, errors.Wrapf(err, "failed to set preset %v for project", presetValue) + return checkmarx.Project{}, fmt.Errorf("failed to set preset %v for project: %w", presetValue, err) } projects, err := sys.GetProjectsByNameAndTeam(projectName, teamID) if err != nil || len(projects) == 0 { - return checkmarx.Project{}, errors.Wrapf(err, "failed to load newly created project %v", projectName) + return checkmarx.Project{}, fmt.Errorf("failed to load newly created project %v: %w", projectName, err) } log.Entry().Debugf("New Project %v created", projectName) log.Entry().Debugf("Projects: %v", projects) @@ -726,13 +727,13 @@ func setPresetForProject(sys checkmarx.System, projectID, presetIDValue int, pro if presetID <= 0 { preset, err := loadPreset(sys, presetValue) if err != nil { - return errors.Wrapf(err, "preset %v not found, configuration of project %v failed", presetValue, projectName) + return fmt.Errorf("preset %v not found, configuration of project %v failed: %w", presetValue, projectName, err) } presetID = preset.ID } err := sys.UpdateProjectConfiguration(projectID, presetID, engineConfiguration) if err != nil { - return errors.Wrapf(err, "updating configuration of project %v failed", projectName) + return fmt.Errorf("updating configuration of project %v failed: %w", projectName, err) } return nil } @@ -740,13 +741,13 @@ func setPresetForProject(sys checkmarx.System, projectID, presetIDValue int, pro func generateAndDownloadReport(sys checkmarx.System, scanID int, reportType string) ([]byte, error) { report, err := sys.RequestNewReport(scanID, reportType) if err != nil { - return []byte{}, errors.Wrap(err, "failed to request new report") + return []byte{}, fmt.Errorf("failed to request new report: %w", err) } finalStatus := 1 for { reportStatus, err := sys.GetReportStatus(report.ReportID) if err != nil { - return []byte{}, errors.Wrap(err, "failed to get report status") + return []byte{}, fmt.Errorf("failed to get report status: %w", err) } finalStatus = reportStatus.Status.ID if finalStatus != 1 { @@ -775,17 +776,17 @@ func getDetailedResults(config checkmarxExecuteScanOptions, sys checkmarx.System resultMap := map[string]interface{}{} data, err := generateAndDownloadReport(sys, scanID, "XML") if err != nil { - return resultMap, errors.Wrap(err, "failed to download xml report") + return resultMap, fmt.Errorf("failed to download xml report: %w", err) } if len(data) > 0 { err = utils.WriteFile(reportFileName, data, 0o700) if err != nil { - return resultMap, errors.Wrap(err, "failed to write file") + return resultMap, fmt.Errorf("failed to write file: %w", err) } var xmlResult checkmarx.DetailedResult err := xml.Unmarshal(data, &xmlResult) if err != nil { - return resultMap, errors.Wrapf(err, "failed to unmarshal XML report for scan %v", scanID) + return resultMap, fmt.Errorf("failed to unmarshal XML report for scan %v: %w", scanID, err) } resultMap["InitiatorName"] = xmlResult.InitiatorName resultMap["Owner"] = xmlResult.Owner @@ -979,7 +980,7 @@ func isFileNotMatchingPattern(patterns []string, path string, info os.FileInfo, } match, err := utils.PathMatch(pattern, path) if err != nil { - return false, errors.Wrapf(err, "Pattern %v could not get executed", pattern) + return false, fmt.Errorf("Pattern %v could not get executed: %w", pattern, err) } if match { diff --git a/cmd/checkmarxOneExecuteScan.go b/cmd/checkmarxOneExecuteScan.go index 5de15b154..d5c7da851 100644 --- a/cmd/checkmarxOneExecuteScan.go +++ b/cmd/checkmarxOneExecuteScan.go @@ -28,7 +28,6 @@ import ( "github.com/SAP/jenkins-library/pkg/toolrecord" "github.com/bmatcuk/doublestar" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" ) type checkmarxOneExecuteScanUtils interface { @@ -467,7 +466,7 @@ func (c *checkmarxOneExecuteScanHelper) IncrementalOrFull(scans []checkmarxOne.S scanMetadatas, err := c.sys.GetScanMetadatas(scanIds) if err != nil { - return false, false, 0, errors.Wrapf(err, "failed to fetch metadata for scans") + return false, false, 0, fmt.Errorf("failed to fetch metadata for scans: %w", err) } contiguousIncrementalScans := 0 @@ -973,7 +972,7 @@ func (c *checkmarxOneExecuteScanHelper) createReportName(workspace, reportFileNa func (c *checkmarxOneExecuteScanHelper) downloadAndSaveReport(reportFileName string, scan *checkmarxOne.Scan, reportType string) error { report, err := c.generateAndDownloadReport(scan, reportType) if err != nil { - return errors.Wrap(err, "failed to download the report") + return fmt.Errorf("failed to download the report: %w", err) } log.Entry().Debugf("Saving report to file %v...", reportFileName) return c.utils.WriteFile(reportFileName, report, 0o700) @@ -984,12 +983,12 @@ func (c *checkmarxOneExecuteScanHelper) generateAndDownloadReport(scan *checkmar report, err := c.sys.RequestNewReport(scan.ScanID, scan.ProjectID, scan.Branch, reportType) if err != nil { - return []byte{}, errors.Wrap(err, "failed to request new report") + return []byte{}, fmt.Errorf("failed to request new report: %w", err) } for { finalStatus, err = c.sys.GetReportStatus(report) if err != nil { - return []byte{}, errors.Wrap(err, "failed to get report status") + return []byte{}, fmt.Errorf("failed to get report status: %w", err) } if finalStatus.Status == "completed" { @@ -1180,13 +1179,13 @@ func (c *checkmarxOneExecuteScanHelper) zipWorkspaceFiles(filterPattern string, sort.Strings(patterns) zipFile, err := os.Create(zipFileName) if err != nil { - return zipFile, errors.Wrap(err, "failed to create archive of project sources") + return zipFile, fmt.Errorf("failed to create archive of project sources: %w", err) } defer zipFile.Close() err = c.zipFolder(utils.GetWorkspace(), zipFile, patterns, utils) if err != nil { - return nil, errors.Wrap(err, "failed to compact folder") + return nil, fmt.Errorf("failed to compact folder: %w", err) } return zipFile, nil } @@ -1282,7 +1281,7 @@ func (c *checkmarxOneExecuteScanHelper) isFileNotMatchingPattern(patterns []stri } match, err := utils.PathMatch(pattern, path) if err != nil { - return false, errors.Wrapf(err, "Pattern %v could not get executed", pattern) + return false, fmt.Errorf("Pattern %v could not get executed: %w", pattern, err) } if match { includeMatch = true @@ -1303,7 +1302,7 @@ func (c *checkmarxOneExecuteScanHelper) isFileNotMatchingPattern(patterns []stri } match, err := utils.PathMatch(pattern, path) if err != nil { - return false, errors.Wrapf(err, "Pattern %v could not get executed", pattern) + return false, fmt.Errorf("Pattern %v could not get executed: %w", pattern, err) } if match { // match with an exclude pattern, the file is excluded diff --git a/cmd/checkmarxOneExecuteScan_test.go b/cmd/checkmarxOneExecuteScan_test.go index f22d2b1cc..8335b4137 100644 --- a/cmd/checkmarxOneExecuteScan_test.go +++ b/cmd/checkmarxOneExecuteScan_test.go @@ -11,7 +11,6 @@ import ( checkmarxOne "github.com/SAP/jenkins-library/pkg/checkmarxone" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) type checkmarxOneSystemMock struct { @@ -214,7 +213,7 @@ func (sys *checkmarxOneSystemMock) GetGroupByName(groupName string) (checkmarxOn } } - return group, errors.New(fmt.Sprintf("No group matching %v", groupName)) + return group, fmt.Errorf("No group matching %v", groupName) } func (sys *checkmarxOneSystemMock) GetGroupByID(groupID string) (checkmarxOne.Group, error) { diff --git a/cmd/cloudFoundryCreateService.go b/cmd/cloudFoundryCreateService.go index e1ca6f73d..70eafcbcd 100644 --- a/cmd/cloudFoundryCreateService.go +++ b/cmd/cloudFoundryCreateService.go @@ -7,7 +7,6 @@ import ( "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func cloudFoundryCreateService(config cloudFoundryCreateServiceOptions, telemetryData *telemetry.CustomData) { @@ -83,14 +82,14 @@ func cloudFoundryCreateServiceRequest(config *cloudFoundryCreateServiceOptions, if len(config.ManifestVariablesFiles) >= 0 { varFileOpts, err := cloudfoundry.GetVarsFileOptions(config.ManifestVariablesFiles) if err != nil { - return errors.Wrapf(err, "Cannot prepare var-file-options: '%v'", config.ManifestVariablesFiles) + return fmt.Errorf("Cannot prepare var-file-options: '%v': %w", config.ManifestVariablesFiles, err) } cfCreateServiceScript = append(cfCreateServiceScript, varFileOpts...) } if len(config.ManifestVariables) >= 0 { varOptions, err := cloudfoundry.GetVarsOptions(config.ManifestVariables) if err != nil { - return errors.Wrapf(err, "Cannot prepare var-options: '%v'", config.ManifestVariables) + return fmt.Errorf("Cannot prepare var-options: '%v': %w", config.ManifestVariables, err) } cfCreateServiceScript = append(cfCreateServiceScript, varOptions...) } diff --git a/cmd/cloudFoundryCreateServiceKey_test.go b/cmd/cloudFoundryCreateServiceKey_test.go index dc886c733..4c983dd52 100644 --- a/cmd/cloudFoundryCreateServiceKey_test.go +++ b/cmd/cloudFoundryCreateServiceKey_test.go @@ -6,10 +6,11 @@ package cmd import ( "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/cloudfoundry" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/cloudFoundryCreateSpace_test.go b/cmd/cloudFoundryCreateSpace_test.go index c29f30a90..020bd249b 100644 --- a/cmd/cloudFoundryCreateSpace_test.go +++ b/cmd/cloudFoundryCreateSpace_test.go @@ -7,10 +7,11 @@ import ( "fmt" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/cloudfoundry" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/cloudFoundryDeploy.go b/cmd/cloudFoundryDeploy.go index 6e9ac1366..e7cb683ea 100644 --- a/cmd/cloudFoundryDeploy.go +++ b/cmd/cloudFoundryDeploy.go @@ -11,13 +11,14 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/cloudfoundry" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/yaml" - "github.com/pkg/errors" ) type cfFileUtil interface { @@ -205,7 +206,7 @@ func handleMTADeployment(config *cloudFoundryDeployOptions, command command.Exec exists, err := fileUtils.FileExists(mtarFilePath) if err != nil { - return errors.Wrapf(err, "Cannot check if file path '%s' exists", mtarFilePath) + return fmt.Errorf("Cannot check if file path '%s' exists: %w", mtarFilePath, err) } if !exists { @@ -242,7 +243,7 @@ func handleCFNativeDeployment(config *cloudFoundryDeployOptions, command command } else if config.DeployType == "standard" { deployCommand, deployOptions, err = prepareCfPushCfNativeDeploy(config) if err != nil { - return errors.Wrapf(err, "Cannot prepare cf push native deployment. DeployType '%s'", config.DeployType) + return fmt.Errorf("Cannot prepare cf push native deployment. DeployType '%s': %w", config.DeployType, err) } } else { return fmt.Errorf("Invalid deploy type received: '%s'. Supported value: standard", config.DeployType) @@ -337,7 +338,7 @@ func getAppName(config *cloudFoundryDeployOptions) (string, error) { fileExists, err := fileUtils.FileExists(manifestFile) if err != nil { - return "", errors.Wrapf(err, "Cannot check if file '%s' exists", manifestFile) + return "", fmt.Errorf("Cannot check if file '%s' exists: %w", manifestFile, err) } if !fileExists { return "", fmt.Errorf("Manifest file '%s' not found. Cannot retrieve app name", manifestFile) @@ -381,7 +382,7 @@ func prepareCfPushCfNativeDeploy(config *cloudFoundryDeployOptions) (string, []s deployOptions := []string{} varOptions, err := _getVarsOptions(config.ManifestVariables) if err != nil { - return "", []string{}, errors.Wrapf(err, "Cannot prepare var-options: '%v'", config.ManifestVariables) + return "", []string{}, fmt.Errorf("Cannot prepare var-options: '%v': %w", config.ManifestVariables, err) } varFileOptions, err := _getVarsFileOptions(config.ManifestVariablesFiles) @@ -391,7 +392,7 @@ func prepareCfPushCfNativeDeploy(config *cloudFoundryDeployOptions) (string, []s log.Entry().Warningf("We skip adding not-existing file '%s' as a vars-file to the cf create-service-push call", missingVarFile) } } else { - return "", []string{}, errors.Wrapf(err, "Cannot prepare var-file-options: '%v'", config.ManifestVariablesFiles) + return "", []string{}, fmt.Errorf("Cannot prepare var-file-options: '%v': %w", config.ManifestVariablesFiles, err) } } @@ -462,13 +463,13 @@ func handleMtaExtensionCredentials(extFile string, credentials map[string]interf b, err := fileUtils.FileRead(extFile) if err != nil { - return false, false, errors.Wrapf(err, "Cannot handle credentials for mta extension file '%s'", extFile) + return false, false, fmt.Errorf("Cannot handle credentials for mta extension file '%s': %w", extFile, err) } content := string(b) env, err := toMap(_environ(), "=") if err != nil { - return false, false, errors.Wrap(err, "Cannot handle mta extension credentials.") + return false, false, fmt.Errorf("Cannot handle mta extension credentials.: %w", err) } missingCredentials := []string{} @@ -513,11 +514,11 @@ func handleMtaExtensionCredentials(extFile string, credentials map[string]interf fInfo, err := fileUtils.Stat(extFile) fMode := fInfo.Mode() if err != nil { - return false, false, errors.Wrap(err, "Cannot handle mta extension credentials.") + return false, false, fmt.Errorf("Cannot handle mta extension credentials.: %w", err) } err = fileUtils.FileWrite(extFile, []byte(content), fMode) if err != nil { - return false, false, errors.Wrap(err, "Cannot handle mta extension credentials.") + return false, false, fmt.Errorf("Cannot handle mta extension credentials.: %w", err) } log.Entry().Debugf("Mta extension credentials handling: Extension file '%s' has been updated.", extFile) } diff --git a/cmd/cnbBuild.go b/cmd/cnbBuild.go index cd4dac06b..a8e6e3abb 100644 --- a/cmd/cnbBuild.go +++ b/cmd/cnbBuild.go @@ -24,7 +24,7 @@ import ( "github.com/SAP/jenkins-library/pkg/syft" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" + ignore "github.com/sabhiram/go-gitignore" ) @@ -166,14 +166,14 @@ func extractZip(source, target string) error { err := verifyZip(source) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "'%s' is not a valid archive", source) + return fmt.Errorf("'%s' is not a valid archive: %w", source, err) } log.Entry().Infof("Extracting archive '%s' to '%s'", source, target) _, err = piperutils.Unzip(source, target) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Extracting archive '%s' to '%s' failed", source, target) + return fmt.Errorf("Extracting archive '%s' to '%s' failed: %w", source, target, err) } return nil } @@ -242,7 +242,7 @@ func (config *cnbBuildOptions) resolvePath(utils cnbutils.BuildUtils) (buildpack pwd, err := utils.Getwd() if err != nil { log.SetErrorCategory(log.ErrorBuild) - return "", "", errors.Wrap(err, "failed to get current working directory") + return "", "", fmt.Errorf("failed to get current working directory: %w", err) } if config.Path == "" { @@ -251,23 +251,23 @@ func (config *cnbBuildOptions) resolvePath(utils cnbutils.BuildUtils) (buildpack matches, err := utils.Glob(config.Path) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return "", "", errors.Wrapf(err, "Failed to resolve glob for '%s'", config.Path) + return "", "", fmt.Errorf("Failed to resolve glob for '%s': %w", config.Path, err) } numMatches := len(matches) if numMatches != 1 { log.SetErrorCategory(log.ErrorConfiguration) - return "", "", errors.Errorf("Failed to resolve glob for '%s', matching %d file(s)", config.Path, numMatches) + return "", "", fmt.Errorf("Failed to resolve glob for '%s', matching %d file(s)", config.Path, numMatches) } source, err := utils.Abs(matches[0]) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return "", "", errors.Wrapf(err, "Failed to resolve absolute path for '%s'", matches[0]) + return "", "", fmt.Errorf("Failed to resolve absolute path for '%s': %w", matches[0], err) } dir, err := utils.DirExists(source) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return "", "", errors.Wrapf(err, "Checking file info '%s' failed", source) + return "", "", fmt.Errorf("Checking file info '%s' failed: %w", source, err) } if dir { @@ -283,7 +283,7 @@ func callCnbBuild(config *cnbBuildOptions, telemetryData *telemetry.CustomData, err := isBuilder(utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "the provided dockerImage is not a valid builder") + return fmt.Errorf("the provided dockerImage is not a valid builder: %w", err) } telemetry := buildpacks.NewTelemetry(telemetryData) @@ -311,7 +311,7 @@ func callCnbBuild(config *cnbBuildOptions, telemetryData *telemetry.CustomData, err = ensureDockerConfig(config, utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to create/rename DockerConfigJSON file") + return fmt.Errorf("failed to create/rename DockerConfigJSON file: %w", err) } if config.DockerConfigJSONCPE != "" { @@ -319,13 +319,13 @@ func callCnbBuild(config *cnbBuildOptions, telemetryData *telemetry.CustomData, err = docker.MergeDockerConfigJSON(config.DockerConfigJSONCPE, config.DockerConfigJSON, utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to merge DockerConfigJSON files") + return fmt.Errorf("failed to merge DockerConfigJSON files: %w", err) } } mergedConfigs, err := processConfigs(*config, config.MultipleImages) if err != nil { - return errors.Wrap(err, "failed to process config") + return fmt.Errorf("failed to process config: %w", err) } buildSummary := cnbutils.NewBuildSummary(dockerImage, utils) @@ -345,7 +345,7 @@ func callCnbBuild(config *cnbBuildOptions, telemetryData *telemetry.CustomData, syftScanner, err := syft.CreateSyftScanner(config.SyftDownloadURL, utils, httpClient) if err != nil { log.SetErrorCategory(log.ErrorCompliance) - return errors.Wrap(err, "failed to create syft scanner file") + return fmt.Errorf("failed to create syft scanner file: %w", err) } // images produces with cnb have sboms syftScanner.AddArgument("--override-default-catalogers=sbom-cataloger,go-module-binary-cataloger,apk-db-cataloger,dpkg-db-cataloger,rpm-db-cataloger") @@ -353,7 +353,7 @@ func callCnbBuild(config *cnbBuildOptions, telemetryData *telemetry.CustomData, err = syftScanner.ScanImages(filepath.Dir(config.DockerConfigJSON), utils, commonPipelineEnvironment.container.registryURL, commonPipelineEnvironment.container.imageNameTags) if err != nil { log.SetErrorCategory(log.ErrorCompliance) - return errors.Wrap(err, "failed to create BOM file") + return fmt.Errorf("failed to create BOM file: %w", err) } } @@ -366,29 +366,29 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image err := cleanDir("/layers", utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrap(err, "failed to clean up layers folder /layers") + return fmt.Errorf("failed to clean up layers folder /layers: %w", err) } err = cleanDir(platformPath, utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrap(err, fmt.Sprintf("failed to clean up platform folder %s", platformPath)) + return fmt.Errorf(fmt.Sprintf("failed to clean up platform folder %s", platformPath), err) } tempdir, err := utils.TempDir("", "cnbBuild-") if err != nil { - return errors.Wrap(err, "failed to create tempdir") + return fmt.Errorf("failed to create tempdir: %w", err) } defer utils.RemoveAll(tempdir) uid, gid, err := cnbutils.CnbUserInfo() if err != nil { - return errors.Wrap(err, "failed to get user information") + return fmt.Errorf("failed to get user information: %w", err) } err = utils.Chown(tempdir, uid, gid) if err != nil { - return errors.Wrap(err, "failed to change tempdir ownership") + return fmt.Errorf("failed to change tempdir ownership: %w", err) } if config.BuildEnvVars == nil { @@ -402,7 +402,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image projDescPath, err := project.ResolvePath(config.ProjectDescriptor, config.Path, utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to check if project descriptor exists") + return fmt.Errorf("failed to check if project descriptor exists: %w", err) } imageSummary.ProjectDescriptor = projDescPath @@ -411,7 +411,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image descriptor, err := project.ParseDescriptor(projDescPath, utils, httpClient) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to parse %s", projDescPath) + return fmt.Errorf("failed to parse %s: %w", projDescPath, err) } config.mergeEnvVars(descriptor.EnvVars) @@ -442,7 +442,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image targetImage, err := cnbutils.GetTargetImage(config.ContainerRegistryURL, config.ContainerImageName, config.ContainerImageTag, projectID, GeneralConfig.EnvRootPath) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to retrieve target image configuration") + return fmt.Errorf("failed to retrieve target image configuration: %w", err) } if commonPipelineEnvironment.container.imageNameTag == "" { @@ -466,40 +466,40 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image err = cnbutils.CreateEnvFiles(utils, platformPath, config.BuildEnvVars) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to write environment variables to files") + return fmt.Errorf("failed to write environment variables to files: %w", err) } } err = bindings.ProcessBindings(utils, httpClient, platformPath, config.Bindings) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed process bindings") + return fmt.Errorf("failed process bindings: %w", err) } pathType, source, err := config.resolvePath(utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrap(err, "could not resolve path") + return fmt.Errorf("could not resolve path: %w", err) } target := "/workspace" err = cleanDir(target, utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "failed to clean up target folder %s", target) + return fmt.Errorf("failed to clean up target folder %s: %w", target, err) } if pathType != buildpacks.PathEnumArchive { err = cnbutils.CopyProject(source, target, include, exclude, utils, false) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Copying '%s' into '%s' failed", source, target) + return fmt.Errorf("Copying '%s' into '%s' failed: %w", source, target, err) } } else { err = extractZip(source, target) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Copying '%s' into '%s' failed", source, target) + return fmt.Errorf("Copying '%s' into '%s' failed: %w", source, target, err) } } @@ -529,7 +529,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image defer func() { _ = utils.RemoveAll(orderPath) }() if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Setting custom buildpacks: %v", config.Buildpacks) + return fmt.Errorf("Setting custom buildpacks: %v: %w", config.Buildpacks, err) } } @@ -537,11 +537,11 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image caCertificates := "/tmp/ca-certificates.crt" _, err := utils.Copy("/etc/ssl/certs/ca-certificates.crt", caCertificates) if err != nil { - return errors.Wrap(err, "failed to copy certificates") + return fmt.Errorf("failed to copy certificates: %w", err) } err = certutils.CertificateUpdate(config.CustomTLSCertificateLinks, httpClient, utils, caCertificates) if err != nil { - return errors.Wrap(err, "failed to update certificates") + return fmt.Errorf("failed to update certificates: %w", err) } utils.AppendEnv([]string{fmt.Sprintf("SSL_CERT_FILE=%s", caCertificates)}) } else { @@ -551,12 +551,12 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image dockerKeychain, err := cnbutils.ParseDockerConfig(config.DockerConfigJSON, utils) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to parse dockerConfigJSON") + return fmt.Errorf("failed to parse dockerConfigJSON: %w", err) } cnbAuthString, err := dockerKeychain.ToCNBString() if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to generate CNB_REGISTRY_AUTH") + return fmt.Errorf("failed to generate CNB_REGISTRY_AUTH: %w", err) } utils.AppendEnv([]string{fmt.Sprintf("CNB_REGISTRY_AUTH=%s", cnbAuthString)}) utils.AppendEnv([]string{fmt.Sprintf("CNB_PLATFORM_API=%s", platformAPIVersion)}) @@ -602,13 +602,13 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image err = utils.RunExecutableWithAttrs(creatorPath, attr, creatorArgs...) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "execution of '%s' failed", creatorArgs) + return fmt.Errorf("execution of '%s' failed: %w", creatorArgs, err) } digest, err := cnbutils.DigestFromReport(utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrap(err, "failed to read image digest") + return fmt.Errorf("failed to read image digest: %w", err) } commonPipelineEnvironment.container.imageDigest = digest commonPipelineEnvironment.container.imageDigests = append(commonPipelineEnvironment.container.imageDigests, digest) @@ -619,7 +619,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image err = cnbutils.CopyProject(target, source, ignore.CompileIgnoreLines(config.PreserveFiles...), nil, utils, true) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "failed to preserve files using glob '%s'", config.PreserveFiles) + return fmt.Errorf("failed to preserve files using glob '%s': %w", config.PreserveFiles, err) } } else { log.Entry().Warnf("skipping preserving files because the source '%s' is an archive", source) diff --git a/cmd/codeqlExecuteScan.go b/cmd/codeqlExecuteScan.go index b23943f37..e6dc74ca2 100644 --- a/cmd/codeqlExecuteScan.go +++ b/cmd/codeqlExecuteScan.go @@ -9,8 +9,9 @@ import ( "path/filepath" "strings" + "errors" + "github.com/google/shlex" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/codeql" "github.com/SAP/jenkins-library/pkg/command" @@ -485,7 +486,7 @@ func uploadSarifResults(config *codeqlExecuteScanOptions, token string, repoInfo codeqlSarifUploader := codeql.NewCodeqlSarifUploaderInstance(sarifUrl, token) if err := codeql.WaitSarifUploaded(config.SarifCheckMaxRetries, config.SarifCheckRetryInterval, &codeqlSarifUploader); err != nil { - return errors.Wrapf(err, "failed to upload sarif %s", sarifPath) + return fmt.Errorf("failed to upload sarif %s: %w", sarifPath, err) } } return nil @@ -512,7 +513,7 @@ func uploadProjectToGitHub(config *codeqlExecuteScanOptions, repoInfo *codeql.Re } targetCommitId, err := repoUploader.UploadProjectToGithub() if err != nil { - return errors.Wrap(err, "failed uploading db sources from non-GitHub SCM to GitHub") + return fmt.Errorf("failed uploading db sources from non-GitHub SCM to GitHub: %w", err) } repoInfo.CommitId = targetCommitId log.Entry().Info("DB sources were successfully uploaded to target GitHub repo") diff --git a/cmd/containerExecuteStructureTests.go b/cmd/containerExecuteStructureTests.go index 59917b8a2..381bcfcb7 100644 --- a/cmd/containerExecuteStructureTests.go +++ b/cmd/containerExecuteStructureTests.go @@ -5,11 +5,12 @@ import ( "io" "os" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type containerExecuteStructureTestsUtils interface { @@ -57,7 +58,7 @@ func runContainerExecuteStructureTests(config *containerExecuteStructureTestsOpt parameters = append(parameters, "test") configFiles, err := findConfigFiles(config.TestConfiguration, utils) if err != nil { - return errors.Wrapf(err, "failed to find config files, error: %v", err) + return fmt.Errorf("failed to find config files, error: %v: %w", err, err) } if len(configFiles) == 0 { log.SetErrorCategory(log.ErrorConfiguration) @@ -86,7 +87,7 @@ func runContainerExecuteStructureTests(config *containerExecuteStructureTestsOpt err = utils.RunExecutable(containerStructureTestsExecutable, parameters...) if err != nil { commandLine := append([]string{containerStructureTestsExecutable}, parameters...) - return errors.Wrapf(err, "failed to run executable, command: '%s', error: %v", commandLine, err) + return fmt.Errorf("failed to run executable, command: '%s', error: %v: %w", commandLine, err, err) } return nil diff --git a/cmd/containerExecuteStructureTests_test.go b/cmd/containerExecuteStructureTests_test.go index d3b8787c3..83e98a5f4 100644 --- a/cmd/containerExecuteStructureTests_test.go +++ b/cmd/containerExecuteStructureTests_test.go @@ -8,8 +8,9 @@ import ( "os" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/containerSaveImage.go b/cmd/containerSaveImage.go index 54d183d42..9ccbcfbde 100644 --- a/cmd/containerSaveImage.go +++ b/cmd/containerSaveImage.go @@ -10,8 +10,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - - "github.com/pkg/errors" ) func containerSaveImage(config containerSaveImageOptions, telemetryData *telemetry.CustomData) { @@ -48,7 +46,7 @@ func runContainerSaveImage(config *containerSaveImageOptions, telemetryData *tel log.Entry().Infof("Downloading '%s' to '%s'", config.ContainerImage, tarfilePath) if _, err := dClient.DownloadImage(config.ContainerImage, tarfilePath); err != nil { - return "", errors.Wrap(err, "failed to download docker image") + return "", fmt.Errorf("failed to download docker image: %w", err) } return tarfilePath, nil @@ -64,7 +62,7 @@ func correctContainerDockerConfigEnvVar(config *containerSaveImageOptions, utils dockerConfigDir, err := utils.TempDir("", "docker") if err != nil { - return errors.Wrap(err, "unable to create docker config dir") + return fmt.Errorf("unable to create docker config dir: %w", err) } dockerConfigFile := fmt.Sprintf("%s/%s", dockerConfigDir, "config.json") @@ -74,7 +72,7 @@ func correctContainerDockerConfigEnvVar(config *containerSaveImageOptions, utils if exists, _ := utils.FileExists(config.DockerConfigJSON); exists { if _, err = utils.Copy(config.DockerConfigJSON, dockerConfigFile); err != nil { - return errors.Wrap(err, "unable to copy docker config") + return fmt.Errorf("unable to copy docker config: %w", err) } } } else { diff --git a/cmd/contrastExecuteScan.go b/cmd/contrastExecuteScan.go index c7c1b39e7..e8ce8dcff 100644 --- a/cmd/contrastExecuteScan.go +++ b/cmd/contrastExecuteScan.go @@ -6,12 +6,13 @@ import ( "fmt" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/contrast" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type contrastExecuteScanUtils interface { @@ -166,7 +167,7 @@ func generateSarifReport(config *contrastExecuteScanOptions, utils contrastExecu data, err := client.GenerateSarifReport(config.ApplicationID) if err != nil { - return nil, errors.Wrap(err, "SARIF generation failed") + return nil, fmt.Errorf("SARIF generation failed: %w", err) } return contrast.SaveReportFile(utils, "piper_contrast.sarif", "Contrast SARIF Report", data) @@ -178,7 +179,7 @@ func generatePdfReport(config *contrastExecuteScanOptions, utils contrastExecute data, err := client.GeneratePdfReport(config.ApplicationID) if err != nil { - return nil, errors.Wrap(err, "PDF generation failed") + return nil, fmt.Errorf("PDF generation failed: %w", err) } return contrast.SaveReportFile(utils, "piper_contrast_attestation.pdf", "Contrast PDF Attestation Report", data) diff --git a/cmd/credentialdiggerScan.go b/cmd/credentialdiggerScan.go index 1684ff80c..461373479 100644 --- a/cmd/credentialdiggerScan.go +++ b/cmd/credentialdiggerScan.go @@ -12,7 +12,6 @@ import ( "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) const piperDbName string = "piper_step_db.db" @@ -53,7 +52,7 @@ func credentialdiggerScan(config credentialdiggerScanOptions, telemetryData *tel repoUrlOrchestrator := provider.RepoURL() if repoUrlOrchestrator == "n/a" { // Jenkins configuration error - configError := errors.New(fmt.Sprintf("Unknown repository URL %s", repoUrlOrchestrator)) + configError := fmt.Errorf("Unknown repository URL %s", repoUrlOrchestrator) log.Entry().WithError(configError).Error( "Repository URL n/a. Please verify git plugin is installed.") // The repository to scan was not identified. Return an error diff --git a/cmd/detectExecuteScan.go b/cmd/detectExecuteScan.go index 0c298013e..f1d823490 100644 --- a/cmd/detectExecuteScan.go +++ b/cmd/detectExecuteScan.go @@ -29,8 +29,9 @@ import ( "github.com/SAP/jenkins-library/pkg/toolrecord" "github.com/SAP/jenkins-library/pkg/versioning" + "errors" + "github.com/google/go-github/v68/github" - "github.com/pkg/errors" ) const NO_VERSION_SUFFIX = "" @@ -278,7 +279,7 @@ func runDetect(ctx context.Context, config detectExecuteScanOptions, utils detec imageError := mapDetectError(runDetectImages(ctx, config, utils, blackduckSystem, influx, blackduckSystem), config, utils) if imageError != nil { if err != nil { - err = errors.Wrapf(err, "error during scanning images: %q", imageError.Error()) + err = fmt.Errorf("error during scanning images: %q: %w", imageError.Error(), err) } else { err = imageError } @@ -316,7 +317,7 @@ func mapDetectError(err error, config detectExecuteScanOptions, utils detectUtil log.Entry().Infof("policy violation(s) found - step will only create data but not fail due to setting failOnSevereVulnerabilities: false") } else { // Error code mapping with more human readable text - err = errors.Wrap(err, exitCodeMapping(utils.GetExitCode())) + err = fmt.Errorf(exitCodeMapping(utils.GetExitCode()), err) } } return err @@ -584,7 +585,7 @@ func addDetectArgs(args []string, config detectExecuteScanOptions, utils detectU err := utils.MkdirAll(".pipeline/blackduckDiagnostics", 0o755) if err != nil { - return nil, errors.Wrap(err, "failed to create diagnostics directory") + return nil, fmt.Errorf("failed to create diagnostics directory: %w", err) } log.Entry().Info("Diagnostics enabled, output will be stored in .pipeline/blackduckDiagnostics") @@ -809,7 +810,7 @@ func postScanChecksAndReporting(ctx context.Context, config detectExecuteScanOpt strings.Contains(err.Error(), "No Components found for project version") { log.Entry().Debug(err.Error()) } else { - return errors.Wrap(err, "failed to fetch vulnerabilities") + return fmt.Errorf("failed to fetch vulnerabilities: %w", err) } } @@ -981,7 +982,7 @@ func writePolicyStatusReports(scanReport reporting.ScanReport, config detectExec htmlReportPath := "piper_detect_policy_violation_report.html" if err := utils.FileWrite(htmlReportPath, htmlReport, 0o666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrap(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "BlackDuck Policy Violation Report", Target: htmlReportPath}) @@ -989,11 +990,11 @@ func writePolicyStatusReports(scanReport reporting.ScanReport, config detectExec if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0o777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create reporting directory") + return reportPaths, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("detectExecuteScan_policy_%v.json", fmt.Sprintf("%v", time.Now()))), jsonReport, 0o666); err != nil { - return reportPaths, errors.Wrap(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } return reportPaths, nil @@ -1002,7 +1003,7 @@ func writePolicyStatusReports(scanReport reporting.ScanReport, config detectExec func writeIpPolicyJson(config detectExecuteScanOptions, utils detectUtils, paths []piperutils.Path, sys *blackduckSystem) (error, int) { components, err := sys.Client.GetComponentsWithLicensePolicyRule(config.ProjectName, getVersionName(config)) if err != nil { - return errors.Wrap(err, "failed to get License Policy Violations"), 0 + return fmt.Errorf("failed to get License Policy Violations: %w", err), 0 } violationCount := getActivePolicyViolations(components) diff --git a/cmd/fortifyExecuteScan.go b/cmd/fortifyExecuteScan.go index 0cb030753..96f60fc67 100644 --- a/cmd/fortifyExecuteScan.go +++ b/cmd/fortifyExecuteScan.go @@ -38,7 +38,7 @@ import ( piperGithub "github.com/SAP/jenkins-library/pkg/github" - "github.com/pkg/errors" + "errors" ) const getClasspathScriptContent = ` @@ -281,7 +281,7 @@ func runFortifyScan(ctx context.Context, config fortifyExecuteScanOptions, sys f reports = append(reports, piperutils.Path{Target: fmt.Sprintf("%vtarget/fortify-scan.*", config.ModulePath)}) reports = append(reports, piperutils.Path{Target: fmt.Sprintf("%vtarget/*.fpr", config.ModulePath)}) if err != nil { - return reports, errors.Wrap(err, "failed to scan project") + return reports, fmt.Errorf("failed to scan project: %w", err) } var message string @@ -367,14 +367,14 @@ func verifyFFProjectCompliance(ctx context.Context, config fortifyExecuteScanOpt // Perform audit compliance checks issueFilterSelectorSet, err := sys.GetIssueFilterSelectorOfProjectVersionByName(projectVersion.ID, []string{"Analysis", "Folder", "Category"}, nil) if err != nil { - return reports, errors.Wrapf(err, "failed to fetch project version issue filter selector for project version ID %v", projectVersion.ID) + return reports, fmt.Errorf("failed to fetch project version issue filter selector for project version ID %v: %w", projectVersion.ID, err) } log.Entry().Debugf("initial filter selector set: %v", issueFilterSelectorSet) spotChecksCountByCategory := []fortify.SpotChecksAuditCount{} numberOfViolations, issueGroups, err := analyseUnauditedIssues(config, sys, projectVersion, filterSet, issueFilterSelectorSet, influx, auditStatus, &spotChecksCountByCategory) if err != nil { - return reports, errors.Wrap(err, "failed to analyze unaudited issues") + return reports, fmt.Errorf("failed to analyze unaudited issues: %w", err) } numberOfSuspiciousExploitable, issueGroupsSuspiciousExploitable := analyseSuspiciousExploitable(config, sys, projectVersion, filterSet, issueFilterSelectorSet, influx, auditStatus) numberOfViolations += numberOfSuspiciousExploitable @@ -392,7 +392,7 @@ func verifyFFProjectCompliance(ctx context.Context, config fortifyExecuteScanOpt scanReport := fortify.CreateCustomReport(fortifyReportingData, issueGroups) paths, err := fortify.WriteCustomReports(scanReport) if err != nil { - return reports, errors.Wrap(err, "failed to write custom reports") + return reports, fmt.Errorf("failed to write custom reports: %w", err) } reports = append(reports, paths...) @@ -415,7 +415,7 @@ func verifyFFProjectCompliance(ctx context.Context, config fortifyExecuteScanOpt jsonReport := fortify.CreateJSONReport(fortifyReportingData, spotChecksCountByCategory, config.ServerURL) paths, err = fortify.WriteJSONReport(jsonReport) if err != nil { - return reports, errors.Wrap(err, "failed to write json report") + return reports, fmt.Errorf("failed to write json report: %w", err) } reports = append(reports, paths...) @@ -457,13 +457,13 @@ func analyseUnauditedIssues(config fortifyExecuteScanOptions, sys fortify.System reducedFilterSelectorSet := sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Folder"}, nil) fetchedIssueGroups, err := sys.GetProjectIssuesByIDAndFilterSetGroupedBySelector(projectVersion.ID, "", filterSet.GUID, reducedFilterSelectorSet) if err != nil { - return 0, fetchedIssueGroups, errors.Wrapf(err, "failed to fetch project version issue groups with filter set %v and selector %v for project version ID %v", filterSet, issueFilterSelectorSet, projectVersion.ID) + return 0, fetchedIssueGroups, fmt.Errorf("failed to fetch project version issue groups with filter set %v and selector %v for project version ID %v: %w", filterSet, issueFilterSelectorSet, projectVersion.ID, err) } overallViolations := 0 for _, issueGroup := range fetchedIssueGroups { issueDelta, err := getIssueDeltaFor(config, sys, issueGroup, projectVersion.ID, filterSet, issueFilterSelectorSet, influx, auditStatus, spotChecksCountByCategory) if err != nil { - return overallViolations, fetchedIssueGroups, errors.Wrap(err, "failed to get issue delta") + return overallViolations, fetchedIssueGroups, fmt.Errorf("failed to get issue delta: %w", err) } overallViolations += issueDelta } @@ -510,7 +510,7 @@ func getIssueDeltaFor(config fortifyExecuteScanOptions, sys fortify.System, issu filter := fmt.Sprintf("%v:%v", folderSelector.EntityType, folderSelector.SelectorOptions[0].Value) fetchedIssueGroups, err := sys.GetProjectIssuesByIDAndFilterSetGroupedBySelector(projectVersionID, filter, filterSet.GUID, sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Category"}, nil)) if err != nil { - return totalMinusAuditedDelta, errors.Wrapf(err, "failed to fetch project version issue groups with filter %v, filter set %v and selector %v for project version ID %v", filter, filterSet, issueFilterSelectorSet, projectVersionID) + return totalMinusAuditedDelta, fmt.Errorf("failed to fetch project version issue groups with filter %v, filter set %v and selector %v for project version ID %v: %w", filter, filterSet, issueFilterSelectorSet, projectVersionID, err) } totalMinusAuditedDelta += getSpotIssueCount(config, sys, fetchedIssueGroups, projectVersionID, filterSet, reducedFilterSelectorSet, influx, auditStatus, spotChecksCountByCategory) } @@ -652,7 +652,7 @@ func generateAndDownloadQGateReport(config fortifyExecuteScanOptions, sys fortif log.Entry().Infof("Generating report with template ID %v", config.ReportTemplateID) report, err := sys.GenerateQGateReport(project.ID, projectVersion.ID, int64(config.ReportTemplateID), *project.Name, *projectVersion.Name, config.ReportType) if err != nil { - return []byte{}, errors.Wrap(err, "failed to generate Q-Gate report") + return []byte{}, fmt.Errorf("failed to generate Q-Gate report: %w", err) } log.Entry().Debugf("Triggered report generation of report ID %v", report.ID) status := report.Status @@ -770,13 +770,13 @@ func executeTemplatedCommand(utils fortifyUtils, cmdTemplate []string, context m for index, cmdTemplatePart := range cmdTemplate { result, err := piperutils.ExecuteTemplate(cmdTemplatePart, context) if err != nil { - return errors.Wrapf(err, "failed to transform template for command fragment: %v", cmdTemplatePart) + return fmt.Errorf("failed to transform template for command fragment: %v: %w", cmdTemplatePart, err) } cmdTemplate[index] = result } err := utils.RunExecutable(cmdTemplate[0], cmdTemplate[1:]...) if err != nil { - return errors.Wrapf(err, "failed to execute command %v", cmdTemplate) + return fmt.Errorf("failed to execute command %v: %w", cmdTemplate, err) } return nil } @@ -785,13 +785,13 @@ func autoresolvePipClasspath(executable string, parameters []string, file string // redirect stdout and create cp file from command output outfile, err := os.Create(file) if err != nil { - return "", errors.Wrap(err, "failed to create classpath file") + return "", fmt.Errorf("failed to create classpath file: %w", err) } defer outfile.Close() utils.Stdout(outfile) err = utils.RunExecutable(executable, parameters...) if err != nil { - return "", errors.Wrapf(err, "failed to run classpath autodetection command %v with parameters %v", executable, parameters) + return "", fmt.Errorf("failed to run classpath autodetection command %v with parameters %v: %w", executable, parameters, err) } utils.Stdout(log.Entry().Writer()) return readClasspathFile(file), nil @@ -955,7 +955,7 @@ func triggerFortifyScan(config fortifyExecuteScanOptions, utils fortifyUtils, bu script := fmt.Sprintf("import sys;p=sys.path;p.remove('');print('%v'.join(p))", separator) classpath, err = autoresolvePipClasspath(config.PythonVersion, []string{"-c", script}, classpathFileName, utils) if err != nil { - return errors.Wrap(err, "failed to autoresolve pip classpath") + return fmt.Errorf("failed to autoresolve pip classpath: %w", err) } } // install the dev dependencies @@ -1076,7 +1076,7 @@ func handleSingleTranslate(config *fortifyExecuteScanOptions, command fortifyUti log.Entry().Debugf("Running sourceanalyzer translate command with options %v", translateOptions) err := command.RunExecutable("sourceanalyzer", translateOptions...) if err != nil { - return errors.Wrapf(err, "failed to execute sourceanalyzer translate command with options %v", translateOptions) + return fmt.Errorf("failed to execute sourceanalyzer translate command with options %v: %w", translateOptions, err) } } else { log.Entry().Debug("Skipping translate with nil value") @@ -1109,7 +1109,7 @@ func scanProject(config *fortifyExecuteScanOptions, command fortifyUtils, buildI err := command.RunExecutable("sourceanalyzer", scanOptions...) if err != nil { - return errors.Wrapf(err, "failed to execute sourceanalyzer scan command with scanOptions %v", scanOptions) + return fmt.Errorf("failed to execute sourceanalyzer scan command with scanOptions %v: %w", scanOptions, err) } return nil } diff --git a/cmd/gaugeExecuteTests.go b/cmd/gaugeExecuteTests.go index 43a1a7a31..d945b92a3 100644 --- a/cmd/gaugeExecuteTests.go +++ b/cmd/gaugeExecuteTests.go @@ -7,11 +7,12 @@ import ( "path/filepath" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) var ErrorGaugeInstall error = errors.New("error installing gauge") @@ -82,7 +83,7 @@ func installGauge(gaugeInstallCommand string, utils gaugeExecuteTestsUtils) erro err := utils.RunExecutable(installGaugeTokens[0], installGaugeTokens[1:]...) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(ErrorGaugeInstall, err.Error()) + return fmt.Errorf("%s: %w", err.Error(), ErrorGaugeInstall) } return nil @@ -94,7 +95,7 @@ func installLanguageRunner(languageRunner string, utils gaugeExecuteTestsUtils) err := utils.RunExecutable(gaugePath, installParams...) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(ErrorGaugeRunnerInstall, err.Error()) + return fmt.Errorf("%s: %w", err.Error(), ErrorGaugeRunnerInstall) } return nil @@ -108,7 +109,7 @@ func runGauge(config *gaugeExecuteTestsOptions, utils gaugeExecuteTestsUtils) er gaugePath := filepath.FromSlash(filepath.Join(utils.Getenv("HOME"), "/.npm-global/bin/gauge")) err := utils.RunExecutable(gaugePath, runCommandTokens...) if err != nil { - return errors.Wrap(ErrorGaugeRun, err.Error()) + return fmt.Errorf("%s: %w", err.Error(), ErrorGaugeRun) } return nil } diff --git a/cmd/gcpPublishEvent.go b/cmd/gcpPublishEvent.go index 95a5493e9..4453f22a1 100644 --- a/cmd/gcpPublishEvent.go +++ b/cmd/gcpPublishEvent.go @@ -1,13 +1,14 @@ package cmd import ( + "fmt" + piperConfig "github.com/SAP/jenkins-library/pkg/config" "github.com/SAP/jenkins-library/pkg/events" "github.com/SAP/jenkins-library/pkg/gcp" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type gcpPublishEventUtils interface { @@ -49,7 +50,7 @@ func runGcpPublishEvent(utils gcpPublishEventUtils) error { config := utils.GetConfig() data, err := createNewEvent(config) if err != nil { - return errors.Wrap(err, "failed to create event data") + return fmt.Errorf("failed to create event data: %w", err) } err = utils.NewPubsubClient( @@ -60,7 +61,7 @@ func runGcpPublishEvent(utils gcpPublishEventUtils) error { GeneralConfig.HookConfig.OIDCConfig.RoleID, ).Publish(config.Topic, data) if err != nil { - return errors.Wrap(err, "failed to publish event") + return fmt.Errorf("failed to publish event: %w", err) } log.Entry().Infof("Event published successfully! With topic: %s", config.Topic) @@ -70,7 +71,7 @@ func runGcpPublishEvent(utils gcpPublishEventUtils) error { func createNewEvent(config *gcpPublishEventOptions) ([]byte, error) { event, err := events.NewEvent(config.EventType, config.EventSource, "").CreateWithJSONData(config.EventData) if err != nil { - return []byte{}, errors.Wrap(err, "failed to create new event") + return []byte{}, fmt.Errorf("failed to create new event: %w", err) } err = event.AddToCloudEventData(config.AdditionalEventData) @@ -80,7 +81,7 @@ func createNewEvent(config *gcpPublishEventOptions) ([]byte, error) { eventBytes, err := event.ToBytes() if err != nil { - return []byte{}, errors.Wrap(err, "casting event to bytes failed") + return []byte{}, fmt.Errorf("casting event to bytes failed: %w", err) } log.Entry().Debugf("CloudEvent created: %s", string(eventBytes)) return eventBytes, nil diff --git a/cmd/gcpPublishEvent_test.go b/cmd/gcpPublishEvent_test.go index cf3b43530..52bcfe7c9 100644 --- a/cmd/gcpPublishEvent_test.go +++ b/cmd/gcpPublishEvent_test.go @@ -1,10 +1,12 @@ package cmd import ( - "github.com/SAP/jenkins-library/pkg/gcp" "testing" - "github.com/pkg/errors" + "github.com/SAP/jenkins-library/pkg/gcp" + + "errors" + "github.com/stretchr/testify/assert" ) diff --git a/cmd/gctsCloneRepository.go b/cmd/gctsCloneRepository.go index 8c47b3416..6c21ead5e 100644 --- a/cmd/gctsCloneRepository.go +++ b/cmd/gctsCloneRepository.go @@ -1,6 +1,7 @@ package cmd import ( + "fmt" "io" "net/http" "net/http/cookiejar" @@ -9,7 +10,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func gctsCloneRepository(config gctsCloneRepositoryOptions, telemetryData *telemetry.CustomData) { @@ -30,7 +30,7 @@ func cloneRepository(config *gctsCloneRepositoryOptions, telemetryData *telemetr cookieJar, cookieErr := cookiejar.New(nil) if cookieErr != nil { - return errors.Wrap(cookieErr, "creating a cookie jar failed") + return fmt.Errorf("creating a cookie jar failed: %w", cookieErr) } clientOptions := piperhttp.ClientOptions{ CookieJar: cookieJar, @@ -62,19 +62,19 @@ func cloneRepository(config *gctsCloneRepositoryOptions, telemetryData *telemetr }() if resp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrap(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } response, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } if httpErr != nil { @@ -87,11 +87,11 @@ func cloneRepository(config *gctsCloneRepositoryOptions, telemetryData *telemetr } else if exception, ok := response.Path("errorLog.1.code").Data().(string); ok && exception == "GCTS.CLIENT.3302" { log.Entry().Errorf("%v", response.Path("errorLog.1.message").Data().(string)) log.Entry().Error("possible reason: the remote repository is set to 'private'. you need to provide the local ABAP server repository with authentication credentials to the remote Git repository in order to clone it.") - return errors.Wrap(httpErr, "cloning the repository failed") + return fmt.Errorf("cloning the repository failed: %w", httpErr) } } log.Entry().Errorf("a HTTP error occurred! Response body: %v", response) - return errors.Wrap(httpErr, "cloning the repository failed") + return fmt.Errorf("cloning the repository failed: %w", httpErr) } log.Entry(). diff --git a/cmd/gctsCreateRepository.go b/cmd/gctsCreateRepository.go index e2cc81cb1..cf0175ef4 100644 --- a/cmd/gctsCreateRepository.go +++ b/cmd/gctsCreateRepository.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "encoding/json" + "fmt" "io" "net/http" "net/http/cookiejar" @@ -12,7 +13,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func gctsCreateRepository(config gctsCreateRepositoryOptions, telemetryData *telemetry.CustomData) { @@ -38,7 +38,7 @@ func createRepository(config *gctsCreateRepositoryOptions, telemetryData *teleme cookieJar, cookieErr := cookiejar.New(nil) if cookieErr != nil { - return errors.Wrapf(cookieErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, cookieErr) } clientOptions := piperhttp.ClientOptions{ CookieJar: cookieJar, @@ -75,7 +75,7 @@ func createRepository(config *gctsCreateRepositoryOptions, telemetryData *teleme jsonBody, marshalErr := json.Marshal(reqBody) if marshalErr != nil { - return errors.Wrapf(marshalErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, marshalErr) } header := make(http.Header) @@ -100,19 +100,19 @@ func createRepository(config *gctsCreateRepositoryOptions, telemetryData *teleme }() if resp == nil { - return errors.Errorf("creating repository on the ABAP system %v failed: %v", config.Host, httpErr) + return fmt.Errorf("creating repository on the ABAP system %v failed: %v", config.Host, httpErr) } bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrapf(readErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, readErr) } response, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, parsingErr) } if httpErr != nil { @@ -125,7 +125,7 @@ func createRepository(config *gctsCreateRepositoryOptions, telemetryData *teleme } } log.Entry().Errorf("a HTTP error occurred! Response body: %v", response) - return errors.Wrapf(httpErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, httpErr) } log.Entry(). diff --git a/cmd/gctsDeploy.go b/cmd/gctsDeploy.go index a884dc905..256544a3d 100644 --- a/cmd/gctsDeploy.go +++ b/cmd/gctsDeploy.go @@ -10,13 +10,14 @@ import ( "net/url" "strings" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/gcts" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) const repoStateExists = "RepoExists" @@ -360,7 +361,7 @@ func deployCommitToAbapSystem(config *gctsDeployOptions, httpClient piperhttp.Se reqBody := deployRequestBody jsonBody, marshalErr := json.Marshal(reqBody) if marshalErr != nil { - return errors.Wrapf(marshalErr, "Deploying repository to abap system failed json body marshalling") + return fmt.Errorf("Deploying repository to abap system failed json body marshalling: %w", marshalErr) } header := make(http.Header) header.Set("Content-Type", "application/json") @@ -477,7 +478,7 @@ func setConfigKey(deployConfig *gctsDeployOptions, httpClient piperhttp.Sender, reqBody := configToSet jsonBody, marshalErr := json.Marshal(reqBody) if marshalErr != nil { - return errors.Wrapf(marshalErr, "Setting config key: %v and value: %v on the ABAP system %v failed", configToSet.Key, configToSet.Value, deployConfig.Host) + return fmt.Errorf("Setting config key: %v and value: %v on the ABAP system %v failed: %w", configToSet.Key, configToSet.Value, deployConfig.Host, marshalErr) } header := make(http.Header) header.Set("Content-Type", "application/json") @@ -548,13 +549,13 @@ func pullByCommit(config *gctsDeployOptions, telemetryData *telemetry.CustomData bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } response, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } log.Entry(). @@ -567,7 +568,7 @@ func createRepositoryForDeploy(config *gctsCreateRepositoryOptions, telemetryDat cookieJar, cookieErr := cookiejar.New(nil) if cookieErr != nil { - return errors.Wrapf(cookieErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, cookieErr) } clientOptions := piperhttp.ClientOptions{ CookieJar: cookieJar, @@ -608,7 +609,7 @@ func createRepositoryForDeploy(config *gctsCreateRepositoryOptions, telemetryDat jsonBody, marshalErr := json.Marshal(reqBody) if marshalErr != nil { - return errors.Wrapf(marshalErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, marshalErr) } header := make(http.Header) @@ -633,7 +634,7 @@ func createRepositoryForDeploy(config *gctsCreateRepositoryOptions, telemetryDat }() if resp == nil { - return errors.Errorf("creating repository on the ABAP system %v failed: %v", config.Host, httpErr) + return fmt.Errorf("creating repository on the ABAP system %v failed: %v", config.Host, httpErr) } if httpErr != nil { @@ -650,7 +651,7 @@ func createRepositoryForDeploy(config *gctsCreateRepositoryOptions, telemetryDat } } log.Entry().Errorf("a HTTP error occurred! Response body: %v", response) - return errors.Wrapf(httpErr, "creating repository on the ABAP system %v failed", config.Host) + return fmt.Errorf("creating repository on the ABAP system %v failed: %w", config.Host, httpErr) } log.Entry(). diff --git a/cmd/gctsExecuteABAPQualityChecks.go b/cmd/gctsExecuteABAPQualityChecks.go index f4dde95e9..8a2b041ae 100644 --- a/cmd/gctsExecuteABAPQualityChecks.go +++ b/cmd/gctsExecuteABAPQualityChecks.go @@ -12,12 +12,13 @@ import ( "strconv" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/gcts" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) var atcFailure, aUnitFailure bool @@ -155,18 +156,18 @@ func getLocalObjects(config *gctsExecuteABAPQualityChecksOptions, client piperht if config.Commit == "" { - return []repoObject{}, errors.Errorf("For scope: localChangedObjects you need to specify a commit") + return []repoObject{}, fmt.Errorf("For scope: localChangedObjects you need to specify a commit") } history, err := getHistory(config, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get local changed objects failed") + return []repoObject{}, fmt.Errorf("get local changed objects failed: %w", err) } if len(history.Result) == 0 { - return []repoObject{}, errors.Wrap(err, "no activities (from commit - to commit) were found") + return []repoObject{}, fmt.Errorf("no activities (from commit - to commit) were found: %w", err) } fromCommit := history.Result[0].FromCommit @@ -177,7 +178,7 @@ func getLocalObjects(config *gctsExecuteABAPQualityChecksOptions, client piperht // object delta between FromCommit and ToCommit retrieved from Activities Tab in gCTS resp, err := getObjectDifference(config, fromCommit, toCommit, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get local changed objects failed") + return []repoObject{}, fmt.Errorf("get local changed objects failed: %w", err) } for _, object := range resp.Objects { @@ -201,14 +202,14 @@ func getRemoteObjects(config *gctsExecuteABAPQualityChecksOptions, client piperh if config.Commit == "" { - return []repoObject{}, errors.Errorf("For scope: remoteChangedObjects you need to specify a commit") + return []repoObject{}, fmt.Errorf("For scope: remoteChangedObjects you need to specify a commit") } commitList, err := getCommitList(config, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get remote changed objects failed") + return []repoObject{}, fmt.Errorf("get remote changed objects failed: %w", err) } for i, commit := range commitList.Commits { @@ -226,7 +227,7 @@ func getRemoteObjects(config *gctsExecuteABAPQualityChecksOptions, client piperh resp, err := getObjectDifference(config, currentRemoteCommit, config.Commit, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get remote changed objects failed") + return []repoObject{}, fmt.Errorf("get remote changed objects failed: %w", err) } for _, object := range resp.Objects { @@ -249,18 +250,18 @@ func getLocalPackages(config *gctsExecuteABAPQualityChecksOptions, client piperh if config.Commit == "" { - return []repoObject{}, errors.Errorf("For scope: localChangedPackages you need to specify a commit") + return []repoObject{}, fmt.Errorf("For scope: localChangedPackages you need to specify a commit") } history, err := getHistory(config, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get local changed objects failed") + return []repoObject{}, fmt.Errorf("get local changed objects failed: %w", err) } if len(history.Result) == 0 { - return []repoObject{}, errors.Wrap(err, "no activities (from commit - to commit) were found") + return []repoObject{}, fmt.Errorf("no activities (from commit - to commit) were found: %w", err) } fromCommit := history.Result[0].FromCommit @@ -272,7 +273,7 @@ func getLocalPackages(config *gctsExecuteABAPQualityChecksOptions, client piperh resp, err := getObjectDifference(config, fromCommit, config.Commit, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get local changed packages failed") + return []repoObject{}, fmt.Errorf("get local changed packages failed: %w", err) } @@ -282,7 +283,7 @@ func getLocalPackages(config *gctsExecuteABAPQualityChecksOptions, client piperh for _, object := range resp.Objects { objInfo, err := getObjectInfo(config, client, object.Name, object.Type) if err != nil { - return []repoObject{}, errors.Wrap(err, "get local changed packages failed") + return []repoObject{}, fmt.Errorf("get local changed packages failed: %w", err) } if myPackages[objInfo.Devclass] { @@ -309,14 +310,14 @@ func getRemotePackages(config *gctsExecuteABAPQualityChecksOptions, client piper if config.Commit == "" { - return []repoObject{}, errors.Errorf("For scope: remoteChangedPackages you need to specify a commit") + return []repoObject{}, fmt.Errorf("For scope: remoteChangedPackages you need to specify a commit") } commitList, err := getCommitList(config, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get remote changed packages failed") + return []repoObject{}, fmt.Errorf("get remote changed packages failed: %w", err) } for i, commit := range commitList.Commits { @@ -327,14 +328,14 @@ func getRemotePackages(config *gctsExecuteABAPQualityChecksOptions, client piper } if currentRemoteCommit == "" { - return []repoObject{}, errors.Wrap(err, "current remote commit was not found") + return []repoObject{}, fmt.Errorf("current remote commit was not found: %w", err) } log.Entry().Info("current commit in the remote repository: ", currentRemoteCommit) //object delta between the commit that triggered the pipeline and the current commit in the remote repository resp, err := getObjectDifference(config, currentRemoteCommit, config.Commit, client) if err != nil { - return []repoObject{}, errors.Wrap(err, "get remote changed packages failed") + return []repoObject{}, fmt.Errorf("get remote changed packages failed: %w", err) } myPackages := map[string]bool{} @@ -342,7 +343,7 @@ func getRemotePackages(config *gctsExecuteABAPQualityChecksOptions, client piper for _, object := range resp.Objects { objInfo, err := getObjectInfo(config, client, object.Name, object.Type) if err != nil { - return []repoObject{}, errors.Wrap(err, "get remote changed packages failed") + return []repoObject{}, fmt.Errorf("get remote changed packages failed: %w", err) } if myPackages[objInfo.Devclass] { @@ -384,14 +385,14 @@ func getRepositoryObjects(config *gctsExecuteABAPQualityChecksOptions, client pi }() if httpErr != nil { - return []repoObject{}, errors.Wrap(httpErr, "could not get repository objects") + return []repoObject{}, fmt.Errorf("could not get repository objects: %w", httpErr) } else if resp == nil { return []repoObject{}, errors.New("could not get repository objects: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &repoResp) if parsingErr != nil { - return []repoObject{}, errors.Errorf("%v", parsingErr) + return []repoObject{}, fmt.Errorf("%v", parsingErr) } var repositoryObjects []repoObject @@ -440,14 +441,14 @@ func getPackages(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S }() if httpErr != nil { - return []repoObject{}, errors.Wrap(httpErr, "get packages failed: could not get repository objects") + return []repoObject{}, fmt.Errorf("get packages failed: could not get repository objects: %w", httpErr) } else if resp == nil { return []repoObject{}, errors.New("get packages failed: could not get repository objects: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &repoResp) if parsingErr != nil { - return []repoObject{}, errors.Errorf("%v", parsingErr) + return []repoObject{}, fmt.Errorf("%v", parsingErr) } // chose only DEVC from repository objects for _, object := range repoResp.Objects { @@ -488,7 +489,7 @@ func discoverServer(config *gctsExecuteABAPQualityChecksOptions, client piperhtt }() if httpErr != nil { - return nil, errors.Wrap(httpErr, "discovery of the ABAP server failed") + return nil, fmt.Errorf("discovery of the ABAP server failed: %w", httpErr) } else if disc == nil || disc.Header == nil { return nil, errors.New("discovery of the ABAP server failed: did not retrieve a HTTP response") } @@ -538,7 +539,7 @@ func executeAUnitTest(config *gctsExecuteABAPQualityChecksOptions, client piperh resp, err := runAUnitTest(config, client, xmlBody) if err != nil { - return errors.Wrap(err, "execute of Aunit test has failed") + return fmt.Errorf("execute of Aunit test has failed: %w", err) } parsingErr := piperhttp.ParseHTTPResponseBodyXML(resp, &result) @@ -575,12 +576,12 @@ func runAUnitTest(config *gctsExecuteABAPQualityChecksOptions, client piperhttp. discHeader, discError := discoverServer(config, client) if discError != nil { - return response, errors.Wrap(discError, "run of unit tests failed") + return response, fmt.Errorf("run of unit tests failed: %w", discError) } if discHeader.Get("X-Csrf-Token") == "" { - return response, errors.Errorf("could not retrieve x-csrf-token from server") + return response, fmt.Errorf("could not retrieve x-csrf-token from server") } header := make(http.Header) @@ -591,7 +592,7 @@ func runAUnitTest(config *gctsExecuteABAPQualityChecksOptions, client piperhttp. response, httpErr := client.SendRequest("POST", url, bytes.NewBuffer(xml), header, nil) if httpErr != nil { - return response, errors.Wrap(httpErr, "run of unit tests failed") + return response, fmt.Errorf("run of unit tests failed: %w", httpErr) } else if response == nil { return response, errors.New("run of unit tests failed: did not retrieve a HTTP response") } @@ -627,13 +628,13 @@ func parseUnitResult(config *gctsExecuteABAPQualityChecksOptions, client piperht aUnitError.Line, err = findLine(config, client, program.Alerts.Alert.Stack.StackEntry.URI, objectName, objectType) log.Entry().Error("line: ", aUnitError.Line) if err != nil { - return parsedResult, errors.Wrap(err, "parse AUnit Result failed") + return parsedResult, fmt.Errorf("parse AUnit Result failed: %w", err) } fileName, err = getFileName(config, client, program.Alerts.Alert.Stack.StackEntry.URI, objectName) log.Entry().Error("file path: ", aUnitError.Line) if err != nil { - return parsedResult, errors.Wrap(err, "parse AUnit Result failed") + return parsedResult, fmt.Errorf("parse AUnit Result failed: %w", err) } @@ -704,7 +705,7 @@ func parseUnitResult(config *gctsExecuteABAPQualityChecksOptions, client piperht fileName, err = getFileName(config, client, testClass.URI, objectName) if err != nil { - return parsedResult, errors.Wrap(err, "parse AUnit Result failed") + return parsedResult, fmt.Errorf("parse AUnit Result failed: %w", err) } } @@ -713,7 +714,7 @@ func parseUnitResult(config *gctsExecuteABAPQualityChecksOptions, client piperht log.Entry().Error("file path: ", aUnitFile.Name) if err != nil { - return parsedResult, errors.Wrap(err, "parse AUnit Result failed") + return parsedResult, fmt.Errorf("parse AUnit Result failed: %w", err) } parsedResult.File = append(parsedResult.File, aUnitFile) aUnitFile = file{} @@ -783,19 +784,19 @@ func executeATCCheck(config *gctsExecuteABAPQualityChecksOptions, client piperht worklist, err := getWorklist(config, client) if err != nil { - return errors.Wrap(err, "execution of ATC Checks failed") + return fmt.Errorf("execution of ATC Checks failed: %w", err) } err = startATCRun(config, client, xmlBody, worklist) if err != nil { - return errors.Wrap(err, "execution of ATC Checks failed") + return fmt.Errorf("execution of ATC Checks failed: %w", err) } resp, err := getATCRun(config, client, worklist) if err != nil { - return errors.Wrap(err, "execution of ATC Checks failed") + return fmt.Errorf("execution of ATC Checks failed: %w", err) } parsingErr := piperhttp.ParseHTTPResponseBodyXML(resp, &result) @@ -808,7 +809,7 @@ func executeATCCheck(config *gctsExecuteABAPQualityChecksOptions, client piperht if err != nil { log.Entry().Error(err) - return errors.Wrap(err, "execution of ATC Checks failed") + return fmt.Errorf("execution of ATC Checks failed: %w", err) } log.Entry().Info("execute ATC Checks finished.", atcRes.Text) @@ -822,11 +823,11 @@ func startATCRun(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S discHeader, discError := discoverServer(config, client) if discError != nil { - return errors.Wrap(discError, "start of ATC run failed") + return fmt.Errorf("start of ATC run failed: %w", discError) } if discHeader.Get("X-Csrf-Token") == "" { - return errors.Errorf("could not retrieve x-csrf-token from server") + return fmt.Errorf("could not retrieve x-csrf-token from server") } header := make(http.Header) @@ -852,7 +853,7 @@ func startATCRun(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S }() if httpErr != nil { - return errors.Wrap(httpErr, "start of ATC run failed") + return fmt.Errorf("start of ATC run failed: %w", httpErr) } else if resp == nil { return errors.New("start of ATC run failed: did not retrieve a HTTP response") } @@ -884,7 +885,7 @@ func getATCRun(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Sen resp, httpErr := client.SendRequest("GET", url, nil, header, nil) if httpErr != nil { - return response, errors.Wrap(httpErr, "get ATC run failed") + return response, fmt.Errorf("get ATC run failed: %w", httpErr) } else if resp == nil { return response, errors.New("get ATC run failed: did not retrieve a HTTP response") } @@ -907,11 +908,11 @@ func getWorklist(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S } if discError != nil { - return worklistID, errors.Wrap(discError, "get worklist failed") + return worklistID, fmt.Errorf("get worklist failed: %w", discError) } if discHeader.Get("X-Csrf-Token") == "" { - return worklistID, errors.Errorf("could not retrieve x-csrf-token from server") + return worklistID, fmt.Errorf("could not retrieve x-csrf-token from server") } header := make(http.Header) @@ -926,7 +927,7 @@ func getWorklist(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S }() if httpErr != nil { - return worklistID, errors.Wrap(httpErr, "get worklist failed") + return worklistID, fmt.Errorf("get worklist failed: %w", httpErr) } else if resp == nil { return worklistID, errors.New("get worklist failed: did not retrieve a HTTP response") } @@ -960,7 +961,7 @@ func parseATCCheckResult(config *gctsExecuteABAPQualityChecksOptions, client pip path, err := url.PathUnescape(atcworklist.Location) if err != nil { - return atcResults, errors.Wrap(err, "conversion of ATC check results to CheckStyle has failed") + return atcResults, fmt.Errorf("conversion of ATC check results to CheckStyle has failed: %w", err) } @@ -969,7 +970,7 @@ func parseATCCheckResult(config *gctsExecuteABAPQualityChecksOptions, client pip priority, err := strconv.Atoi(atcworklist.Priority) if err != nil { - return atcResults, errors.Wrap(err, "conversion of ATC check results to CheckStyle has failed") + return atcResults, fmt.Errorf("conversion of ATC check results to CheckStyle has failed: %w", err) } @@ -1022,13 +1023,13 @@ func parseATCCheckResult(config *gctsExecuteABAPQualityChecksOptions, client pip fileName, err := getFileName(config, client, path, objectName) if err != nil { - return atcResults, errors.Wrap(err, "conversion of ATC check results to CheckStyle has failed") + return atcResults, fmt.Errorf("conversion of ATC check results to CheckStyle has failed: %w", err) } atcFile.Name, err = constructPath(config, client, fileName, objectName, objectType) log.Entry().Info("file path: ", atcFile.Name) if err != nil { - return atcResults, errors.Wrap(err, "conversion of ATC check results to CheckStyle has failed") + return atcResults, fmt.Errorf("conversion of ATC check results to CheckStyle has failed: %w", err) } atcResults.File = append(atcResults.File, atcFile) atcFile = file{} @@ -1054,7 +1055,7 @@ func constructPath(config *gctsExecuteABAPQualityChecksOptions, client piperhttp targetDir, err := getTargetDir(config, client) if err != nil { - return filePath, errors.Wrap(err, "path could not be constructed") + return filePath, fmt.Errorf("path could not be constructed: %w", err) } @@ -1072,7 +1073,7 @@ func findLine(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Send if err != nil { - return line, errors.Wrap(err, "could not find line in source code") + return line, fmt.Errorf("could not find line in source code: %w", err) } @@ -1086,7 +1087,7 @@ func findLine(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Send filePath, err := constructPath(config, client, fileName, objectName, objectType) if err != nil { - return line, errors.Wrap(err, objectType+"/"+objectName+"could not find line in source code") + return line, fmt.Errorf(objectType+"/"+objectName+"could not find line in source code", err) } @@ -1098,7 +1099,7 @@ func findLine(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Send if err != nil { - return line, errors.Wrapf(err, "could not find object in the workspace of your CI/CD tool ") + return line, fmt.Errorf("could not find object in the workspace of your CI/CD tool : %w", err) } file := string(rawfile) @@ -1178,7 +1179,7 @@ func getFileName(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S readableSource, err := checkReadableSource(config, client) if err != nil { - return fileName, errors.Wrap(err, "get file name has failed") + return fileName, fmt.Errorf("get file name has failed: %w", err) } @@ -1191,7 +1192,7 @@ func getFileName(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.S } if err != nil { - return fileName, errors.Wrap(err, "get file name has failed") + return fileName, fmt.Errorf("get file name has failed: %w", err) } @@ -1435,7 +1436,7 @@ func checkReadableSource(config *gctsExecuteABAPQualityChecksOptions, client pip repoLayout, err := getRepositoryLayout(config, client) if err != nil { - return readableSource, errors.Wrap(err, "could not check readable source format") + return readableSource, fmt.Errorf("could not check readable source format: %w", err) } if repoLayout.Layout.ReadableSource == "true" || repoLayout.Layout.ReadableSource == "only" || repoLayout.Layout.ReadableSource == "all" { @@ -1473,14 +1474,14 @@ func getRepo(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Sende }() if httpErr != nil { - return repositoryResponse{}, errors.Wrap(httpErr, "could not get repository") + return repositoryResponse{}, fmt.Errorf("could not get repository: %w", httpErr) } else if resp == nil { return repositoryResponse{}, errors.New("could not get repository: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &repositoryResp) if parsingErr != nil { - return repositoryResponse{}, errors.Errorf("%v", parsingErr) + return repositoryResponse{}, fmt.Errorf("%v", parsingErr) } return repositoryResp, nil @@ -1510,14 +1511,14 @@ func getRepositoryLayout(config *gctsExecuteABAPQualityChecksOptions, client pip }() if httpErr != nil { - return layoutResponse{}, errors.Wrap(httpErr, "could not get repository layout") + return layoutResponse{}, fmt.Errorf("could not get repository layout: %w", httpErr) } else if resp == nil { return layoutResponse{}, errors.New("could not get repository layout: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &repoLayoutResponse) if parsingErr != nil { - return layoutResponse{}, errors.Errorf("%v", parsingErr) + return layoutResponse{}, fmt.Errorf("%v", parsingErr) } return repoLayoutResponse, nil @@ -1545,14 +1546,14 @@ func getCommitList(config *gctsExecuteABAPQualityChecksOptions, client piperhttp }() if httpErr != nil { - return commitResponse{}, errors.Wrap(httpErr, "get repository history failed") + return commitResponse{}, fmt.Errorf("get repository history failed: %w", httpErr) } else if resp == nil { return commitResponse{}, errors.New("get repository history failed: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &commitResp) if parsingErr != nil { - return commitResponse{}, errors.Errorf("%v", parsingErr) + return commitResponse{}, fmt.Errorf("%v", parsingErr) } return commitResp, nil @@ -1581,14 +1582,14 @@ func getObjectDifference(config *gctsExecuteABAPQualityChecksOptions, fromCommit }() if httpErr != nil { - return objectsResponse{}, errors.Wrap(httpErr, "get object difference failed") + return objectsResponse{}, fmt.Errorf("get object difference failed: %w", httpErr) } else if resp == nil { return objectsResponse{}, errors.New("get object difference failed: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &objectResponse) if parsingErr != nil { - return objectsResponse{}, errors.Errorf("%v", parsingErr) + return objectsResponse{}, fmt.Errorf("%v", parsingErr) } log.Entry().Info("get object differences: ", objectResponse.Objects) return objectResponse, nil @@ -1617,14 +1618,14 @@ func getObjectInfo(config *gctsExecuteABAPQualityChecksOptions, client piperhttp }() if httpErr != nil { - return objectInfo{}, errors.Wrap(httpErr, "resolve package failed") + return objectInfo{}, fmt.Errorf("resolve package failed: %w", httpErr) } else if resp == nil { return objectInfo{}, errors.New("resolve package failed: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &objectMetInfoResponse) if parsingErr != nil { - return objectInfo{}, errors.Errorf("%v", parsingErr) + return objectInfo{}, fmt.Errorf("%v", parsingErr) } return objectMetInfoResponse, nil @@ -1651,14 +1652,14 @@ func getHistory(config *gctsExecuteABAPQualityChecksOptions, client piperhttp.Se } }() if httpErr != nil { - return historyResponse{}, errors.Wrap(httpErr, "get history failed") + return historyResponse{}, fmt.Errorf("get history failed: %w", httpErr) } else if resp == nil { return historyResponse{}, errors.New("get history failed: did not retrieve a HTTP response") } parsingErr := piperhttp.ParseHTTPResponseBodyJSON(resp, &historyResp) if parsingErr != nil { - return historyResponse{}, errors.Errorf("%v", parsingErr) + return historyResponse{}, fmt.Errorf("%v", parsingErr) } return historyResp, nil diff --git a/cmd/gctsExecuteABAPQualityChecks_test.go b/cmd/gctsExecuteABAPQualityChecks_test.go index ea4de7f85..4ef898f81 100644 --- a/cmd/gctsExecuteABAPQualityChecks_test.go +++ b/cmd/gctsExecuteABAPQualityChecks_test.go @@ -10,8 +10,9 @@ import ( "net/http" "testing" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/gctsRollback.go b/cmd/gctsRollback.go index 35acd2d26..aae62608a 100644 --- a/cmd/gctsRollback.go +++ b/cmd/gctsRollback.go @@ -1,17 +1,19 @@ package cmd import ( + "fmt" "io" "net/http/cookiejar" "net/url" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/gcts" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func gctsRollback(config gctsRollbackOptions, telemetryData *telemetry.CustomData) { @@ -43,15 +45,15 @@ func rollback(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, repoInfo, err := getRepoInfo(config, telemetryData, httpClient) if err != nil { - return errors.Wrap(err, "could not get local repository data") + return fmt.Errorf("could not get local repository data: %w", err) } if repoInfo.Result.URL == "" { - return errors.Errorf("no remote repository URL configured") + return fmt.Errorf("no remote repository URL configured") } if err != nil { - return errors.Wrap(err, "could not parse remote repository URL as valid URL") + return fmt.Errorf("could not parse remote repository URL as valid URL: %w", err) } var deployOptions gctsDeployOptions @@ -72,7 +74,7 @@ func rollback(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, } else { repoHistory, err := getRepoHistory(config, telemetryData, httpClient) if err != nil { - return errors.Wrap(err, "could not retrieve repository commit history") + return fmt.Errorf("could not retrieve repository commit history: %w", err) } if repoHistory.Result[0].FromCommit != "" { @@ -88,14 +90,14 @@ func rollback(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, } } else { - return errors.Errorf("no commit to rollback to (fromCommit) could be identified from the repository commit history") + return fmt.Errorf("no commit to rollback to (fromCommit) could be identified from the repository commit history") } } deployErr := pullByCommit(&deployOptions, telemetryData, command, httpClient) if deployErr != nil { - return errors.Wrap(deployErr, "rollback commit failed") + return fmt.Errorf("rollback commit failed: %w", deployErr) } log.Entry(). @@ -123,7 +125,7 @@ func getLastSuccessfullCommit(config *gctsRollbackOptions, telemetryData *teleme if config.Proxy != "" { proxyURL, err := url.Parse(config.Proxy) if err != nil { - return "", errors.Wrap(err, "failed to parse proxy URL") + return "", fmt.Errorf("failed to parse proxy URL: %w", err) } clientOptions.TransportProxy = proxyURL log.Entry().Infof("Using proxy: %v", config.Proxy) @@ -159,13 +161,13 @@ func getLastSuccessfullCommit(config *gctsRollbackOptions, telemetryData *teleme bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read") + return "", fmt.Errorf("HTTP response body could not be read: %w", readErr) } response, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return "", errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return "", fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } if status, ok := response.Path("state").Data().(string); ok && status == "success" { @@ -176,7 +178,7 @@ func getLastSuccessfullCommit(config *gctsRollbackOptions, telemetryData *teleme } } - return "", errors.Errorf("no commit with status 'success' could be found") + return "", fmt.Errorf("no commit with status 'success' could be found") } func getCommits(config *gctsRollbackOptions, telemetryData *telemetry.CustomData, httpClient piperhttp.Sender) ([]string, error) { diff --git a/cmd/getConfig.go b/cmd/getConfig.go index b77ca6b4e..bbc82df58 100644 --- a/cmd/getConfig.go +++ b/cmd/getConfig.go @@ -8,12 +8,13 @@ import ( "path/filepath" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/config" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" ws "github.com/SAP/jenkins-library/pkg/whitesource" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -133,7 +134,7 @@ func GetStageConfig() (config.StepConfig, error) { customConfig, err := configOptions.OpenFile(projectConfigFile, GeneralConfig.GitHubAccessTokens) if err != nil { if !errors.Is(err, os.ErrNotExist) { - return stepConfig, errors.Wrapf(err, "config: open configuration file '%v' failed", projectConfigFile) + return stepConfig, fmt.Errorf("config: open configuration file '%v' failed: %w", projectConfigFile, err) } customConfig = nil } @@ -146,7 +147,7 @@ func GetStageConfig() (config.StepConfig, error) { fc, err := configOptions.OpenFile(f, GeneralConfig.GitHubAccessTokens) // only create error for non-default values if err != nil && f != ".pipeline/defaults.yaml" { - return stepConfig, errors.Wrapf(err, "config: getting defaults failed: '%v'", f) + return stepConfig, fmt.Errorf("config: getting defaults failed: '%v': %w", f, err) } if err == nil { defaultConfig = append(defaultConfig, fc) @@ -168,7 +169,7 @@ func getConfigWithFlagValues(cmd *cobra.Command) (config.StepConfig, error) { if configOptions.StageConfig { stepConfig, err = GetStageConfig() if err != nil { - return stepConfig, errors.Wrap(err, "getting stage config failed") + return stepConfig, fmt.Errorf("getting stage config failed: %w", err) } // add hooks (defaults + custom defaults) to stage-config.json output stepConfig.Config["hooks"] = stepConfig.HookConfig @@ -179,7 +180,7 @@ func getConfigWithFlagValues(cmd *cobra.Command) (config.StepConfig, error) { } metadata, err := config.ResolveMetadata(GeneralConfig.GitHubAccessTokens, GeneralConfig.MetaDataResolver, configOptions.StepMetadata, configOptions.StepName) if err != nil { - return stepConfig, errors.Wrapf(err, "failed to resolve metadata") + return stepConfig, fmt.Errorf("failed to resolve metadata: %w", err) } // prepare output resource directories: @@ -198,21 +199,21 @@ func getConfigWithFlagValues(cmd *cobra.Command) (config.StepConfig, error) { customConfig, err := configOptions.OpenFile(projectConfigFile, GeneralConfig.GitHubAccessTokens) if err != nil { if !errors.Is(err, os.ErrNotExist) { - return stepConfig, errors.Wrapf(err, "config: open configuration file '%v' failed", projectConfigFile) + return stepConfig, fmt.Errorf("config: open configuration file '%v' failed: %w", projectConfigFile, err) } customConfig = nil } defaultConfig, paramFilter, err := defaultsAndFilters(&metadata, metadata.Metadata.Name) if err != nil { - return stepConfig, errors.Wrap(err, "defaults: retrieving step defaults failed") + return stepConfig, fmt.Errorf("defaults: retrieving step defaults failed: %w", err) } for _, f := range GeneralConfig.DefaultConfig { fc, err := configOptions.OpenFile(f, GeneralConfig.GitHubAccessTokens) // only create error for non-default values if err != nil && f != ".pipeline/defaults.yaml" { - return stepConfig, errors.Wrapf(err, "config: getting defaults failed: '%v'", f) + return stepConfig, fmt.Errorf("config: getting defaults failed: '%v': %w", f, err) } if err == nil { defaultConfig = append(defaultConfig, fc) @@ -244,7 +245,7 @@ func getConfigWithFlagValues(cmd *cobra.Command) (config.StepConfig, error) { stepConfig, err = myConfig.GetStepConfig(flagValues, GeneralConfig.ParametersJSON, customConfig, defaultConfig, GeneralConfig.IgnoreCustomDefaults, paramFilter, metadata, resourceParams, GeneralConfig.StageName, metadata.Metadata.Name) if err != nil { - return stepConfig, errors.Wrap(err, "getting step config failed") + return stepConfig, fmt.Errorf("getting step config failed: %w", err) } // apply context conditions if context configuration is requested @@ -310,7 +311,7 @@ func defaultsAndFilters(metadata *config.StepData, stepName string) ([]io.ReadCl if configOptions.ContextConfig { defaults, err := metadata.GetContextDefaults(stepName) if err != nil { - return nil, config.StepFilters{}, errors.Wrap(err, "metadata: getting context defaults failed") + return nil, config.StepFilters{}, fmt.Errorf("metadata: getting context defaults failed: %w", err) } return []io.ReadCloser{defaults}, metadata.GetContextParameterFilters(), nil } diff --git a/cmd/getDefaults.go b/cmd/getDefaults.go index 855400c90..29467b8a4 100644 --- a/cmd/getDefaults.go +++ b/cmd/getDefaults.go @@ -6,7 +6,6 @@ import ( "io" "os" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/SAP/jenkins-library/pkg/config" @@ -76,7 +75,7 @@ func getDefaults() ([]map[string]string, error) { for _, f := range defaultsOptions.defaultsFiles { fc, err := defaultsOptions.openFile(f, GeneralConfig.GitHubAccessTokens) if err != nil { - return yamlDefaults, errors.Wrapf(err, "defaults: retrieving defaults file failed: '%v'", f) + return yamlDefaults, fmt.Errorf("defaults: retrieving defaults file failed: '%v': %w", f, err) } if err == nil { var yamlContent string @@ -87,7 +86,7 @@ func getDefaults() ([]map[string]string, error) { yamlContent, err = config.GetYAML(c) if err != nil { - return yamlDefaults, errors.Wrapf(err, "defaults: could not marshal YAML default file: '%v", f) + return yamlDefaults, fmt.Errorf("defaults: could not marshal YAML default file: '%v: %w", f, err) } } else { var rc config.RunConfigV1 @@ -96,7 +95,7 @@ func getDefaults() ([]map[string]string, error) { yamlContent, err = config.GetYAML(rc.PipelineConfig) if err != nil { - return yamlDefaults, errors.Wrapf(err, "defaults: could not marshal YAML default file: '%v", f) + return yamlDefaults, fmt.Errorf("defaults: could not marshal YAML default file: '%v: %w", f, err) } } @@ -123,7 +122,7 @@ func generateDefaults(utils getDefaultsUtils) ([]byte, error) { } if err != nil { - return jsonOutput, errors.Wrapf(err, "defaults: could not embed YAML defaults into JSON") + return jsonOutput, fmt.Errorf("defaults: could not embed YAML defaults into JSON: %w", err) } if len(defaultsOptions.outputFile) > 0 { diff --git a/cmd/githubCheckBranchProtection.go b/cmd/githubCheckBranchProtection.go index a3676a1bc..07d534588 100644 --- a/cmd/githubCheckBranchProtection.go +++ b/cmd/githubCheckBranchProtection.go @@ -9,8 +9,6 @@ import ( "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" - piperGithub "github.com/SAP/jenkins-library/pkg/github" ) @@ -34,7 +32,7 @@ func githubCheckBranchProtection(config githubCheckBranchProtectionOptions, tele func runGithubCheckBranchProtection(ctx context.Context, config *githubCheckBranchProtectionOptions, telemetryData *telemetry.CustomData, ghRepositoriesService gitHubBranchProtectionRepositoriesService) error { ghProtection, _, err := ghRepositoriesService.GetBranchProtection(ctx, config.Owner, config.Repository, config.Branch) if err != nil { - return errors.Wrap(err, "failed to read branch protection information") + return fmt.Errorf("failed to read branch protection information: %w", err) } // validate required status checks diff --git a/cmd/githubCommentIssue.go b/cmd/githubCommentIssue.go index d1bb0a4ff..007be9a9e 100644 --- a/cmd/githubCommentIssue.go +++ b/cmd/githubCommentIssue.go @@ -2,11 +2,11 @@ package cmd import ( "context" + "fmt" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" piperGithub "github.com/SAP/jenkins-library/pkg/github" ) @@ -35,7 +35,7 @@ func runGithubCommentIssue(ctx context.Context, config *githubCommentIssueOption newcomment, resp, err := ghIssueCommentService.CreateComment(ctx, config.Owner, config.Repository, config.Number, &issueComment) if err != nil { log.Entry().Errorf("GitHub response code %v", resp.Status) - return errors.Wrapf(err, "Error occurred when creating comment on issue %v", config.Number) + return fmt.Errorf("Error occurred when creating comment on issue %v: %w", config.Number, err) } log.Entry().Debugf("New issue comment created for issue %v: %v", config.Number, newcomment) diff --git a/cmd/githubCreateIssue.go b/cmd/githubCreateIssue.go index 9d545bbbf..2be05093e 100644 --- a/cmd/githubCreateIssue.go +++ b/cmd/githubCreateIssue.go @@ -6,7 +6,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" piperGithub "github.com/SAP/jenkins-library/pkg/github" github "github.com/google/go-github/v68/github" @@ -57,7 +56,7 @@ func getBody(config *githubCreateIssueOptions, readFile func(string) ([]byte, er if len(config.Body) == 0 { issueContent, err := readFile(config.BodyFilePath) if err != nil { - return nil, errors.Wrapf(err, "failed to read file '%v'", config.BodyFilePath) + return nil, fmt.Errorf("failed to read file '%v': %w", config.BodyFilePath, err) } bodyString = []rune(string(issueContent)) } else { diff --git a/cmd/githubCreatePullRequest.go b/cmd/githubCreatePullRequest.go index 872e50513..883fbbdd1 100644 --- a/cmd/githubCreatePullRequest.go +++ b/cmd/githubCreatePullRequest.go @@ -2,11 +2,11 @@ package cmd import ( "context" + "fmt" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" piperGithub "github.com/SAP/jenkins-library/pkg/github" ) @@ -43,7 +43,7 @@ func runGithubCreatePullRequest(ctx context.Context, config *githubCreatePullReq newPR, resp, err := ghPRService.Create(ctx, config.Owner, config.Repository, &prRequest) if err != nil { log.Entry().Errorf("GitHub response code %v", resp.Status) - return errors.Wrap(err, "Error occurred when creating pull request") + return fmt.Errorf("Error occurred when creating pull request: %w", err) } log.Entry().Debugf("New pull request created: %v", newPR) @@ -55,7 +55,7 @@ func runGithubCreatePullRequest(ctx context.Context, config *githubCreatePullReq updatedPr, resp, err := ghIssueService.Edit(ctx, config.Owner, config.Repository, newPR.GetNumber(), &issueRequest) if err != nil { log.Entry().Errorf("GitHub response code %v", resp.Status) - return errors.Wrap(err, "Error occurred when editing pull request") + return fmt.Errorf("Error occurred when editing pull request: %w", err) } log.Entry().Debugf("Updated pull request: %v", updatedPr) diff --git a/cmd/githubPublishRelease.go b/cmd/githubPublishRelease.go index 5a7e2495f..736c20694 100644 --- a/cmd/githubPublishRelease.go +++ b/cmd/githubPublishRelease.go @@ -12,7 +12,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" piperGithub "github.com/SAP/jenkins-library/pkg/github" ) @@ -55,7 +54,7 @@ func runGithubPublishRelease(ctx context.Context, config *githubPublishReleaseOp config.AddDeltaToLastRelease = false log.Entry().Debug("This is the first release.") } else { - return errors.Wrapf(err, "Error occurred when retrieving latest GitHub release (%v/%v)", config.Owner, config.Repository) + return fmt.Errorf("Error occurred when retrieving latest GitHub release (%v/%v): %w", config.Owner, config.Repository, err) } } publishedAt = lastRelease.GetPublishedAt() @@ -94,7 +93,7 @@ func runGithubPublishRelease(ctx context.Context, config *githubPublishReleaseOp createdRelease, _, err := ghRepoClient.CreateRelease(ctx, config.Owner, config.Repository, &release) if err != nil { - return errors.Wrapf(err, "Creation of release '%v' failed", *release.TagName) + return fmt.Errorf("Creation of release '%v' failed: %w", *release.TagName, err) } log.Entry().Infof("Release %v created on %v/%v", *createdRelease.TagName, config.Owner, config.Repository) @@ -189,7 +188,7 @@ func uploadReleaseAssetList(ctx context.Context, releaseID int64, config *github func uploadReleaseAsset(ctx context.Context, releaseID int64, config *githubPublishReleaseOptions, ghRepoClient GithubRepoClient) error { assets, _, err := ghRepoClient.ListReleaseAssets(ctx, config.Owner, config.Repository, releaseID, &github.ListOptions{}) if err != nil { - return errors.Wrap(err, "Failed to get list of release assets.") + return fmt.Errorf("Failed to get list of release assets.: %w", err) } var assetID int64 for _, a := range assets { @@ -202,7 +201,7 @@ func uploadReleaseAsset(ctx context.Context, releaseID int64, config *githubPubl // asset needs to be deleted first since API does not allow for replacement _, err := ghRepoClient.DeleteReleaseAsset(ctx, config.Owner, config.Repository, assetID) if err != nil { - return errors.Wrap(err, "Failed to delete release asset.") + return fmt.Errorf("Failed to delete release asset.: %w", err) } } @@ -225,13 +224,13 @@ func uploadReleaseAsset(ctx context.Context, releaseID int64, config *githubPubl } defer file.Close() if err != nil { - return errors.Wrapf(err, "Failed to load release asset '%v'", config.AssetPath) + return fmt.Errorf("Failed to load release asset '%v': %w", config.AssetPath, err) } log.Entry().Info("Starting to upload release asset.") asset, _, err := ghRepoClient.UploadReleaseAsset(ctx, config.Owner, config.Repository, releaseID, &opts, file) if err != nil { - return errors.Wrap(err, "Failed to upload release asset.") + return fmt.Errorf("Failed to upload release asset.: %w", err) } log.Entry().Infof("Done uploading asset '%v'.", asset.GetURL()) diff --git a/cmd/githubSetCommitStatus.go b/cmd/githubSetCommitStatus.go index 30b369f1d..d9d8bb124 100644 --- a/cmd/githubSetCommitStatus.go +++ b/cmd/githubSetCommitStatus.go @@ -9,8 +9,6 @@ import ( "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" - piperGithub "github.com/SAP/jenkins-library/pkg/github" ) @@ -38,7 +36,7 @@ func runGithubSetCommitStatus(ctx context.Context, config *githubSetCommitStatus if strings.Contains(fmt.Sprint(err), "No commit found for SHA") { log.SetErrorCategory(log.ErrorCustom) } - return errors.Wrapf(err, "failed to set status '%v' on commitId '%v'", config.Status, config.CommitID) + return fmt.Errorf("failed to set status '%v' on commitId '%v': %w", config.Status, config.CommitID, err) } return nil } diff --git a/cmd/gitopsUpdateDeployment.go b/cmd/gitopsUpdateDeployment.go index 8eaf5c4b2..96ad24ac2 100644 --- a/cmd/gitopsUpdateDeployment.go +++ b/cmd/gitopsUpdateDeployment.go @@ -12,6 +12,8 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/docker" gitUtil "github.com/SAP/jenkins-library/pkg/git" @@ -22,7 +24,6 @@ import ( "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" - "github.com/pkg/errors" ) const toolKubectl = "kubectl" @@ -80,7 +81,7 @@ func (g *gitopsUpdateDeploymentGitUtils) CommitFiles(filePaths []string, commitM _, err := g.worktree.Add(path) if err != nil { - return [20]byte{}, errors.Wrap(err, "failed to add file to git") + return [20]byte{}, fmt.Errorf("failed to add file to git: %w", err) } } @@ -89,7 +90,7 @@ func (g *gitopsUpdateDeploymentGitUtils) CommitFiles(filePaths []string, commitM Author: &object.Signature{Name: author, When: time.Now()}, }) if err != nil { - return [20]byte{}, errors.Wrap(err, "failed to commit file") + return [20]byte{}, fmt.Errorf("failed to commit file: %w", err) } return commit, nil @@ -103,10 +104,13 @@ func (g *gitopsUpdateDeploymentGitUtils) PlainClone(username, password, serverUR var err error g.repository, err = gitUtil.PlainClone(username, password, serverURL, branchName, directory, caCerts) if err != nil { - return errors.Wrapf(err, "plain clone failed '%s'", serverURL) + return fmt.Errorf("plain clone failed '%s': %w", serverURL, err) } g.worktree, err = g.repository.Worktree() - return errors.Wrap(err, "failed to retrieve worktree") + if err != nil { + return fmt.Errorf("failed to retrieve worktree: %w", err) + } + return nil } func (g *gitopsUpdateDeploymentGitUtils) ChangeBranch(branchName string) error { @@ -140,7 +144,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi temporaryFolder, err := fileUtils.TempDir(".", "temp-") temporaryFolder = regexp.MustCompile(`^./`).ReplaceAllString(temporaryFolder, "") if err != nil { - return errors.Wrap(err, "failed to create temporary directory") + return fmt.Errorf("failed to create temporary directory: %w", err) } defer func() { @@ -157,7 +161,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi err = cloneRepositoryAndChangeBranch(config, gitUtils, fileUtils, temporaryFolder, certs) if err != nil { - return errors.Wrap(err, "repository could not get prepared") + return fmt.Errorf("repository could not get prepared: %w", err) } filePath := filepath.Join(temporaryFolder, config.FilePath) @@ -167,7 +171,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi allFiles, err := fileUtils.Glob(filePath) if err != nil { - return errors.Wrap(err, "unable to expand globbing pattern") + return fmt.Errorf("unable to expand globbing pattern: %w", err) } else if len(allFiles) == 0 { return errors.New("no matching files found for provided globbing pattern") } @@ -178,13 +182,13 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi if config.Tool == toolKubectl { outputBytes, err = executeKubectl(config, command, currentFile) if err != nil { - return errors.Wrap(err, "error on kubectl execution") + return fmt.Errorf("error on kubectl execution: %w", err) } } else if config.Tool == toolHelm { out, err := runHelmCommand(command, config, currentFile) if err != nil { - return errors.Wrap(err, "failed to apply helm command") + return fmt.Errorf("failed to apply helm command: %w", err) } // join all helm outputs into the same "FilePath" outputBytes = append(outputBytes, []byte("---\n")...) @@ -194,7 +198,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi } else if config.Tool == toolKustomize { _, err = runKustomizeCommand(command, config, currentFile) if err != nil { - return errors.Wrap(err, "failed to apply kustomize command") + return fmt.Errorf("failed to apply kustomize command: %w", err) } outputBytes = nil } else { @@ -205,7 +209,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi if outputBytes != nil { err = fileUtils.FileWrite(currentFile, outputBytes, 0755) if err != nil { - return errors.Wrap(err, "failed to write file") + return fmt.Errorf("failed to write file: %w", err) } } } @@ -221,7 +225,7 @@ func runGitopsUpdateDeployment(config *gitopsUpdateDeploymentOptions, command gi commit, err := commitAndPushChanges(config, gitUtils, allFiles, certs) if err != nil { - return errors.Wrap(err, "failed to commit and push changes") + return fmt.Errorf("failed to commit and push changes: %w", err) } log.Entry().Infof("Changes committed with %s", commit.String()) @@ -233,19 +237,19 @@ func checkRequiredFieldsForDeployTool(config *gitopsUpdateDeploymentOptions) err if config.Tool == toolHelm { err := checkRequiredFieldsForHelm(config) if err != nil { - return errors.Wrap(err, "missing required fields for helm") + return fmt.Errorf("missing required fields for helm: %w", err) } logNotRequiredButFilledFieldForHelm(config) } else if config.Tool == toolKubectl { err := checkRequiredFieldsForKubectl(config) if err != nil { - return errors.Wrap(err, "missing required fields for kubectl") + return fmt.Errorf("missing required fields for kubectl: %w", err) } logNotRequiredButFilledFieldForKubectl(config) } else if config.Tool == toolKustomize { err := checkRequiredFieldsForKustomize(config) if err != nil { - return errors.Wrap(err, "missing required fields for kustomize") + return fmt.Errorf("missing required fields for kustomize: %w", err) } logNotRequiredButFilledFieldForKustomize(config) } @@ -263,7 +267,7 @@ func checkRequiredFieldsForHelm(config *gitopsUpdateDeploymentOptions) error { } if len(missingParameters) > 0 { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("the following parameters are necessary for helm: %v", missingParameters) + return fmt.Errorf("the following parameters are necessary for helm: %v", missingParameters) } return nil } @@ -278,7 +282,7 @@ func checkRequiredFieldsForKustomize(config *gitopsUpdateDeploymentOptions) erro } if len(missingParameters) > 0 { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("the following parameters are necessary for kustomize: %v", missingParameters) + return fmt.Errorf("the following parameters are necessary for kustomize: %v", missingParameters) } return nil } @@ -290,7 +294,7 @@ func checkRequiredFieldsForKubectl(config *gitopsUpdateDeploymentOptions) error } if len(missingParameters) > 0 { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("the following parameters are necessary for kubectl: %v", missingParameters) + return fmt.Errorf("the following parameters are necessary for kubectl: %v", missingParameters) } return nil } @@ -325,12 +329,12 @@ func cloneRepositoryAndChangeBranch(config *gitopsUpdateDeploymentOptions, gitUt err := gitUtils.PlainClone(config.Username, config.Password, config.ServerURL, config.BranchName, temporaryFolder, certs) if err != nil { - return errors.Wrap(err, "failed to plain clone repository") + return fmt.Errorf("failed to plain clone repository: %w", err) } err = gitUtils.ChangeBranch(config.BranchName) if err != nil { - return errors.Wrap(err, "failed to change branch") + return fmt.Errorf("failed to change branch: %w", err) } return nil } @@ -363,14 +367,14 @@ func executeKubectl(config *gitopsUpdateDeploymentOptions, command gitopsUpdateD var outputBytes []byte registryImage, err := buildRegistryPlusImage(config) if err != nil { - return nil, errors.Wrap(err, "failed to apply kubectl command") + return nil, fmt.Errorf("failed to apply kubectl command: %w", err) } patchString := "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"" + config.ContainerName + "\",\"image\":\"" + registryImage + "\"}]}}}}" log.Entry().Infof("[kubectl] updating '%s'", filePath) outputBytes, err = runKubeCtlCommand(command, patchString, filePath) if err != nil { - return nil, errors.Wrap(err, "failed to apply kubectl command") + return nil, fmt.Errorf("failed to apply kubectl command: %w", err) } return outputBytes, nil } @@ -383,7 +387,7 @@ func buildRegistryPlusImage(config *gitopsUpdateDeploymentOptions) (string, erro url, err := docker.ContainerRegistryFromURL(registryURL) if err != nil { - return "", errors.Wrap(err, "registry URL could not be extracted") + return "", fmt.Errorf("registry URL could not be extracted: %w", err) } if url != "" { url = url + "/" @@ -404,7 +408,7 @@ func runKubeCtlCommand(command gitopsUpdateDeploymentExecRunner, patchString str } err := command.RunExecutable(toolKubectl, kubeParams...) if err != nil { - return nil, errors.Wrap(err, "failed to apply kubectl command") + return nil, fmt.Errorf("failed to apply kubectl command: %w", err) } return kubectlOutput.Bytes(), nil } @@ -415,7 +419,7 @@ func runHelmCommand(command gitopsUpdateDeploymentExecRunner, config *gitopsUpda registryImage, imageTag, err := buildRegistryPlusImageAndTagSeparately(config) if err != nil { - return nil, errors.Wrap(err, "failed to extract registry URL, image name, and image tag") + return nil, fmt.Errorf("failed to extract registry URL, image name, and image tag: %w", err) } helmParams := []string{ "template", @@ -432,7 +436,7 @@ func runHelmCommand(command gitopsUpdateDeploymentExecRunner, config *gitopsUpda log.Entry().Infof("[helmn] updating '%s'", filePath) err = command.RunExecutable(toolHelm, helmParams...) if err != nil { - return nil, errors.Wrap(err, "failed to execute helm command") + return nil, fmt.Errorf("failed to execute helm command: %w", err) } return helmOutput.Bytes(), nil } @@ -454,7 +458,7 @@ func runKustomizeCommand(command gitopsUpdateDeploymentExecRunner, config *gitop log.Entry().Infof("[kustomize] updating '%s'", filePath) err = command.RunExecutable(toolKustomize, kustomizeParams...) if err != nil { - return nil, errors.Wrap(err, "failed to execute kustomize command") + return nil, fmt.Errorf("failed to execute kustomize command: %w", err) } return kustomizeOutput.Bytes(), nil @@ -468,7 +472,7 @@ func buildRegistryPlusImageAndTagSeparately(config *gitopsUpdateDeploymentOption if registryURL != "" { containerURL, err := docker.ContainerRegistryFromURL(registryURL) if err != nil { - return "", "", errors.Wrap(err, "registry URL could not be extracted") + return "", "", fmt.Errorf("registry URL could not be extracted: %w", err) } if containerURL != "" { containerURL = containerURL + "/" @@ -507,12 +511,12 @@ func commitAndPushChanges(config *gitopsUpdateDeploymentOptions, gitUtils iGitop commit, err := gitUtils.CommitFiles(filePaths, commitMessage, config.Username) if err != nil { - return [20]byte{}, errors.Wrap(err, "committing changes failed") + return [20]byte{}, fmt.Errorf("committing changes failed: %w", err) } err = gitUtils.PushChangesToRepository(config.Username, config.Password, &config.ForcePush, certs) if err != nil { - return [20]byte{}, errors.Wrap(err, "pushing changes failed") + return [20]byte{}, fmt.Errorf("pushing changes failed: %w", err) } return commit, nil diff --git a/cmd/gitopsUpdateDeployment_test.go b/cmd/gitopsUpdateDeployment_test.go index f776c7c23..74d82061f 100644 --- a/cmd/gitopsUpdateDeployment_test.go +++ b/cmd/gitopsUpdateDeployment_test.go @@ -5,15 +5,16 @@ package cmd import ( "errors" - "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/go-git/go-git/v5" - "github.com/go-git/go-git/v5/plumbing" - "github.com/stretchr/testify/assert" "io" "os" "path/filepath" "strings" "testing" + + "github.com/SAP/jenkins-library/pkg/piperutils" + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing" + "github.com/stretchr/testify/assert" ) func TestBuildRegistryPlusImage(t *testing.T) { diff --git a/cmd/gradleExecuteBuild_test.go b/cmd/gradleExecuteBuild_test.go index 2d9317d52..99f3e7ab9 100644 --- a/cmd/gradleExecuteBuild_test.go +++ b/cmd/gradleExecuteBuild_test.go @@ -9,7 +9,8 @@ import ( "path/filepath" "testing" - "github.com/pkg/errors" + "errors" + "github.com/stretchr/testify/assert" "github.com/SAP/jenkins-library/pkg/config" diff --git a/cmd/hadolintExecute.go b/cmd/hadolintExecute.go index fcfcf4f3a..1f006f1a2 100644 --- a/cmd/hadolintExecute.go +++ b/cmd/hadolintExecute.go @@ -2,6 +2,7 @@ package cmd import ( "bytes" + "fmt" "io" "net/http" "os" @@ -12,7 +13,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) const hadolintCommand = "hadolint" @@ -86,7 +86,7 @@ func runHadolint(config hadolintExecuteOptions, utils hadolintUtils) error { } utils.SetOptions(clientOptions) if err := loadConfigurationFile(config.ConfigurationURL, config.ConfigurationFile, utils); err != nil { - return errors.Wrap(err, "failed to load configuration file from URL") + return fmt.Errorf("failed to load configuration file from URL: %w", err) } } // use config @@ -109,7 +109,7 @@ func runHadolint(config hadolintExecuteOptions, utils hadolintUtils) error { } } else if err != nil { // if stdout is empty a processing issue occured - return errors.Wrap(err, errorBuffer.String()) + return fmt.Errorf(errorBuffer.String(), err) } //TODO: mock away in tests // persist report information diff --git a/cmd/helmExecute_test.go b/cmd/helmExecute_test.go index 521fca26a..7b3b4851b 100644 --- a/cmd/helmExecute_test.go +++ b/cmd/helmExecute_test.go @@ -9,10 +9,11 @@ import ( "path" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/kubernetes/mocks" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/piperenv" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/cmd/imagePushToRegistry.go b/cmd/imagePushToRegistry.go index fc70ee8f4..712d46f75 100644 --- a/cmd/imagePushToRegistry.go +++ b/cmd/imagePushToRegistry.go @@ -6,8 +6,9 @@ import ( "regexp" "strings" + "errors" + v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/pkg/errors" "golang.org/x/sync/errgroup" "github.com/SAP/jenkins-library/pkg/command" @@ -107,30 +108,30 @@ func runImagePushToRegistry(config *imagePushToRegistryOptions, telemetryData *t log.Entry().Debug("Handling destination registry credentials") if err := handleCredentialsForPrivateRegistry(config.DockerConfigJSON, config.TargetRegistryURL, config.TargetRegistryUser, config.TargetRegistryPassword, utils); err != nil { - return errors.Wrap(err, "failed to handle credentials for target registry") + return fmt.Errorf("failed to handle credentials for target registry: %w", err) } if config.PushLocalDockerImage { if err := pushLocalImageToTargetRegistry(config, utils); err != nil { - return errors.Wrapf(err, "failed to push local image to %q", config.TargetRegistryURL) + return fmt.Errorf("failed to push local image to %q: %w", config.TargetRegistryURL, err) } return nil } log.Entry().Debug("Handling source registry credentials") if err := handleCredentialsForPrivateRegistry(config.DockerConfigJSON, config.SourceRegistryURL, config.SourceRegistryUser, config.SourceRegistryPassword, utils); err != nil { - return errors.Wrap(err, "failed to handle credentials for source registry") + return fmt.Errorf("failed to handle credentials for source registry: %w", err) } if config.UseImageNameTags { if err := pushImageNameTagsToTargetRegistry(config, utils); err != nil { - return errors.Wrapf(err, "failed to push imageNameTags to target registry") + return fmt.Errorf("failed to push imageNameTags to target registry: %w", err) } return nil } if err := copyImages(config, utils); err != nil { - return errors.Wrap(err, "failed to copy images") + return fmt.Errorf("failed to copy images: %w", err) } return nil @@ -143,17 +144,17 @@ func handleCredentialsForPrivateRegistry(dockerConfigJsonPath, registry, usernam } if _, err := docker.CreateDockerConfigJSON(registry, username, password, "", targetDockerConfigPath, utils); err != nil { - return errors.Wrap(err, "failed to create new docker config") + return fmt.Errorf("failed to create new docker config: %w", err) } return nil } if _, err := docker.CreateDockerConfigJSON(registry, username, password, targetDockerConfigPath, dockerConfigJsonPath, utils); err != nil { - return errors.Wrapf(err, "failed to update docker config %q", dockerConfigJsonPath) + return fmt.Errorf("failed to update docker config %q: %w", dockerConfigJsonPath, err) } if err := docker.MergeDockerConfigJSON(targetDockerConfigPath, dockerConfigJsonPath, utils); err != nil { - return errors.Wrapf(err, "failed to merge docker config files") + return fmt.Errorf("failed to merge docker config files: %w", err) } return nil diff --git a/cmd/integrationArtifactDeploy.go b/cmd/integrationArtifactDeploy.go index cb2fef423..8493b4b4c 100644 --- a/cmd/integrationArtifactDeploy.go +++ b/cmd/integrationArtifactDeploy.go @@ -6,13 +6,14 @@ import ( "net/http" "time" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/cpi" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) const retryCount = 14 @@ -77,14 +78,14 @@ func runIntegrationArtifactDeploy(config *integrationArtifactDeployOptions, tele tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := "POST" deployResp, httpErr := httpClient.SendRequest(httpMethod, deployURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, deployURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, deployURL, httpErr) } if deployResp != nil && deployResp.Body != nil { @@ -92,7 +93,7 @@ func runIntegrationArtifactDeploy(config *integrationArtifactDeployOptions, tele } if deployResp == nil { - return errors.Errorf("did not retrieve a HTTP response") + return fmt.Errorf("did not retrieve a HTTP response") } if deployResp.StatusCode == http.StatusAccepted { @@ -101,7 +102,7 @@ func runIntegrationArtifactDeploy(config *integrationArtifactDeployOptions, tele Info("successfully deployed into CPI runtime") taskId, readErr := io.ReadAll(deployResp.Body) if readErr != nil { - return errors.Wrap(readErr, "Task Id not found. HTTP response body could not be read.") + return fmt.Errorf("Task Id not found. HTTP response body could not be read.: %w", readErr) } deploymentError := pollIFlowDeploymentStatus(string(taskId), retryCount, config, httpClient, serviceKey.OAuth.Host) return deploymentError @@ -109,10 +110,10 @@ func runIntegrationArtifactDeploy(config *integrationArtifactDeployOptions, tele responseBody, readErr := io.ReadAll(deployResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", deployResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", deployResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", string(responseBody), deployResp.StatusCode) - return errors.Errorf("integration flow deployment failed, response Status code: %v", deployResp.StatusCode) + return fmt.Errorf("integration flow deployment failed, response Status code: %v", deployResp.StatusCode) } // pollIFlowDeploymentStatus - Poll the integration flow deployment status, return status or error details @@ -156,10 +157,10 @@ func pollIFlowDeploymentStatus(taskId string, retryCount int, config *integratio func getHTTPErrorMessage(httpErr error, response *http.Response, httpMethod, statusURL string) (string, error) { responseBody, readErr := io.ReadAll(response.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", response.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", response.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, response status code: %v", string(responseBody), response.StatusCode) - return "", errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpMethod, statusURL, responseBody) + return "", fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpMethod, statusURL, responseBody, httpErr) } // getIntegrationArtifactDeployStatus - Get integration artifact Deploy Status @@ -176,7 +177,7 @@ func getIntegrationArtifactDeployStatus(config *integrationArtifactDeployOptions } if deployStatusResp == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if deployStatusResp.StatusCode == http.StatusOK { @@ -186,11 +187,11 @@ func getIntegrationArtifactDeployStatus(config *integrationArtifactDeployOptions bodyText, readErr := io.ReadAll(deployStatusResp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", deployStatusResp.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", deployStatusResp.StatusCode, readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return "", errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return "", fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } deployStatus := jsonResponse.Path("d.Status").Data().(string) return deployStatus, nil @@ -198,7 +199,7 @@ func getIntegrationArtifactDeployStatus(config *integrationArtifactDeployOptions if httpErr != nil { return getHTTPErrorMessage(httpErr, deployStatusResp, httpMethod, deployStatusURL) } - return "", errors.Errorf("failed to get Integration Flow artefact runtime status, response Status code: %v", deployStatusResp.StatusCode) + return "", fmt.Errorf("failed to get Integration Flow artefact runtime status, response Status code: %v", deployStatusResp.StatusCode) } // getIntegrationArtifactDeployError - Get integration artifact deploy error details @@ -214,7 +215,7 @@ func getIntegrationArtifactDeployError(config *integrationArtifactDeployOptions, } if errorStatusResp == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if errorStatusResp.StatusCode == http.StatusOK { @@ -223,7 +224,7 @@ func getIntegrationArtifactDeployError(config *integrationArtifactDeployOptions, Info("Successfully retrieved Integration Flow artefact deploy error details") responseBody, readErr := io.ReadAll(errorStatusResp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", errorStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), errorStatusResp.StatusCode) errorDetails := string(responseBody) @@ -232,5 +233,5 @@ func getIntegrationArtifactDeployError(config *integrationArtifactDeployOptions, if httpErr != nil { return getHTTPErrorMessage(httpErr, errorStatusResp, httpMethod, errorStatusURL) } - return "", errors.Errorf("failed to get Integration Flow artefact deploy error details, response Status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("failed to get Integration Flow artefact deploy error details, response Status code: %v", errorStatusResp.StatusCode) } diff --git a/cmd/integrationArtifactDownload.go b/cmd/integrationArtifactDownload.go index 6c703de82..62ece5ee7 100644 --- a/cmd/integrationArtifactDownload.go +++ b/cmd/integrationArtifactDownload.go @@ -12,7 +12,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactDownload(config integrationArtifactDownloadOptions, telemetryData *telemetry.CustomData) { @@ -44,22 +43,22 @@ func runIntegrationArtifactDownload(config *integrationArtifactDownloadOptions, tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := "GET" downloadResp, httpErr := httpClient.SendRequest(httpMethod, downloadArtifactURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, downloadArtifactURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, downloadArtifactURL, httpErr) } if downloadResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } contentDisposition := downloadResp.Header.Get("Content-Disposition") disposition, params, err := mime.ParseMediaType(contentDisposition) if err != nil { - return errors.Wrapf(err, "failed to read filename from http response headers, Content-Disposition %s", disposition) + return fmt.Errorf("failed to read filename from http response headers, Content-Disposition %s: %w", disposition, err) } filename := params["filename"] @@ -71,12 +70,12 @@ func runIntegrationArtifactDownload(config *integrationArtifactDownloadOptions, workspaceRelativePath := config.DownloadPath err = os.MkdirAll(workspaceRelativePath, 0755) if err != nil { - return errors.Wrap(err, "Failed to create workspace directory") + return fmt.Errorf("Failed to create workspace directory: %w", err) } zipFileName := filepath.Join(workspaceRelativePath, filename) file, err := os.Create(zipFileName) if err != nil { - return errors.Wrap(err, "Failed to create integration flow artifact file") + return fmt.Errorf("Failed to create integration flow artifact file: %w", err) } if _, err := io.Copy(file, downloadResp.Body); err != nil { return err @@ -86,9 +85,9 @@ func runIntegrationArtifactDownload(config *integrationArtifactDownloadOptions, responseBody, readErr := io.ReadAll(downloadResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code : %v", downloadResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code : %v: %w", downloadResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", string(responseBody), downloadResp.StatusCode) - return errors.Errorf("Integration Flow artifact download failed, Response Status code: %v", downloadResp.StatusCode) + return fmt.Errorf("Integration Flow artifact download failed, Response Status code: %v", downloadResp.StatusCode) } diff --git a/cmd/integrationArtifactGetMplStatus.go b/cmd/integrationArtifactGetMplStatus.go index f11c82e0f..3e4f7a9b0 100644 --- a/cmd/integrationArtifactGetMplStatus.go +++ b/cmd/integrationArtifactGetMplStatus.go @@ -6,12 +6,13 @@ import ( "net/http" "net/url" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/cpi" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactGetMplStatus(config integrationArtifactGetMplStatusOptions, telemetryData *telemetry.CustomData, commonPipelineEnvironment *integrationArtifactGetMplStatusCommonPipelineEnvironment) { @@ -50,14 +51,14 @@ func runIntegrationArtifactGetMplStatus( tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := "GET" mplStatusResp, httpErr := httpClient.SendRequest(httpMethod, mplStatusEncodedURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, mplStatusEncodedURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, mplStatusEncodedURL, httpErr) } if mplStatusResp != nil && mplStatusResp.Body != nil { @@ -65,20 +66,20 @@ func runIntegrationArtifactGetMplStatus( } if mplStatusResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if mplStatusResp.StatusCode == 200 { bodyText, readErr := io.ReadAll(mplStatusResp.Body) if readErr != nil { - return errors.Wrap(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } if jsonResponse == nil { - return errors.Errorf("Empty json response: %v", string(bodyText)) + return fmt.Errorf("Empty json response: %v", string(bodyText)) } if jsonResponse.Exists("d", "results", "0") { mplStatus := jsonResponse.Path("d.results.0.Status").Data().(string) @@ -99,11 +100,11 @@ func runIntegrationArtifactGetMplStatus( responseBody, readErr := io.ReadAll(mplStatusResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", mplStatusResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", mplStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), mplStatusResp.StatusCode) - return errors.Errorf("Unable to get integration flow MPL status, Response Status code: %v", mplStatusResp.StatusCode) + return fmt.Errorf("Unable to get integration flow MPL status, Response Status code: %v", mplStatusResp.StatusCode) } // getIntegrationArtifactMPLError - Get integration artifact MPL error details @@ -119,7 +120,7 @@ func getIntegrationArtifactMPLError(commonPipelineEnvironment *integrationArtifa } if errorStatusResp == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if errorStatusResp.StatusCode == http.StatusOK { @@ -128,7 +129,7 @@ func getIntegrationArtifactMPLError(commonPipelineEnvironment *integrationArtifa Info("Successfully retrieved Integration Flow artefact message processing error") responseBody, readErr := io.ReadAll(errorStatusResp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", errorStatusResp.StatusCode, readErr) } mplErrorDetails := string(responseBody) commonPipelineEnvironment.custom.integrationFlowMplError = mplErrorDetails @@ -137,5 +138,5 @@ func getIntegrationArtifactMPLError(commonPipelineEnvironment *integrationArtifa if httpErr != nil { return getHTTPErrorMessage(httpErr, errorStatusResp, httpMethod, errorStatusURL) } - return "", errors.Errorf("failed to get Integration Flow artefact message processing error, response Status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("failed to get Integration Flow artefact message processing error, response Status code: %v", errorStatusResp.StatusCode) } diff --git a/cmd/integrationArtifactGetServiceEndpoint.go b/cmd/integrationArtifactGetServiceEndpoint.go index acee50029..992d045f3 100644 --- a/cmd/integrationArtifactGetServiceEndpoint.go +++ b/cmd/integrationArtifactGetServiceEndpoint.go @@ -11,7 +11,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactGetServiceEndpoint(config integrationArtifactGetServiceEndpointOptions, telemetryData *telemetry.CustomData, commonPipelineEnvironment *integrationArtifactGetServiceEndpointCommonPipelineEnvironment) { @@ -43,7 +42,7 @@ func runIntegrationArtifactGetServiceEndpoint(config *integrationArtifactGetServ tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -51,7 +50,7 @@ func runIntegrationArtifactGetServiceEndpoint(config *integrationArtifactGetServ serviceEndpointResp, httpErr := httpClient.SendRequest(httpMethod, servieEndpointURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, servieEndpointURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, servieEndpointURL, httpErr) } if serviceEndpointResp != nil && serviceEndpointResp.Body != nil { @@ -59,17 +58,17 @@ func runIntegrationArtifactGetServiceEndpoint(config *integrationArtifactGetServ } if serviceEndpointResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if serviceEndpointResp.StatusCode == 200 { bodyText, readErr := io.ReadAll(serviceEndpointResp.Body) if readErr != nil { - return errors.Wrap(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } for _, child := range jsonResponse.S("d", "results").Children() { @@ -81,15 +80,15 @@ func runIntegrationArtifactGetServiceEndpoint(config *integrationArtifactGetServ return nil } } - return errors.Errorf("Unable to get integration flow service endpoint '%v', Response body: %v, Response Status code: %v", + return fmt.Errorf("Unable to get integration flow service endpoint '%v', Response body: %v, Response Status code: %v", config.IntegrationFlowID, string(bodyText), serviceEndpointResp.StatusCode) } responseBody, readErr := io.ReadAll(serviceEndpointResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", serviceEndpointResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", serviceEndpointResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), serviceEndpointResp.StatusCode) - return errors.Errorf("Unable to get integration flow service endpoint, Response Status code: %v", serviceEndpointResp.StatusCode) + return fmt.Errorf("Unable to get integration flow service endpoint, Response Status code: %v", serviceEndpointResp.StatusCode) } diff --git a/cmd/integrationArtifactResource.go b/cmd/integrationArtifactResource.go index 0e375519b..57307ebe6 100644 --- a/cmd/integrationArtifactResource.go +++ b/cmd/integrationArtifactResource.go @@ -10,13 +10,14 @@ import ( "path/filepath" "strings" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/cpi" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type integrationArtifactResourceData struct { @@ -58,7 +59,7 @@ func runIntegrationArtifactResource(config *integrationArtifactResourceOptions, tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -83,7 +84,7 @@ func UploadIntegrationArtifactResource(config *integrationArtifactResourceOption header.Add("content-type", "application/json") payload, jsonError := GetJSONPayload(config, "create", fileUtils) if jsonError != nil { - return errors.Wrapf(jsonError, "Failed to get json payload for file %v, failed with error", config.ResourcePath) + return fmt.Errorf("Failed to get json payload for file %v, failed with error: %w", config.ResourcePath, jsonError) } uploadIflowStatusResp, httpErr := httpClient.SendRequest(httpMethod, uploadIflowStatusURL, payload, header, nil) @@ -115,7 +116,7 @@ func UpdateIntegrationArtifactResource(config *integrationArtifactResourceOption updateIflowStatusURL := fmt.Sprintf("%s/api/v1/IntegrationDesigntimeArtifacts(Id='%s',Version='%s')/$links/Resources(Name='%s',ResourceType='%s')", apiHost, config.IntegrationFlowID, "Active", fileName, fileExt) payload, jsonError := GetJSONPayload(config, "update", fileUtils) if jsonError != nil { - return errors.Wrapf(jsonError, "Failed to get json payload for file %v, failed with error", config.ResourcePath) + return fmt.Errorf("Failed to get json payload for file %v, failed with error: %w", config.ResourcePath, jsonError) } updateIflowStatusResp, httpErr := httpClient.SendRequest(httpMethod, updateIflowStatusURL, payload, header, nil) @@ -164,7 +165,7 @@ func DeleteIntegrationArtifactResource(config *integrationArtifactResourceOption func GetJSONPayload(config *integrationArtifactResourceOptions, mode string, fileUtils piperutils.FileUtils) (*bytes.Buffer, error) { fileContent, readError := fileUtils.FileRead(config.ResourcePath) if readError != nil { - return nil, errors.Wrapf(readError, "Error reading file") + return nil, fmt.Errorf("Error reading file: %w", readError) } fileName := filepath.Base(config.ResourcePath) jsonObj := gabs.New() @@ -181,7 +182,7 @@ func GetJSONPayload(config *integrationArtifactResourceOptions, mode string, fil jsonBody, jsonErr := json.Marshal(jsonObj) if jsonErr != nil { - return nil, errors.Wrapf(jsonErr, "json payload is invalid for integration flow artifact %q", config.IntegrationFlowID) + return nil, fmt.Errorf("json payload is invalid for integration flow artifact %q: %w", config.IntegrationFlowID, jsonErr) } return bytes.NewBuffer(jsonBody), nil } @@ -211,7 +212,7 @@ func HttpResponseHandler(resp *http.Response, httpErr error, integrationArtifact } if resp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if resp.StatusCode == integrationArtifactResourceData.StatusCode { @@ -223,10 +224,10 @@ func HttpResponseHandler(resp *http.Response, httpErr error, integrationArtifact if httpErr != nil { responseBody, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", resp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", resp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), resp.StatusCode) - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", integrationArtifactResourceData.Method, integrationArtifactResourceData.URL, string(responseBody)) + return fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", integrationArtifactResourceData.Method, integrationArtifactResourceData.URL, string(responseBody), httpErr) } - return errors.Errorf("%s, Response Status code: %v", integrationArtifactResourceData.FlrMessage, resp.StatusCode) + return fmt.Errorf("%s, Response Status code: %v", integrationArtifactResourceData.FlrMessage, resp.StatusCode) } diff --git a/cmd/integrationArtifactTransport.go b/cmd/integrationArtifactTransport.go index d2c67397f..cdbefc4e7 100644 --- a/cmd/integrationArtifactTransport.go +++ b/cmd/integrationArtifactTransport.go @@ -9,12 +9,13 @@ import ( "net/http" "time" + "errors" + "github.com/Jeffail/gabs/v2" "github.com/SAP/jenkins-library/pkg/apim" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactTransport(config integrationArtifactTransportOptions, telemetryData *telemetry.CustomData) { @@ -43,13 +44,13 @@ func CreateIntegrationArtifactTransportRequest(config *integrationArtifactTransp header.Add("content-type", "application/json") payload, jsonError := GetCPITransportReqPayload(config) if jsonError != nil { - return errors.Wrapf(jsonError, "Failed to get json payload for file %v, failed with error", config.IntegrationPackageID) + return fmt.Errorf("Failed to get json payload for file %v, failed with error: %w", config.IntegrationPackageID, jsonError) } createTransportRequestResp, httpErr := httpClient.SendRequest(httpMethod, createTransportRequestURL, payload, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, createTransportRequestURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, createTransportRequestURL, httpErr) } if createTransportRequestResp != nil && createTransportRequestResp.Body != nil { @@ -57,7 +58,7 @@ func CreateIntegrationArtifactTransportRequest(config *integrationArtifactTransp } if createTransportRequestResp == nil { - return errors.Errorf("did not retrieve a HTTP response") + return fmt.Errorf("did not retrieve a HTTP response") } if createTransportRequestResp.StatusCode == http.StatusAccepted { @@ -67,11 +68,11 @@ func CreateIntegrationArtifactTransportRequest(config *integrationArtifactTransp bodyText, readErr := io.ReadAll(createTransportRequestResp.Body) if readErr != nil { - return errors.Wrap(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } processId := jsonResponse.Path("processId").Data().(string) @@ -84,10 +85,10 @@ func CreateIntegrationArtifactTransportRequest(config *integrationArtifactTransp responseBody, readErr := io.ReadAll(createTransportRequestResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", createTransportRequestResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", createTransportRequestResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", string(responseBody), createTransportRequestResp.StatusCode) - return errors.Errorf("integration flow deployment failed, response Status code: %v", createTransportRequestResp.StatusCode) + return fmt.Errorf("integration flow deployment failed, response Status code: %v", createTransportRequestResp.StatusCode) } // pollTransportStatus - Poll the integration package transport processing, return status or error details @@ -148,7 +149,7 @@ func GetCPITransportReqPayload(config *integrationArtifactTransportOptions) (*by jsonBody, jsonErr := json.Marshal(jsonObj) if jsonErr != nil { - return nil, errors.Wrapf(jsonErr, "Transport request payload is invalid for integration package artifact %q", config.IntegrationPackageID) + return nil, fmt.Errorf("Transport request payload is invalid for integration package artifact %q: %w", config.IntegrationPackageID, jsonErr) } return bytes.NewBuffer(jsonBody), nil } @@ -167,7 +168,7 @@ func getIntegrationTransportProcessingStatus(config *integrationArtifactTranspor } if transportProcStatusResp == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if (transportProcStatusResp.StatusCode == http.StatusOK) || (transportProcStatusResp.StatusCode == http.StatusAccepted) { @@ -177,11 +178,11 @@ func getIntegrationTransportProcessingStatus(config *integrationArtifactTranspor bodyText, readErr := io.ReadAll(transportProcStatusResp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", transportProcStatusResp.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", transportProcStatusResp.StatusCode, readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return "", errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return "", fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } contentTransporStatus := jsonResponse.Path("state").Data().(string) return contentTransporStatus, nil @@ -189,7 +190,7 @@ func getIntegrationTransportProcessingStatus(config *integrationArtifactTranspor if httpErr != nil { return getHTTPErrorMessage(httpErr, transportProcStatusResp, httpMethod, transportProcStatusURL) } - return "", errors.Errorf("failed to get transport request processing status, response Status code: %v", transportProcStatusResp.StatusCode) + return "", fmt.Errorf("failed to get transport request processing status, response Status code: %v", transportProcStatusResp.StatusCode) } // getTransportError - Get integration package transport failures error details @@ -205,7 +206,7 @@ func getIntegrationTransportError(config *integrationArtifactTransportOptions, h } if errorStatusResp == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if errorStatusResp.StatusCode == http.StatusOK { @@ -214,7 +215,7 @@ func getIntegrationTransportError(config *integrationArtifactTransportOptions, h Info("Successfully retrieved deployment failures error details") responseBody, readErr := io.ReadAll(errorStatusResp.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", errorStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), errorStatusResp.StatusCode) errorDetails := string(responseBody) @@ -223,5 +224,5 @@ func getIntegrationTransportError(config *integrationArtifactTransportOptions, h if httpErr != nil { return getHTTPErrorMessage(httpErr, errorStatusResp, httpMethod, errorStatusURL) } - return "", errors.Errorf("failed to get Integration Package transport error details, response Status code: %v", errorStatusResp.StatusCode) + return "", fmt.Errorf("failed to get Integration Package transport error details, response Status code: %v", errorStatusResp.StatusCode) } diff --git a/cmd/integrationArtifactTriggerIntegrationTest.go b/cmd/integrationArtifactTriggerIntegrationTest.go index 90b4bdc1b..8d57d542a 100644 --- a/cmd/integrationArtifactTriggerIntegrationTest.go +++ b/cmd/integrationArtifactTriggerIntegrationTest.go @@ -14,7 +14,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type integrationArtifactTriggerIntegrationTestUtils interface { @@ -137,7 +136,7 @@ func callIFlowURL( tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpIFlowClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) clientOptions.MaxRetries = -1 @@ -145,11 +144,11 @@ func callIFlowURL( iFlowResp, httpErr := httpIFlowClient.SendRequest(httpMethod, serviceEndpointUrl, bytes.NewBuffer(fileBody), header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %q request to %q failed with error", httpMethod, serviceEndpointUrl) + return fmt.Errorf("HTTP %q request to %q failed with error: %w", httpMethod, serviceEndpointUrl, httpErr) } if iFlowResp == nil { - return errors.Errorf("did not retrieve any HTTP response") + return fmt.Errorf("did not retrieve any HTTP response") } if iFlowResp.StatusCode < 400 { diff --git a/cmd/integrationArtifactUnDeploy.go b/cmd/integrationArtifactUnDeploy.go index 6fef01cf7..fe09ac13a 100644 --- a/cmd/integrationArtifactUnDeploy.go +++ b/cmd/integrationArtifactUnDeploy.go @@ -9,7 +9,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactUnDeploy(config integrationArtifactUnDeployOptions, telemetryData *telemetry.CustomData) { @@ -40,14 +39,14 @@ func runIntegrationArtifactUnDeploy(config *integrationArtifactUnDeployOptions, tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) httpMethod := "DELETE" unDeployResp, httpErr := httpClient.SendRequest(httpMethod, unDeployURL, nil, header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", httpMethod, unDeployURL) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", httpMethod, unDeployURL, httpErr) } if unDeployResp != nil && unDeployResp.Body != nil { @@ -55,7 +54,7 @@ func runIntegrationArtifactUnDeploy(config *integrationArtifactUnDeployOptions, } if unDeployResp == nil { - return errors.Errorf("did not retrieve a HTTP response") + return fmt.Errorf("did not retrieve a HTTP response") } if unDeployResp.StatusCode == http.StatusAccepted { @@ -67,8 +66,8 @@ func runIntegrationArtifactUnDeploy(config *integrationArtifactUnDeployOptions, responseBody, readErr := io.ReadAll(unDeployResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", unDeployResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", unDeployResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", string(responseBody), unDeployResp.StatusCode) - return errors.Errorf("integration flow undeployment failed, response Status code: %v", unDeployResp.StatusCode) + return fmt.Errorf("integration flow undeployment failed, response Status code: %v", unDeployResp.StatusCode) } diff --git a/cmd/integrationArtifactUnDeploy_test.go b/cmd/integrationArtifactUnDeploy_test.go index 8109f8ba5..21b699c37 100644 --- a/cmd/integrationArtifactUnDeploy_test.go +++ b/cmd/integrationArtifactUnDeploy_test.go @@ -4,8 +4,9 @@ package cmd import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestRunIntegrationArtifactUnDeploy(t *testing.T) { diff --git a/cmd/integrationArtifactUpdateConfiguration.go b/cmd/integrationArtifactUpdateConfiguration.go index ddaf53de1..b3e6042a6 100644 --- a/cmd/integrationArtifactUpdateConfiguration.go +++ b/cmd/integrationArtifactUpdateConfiguration.go @@ -12,7 +12,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactUpdateConfiguration(config integrationArtifactUpdateConfigurationOptions, telemetryData *telemetry.CustomData) { @@ -42,7 +41,7 @@ func runIntegrationArtifactUpdateConfiguration(config *integrationArtifactUpdate tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -55,11 +54,11 @@ func runIntegrationArtifactUpdateConfiguration(config *integrationArtifactUpdate jsonBody, jsonErr := json.Marshal(jsonObj) if jsonErr != nil { - return errors.Wrapf(jsonErr, "input json body is invalid for parameterValue %q", config.ParameterValue) + return fmt.Errorf("input json body is invalid for parameterValue %q: %w", config.ParameterValue, jsonErr) } configUpdateResp, httpErr := httpClient.SendRequest(httpMethod, configUpdateURL, bytes.NewBuffer(jsonBody), header, nil) if httpErr != nil { - return errors.Wrapf(httpErr, "HTTP %q request to %q failed with error", httpMethod, configUpdateURL) + return fmt.Errorf("HTTP %q request to %q failed with error: %w", httpMethod, configUpdateURL, httpErr) } if configUpdateResp != nil && configUpdateResp.Body != nil { @@ -67,7 +66,7 @@ func runIntegrationArtifactUpdateConfiguration(config *integrationArtifactUpdate } if configUpdateResp == nil { - return errors.Errorf("did not retrieve a HTTP response") + return fmt.Errorf("did not retrieve a HTTP response") } if configUpdateResp.StatusCode == http.StatusAccepted { @@ -79,9 +78,9 @@ func runIntegrationArtifactUpdateConfiguration(config *integrationArtifactUpdate response, readErr := io.ReadAll(configUpdateResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", configUpdateResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", configUpdateResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(response), configUpdateResp.StatusCode) - return errors.Errorf("Failed to update the integration flow configuration parameter, Response Status code: %v", configUpdateResp.StatusCode) + return fmt.Errorf("Failed to update the integration flow configuration parameter, Response Status code: %v", configUpdateResp.StatusCode) } diff --git a/cmd/integrationArtifactUpload.go b/cmd/integrationArtifactUpload.go index a4e317028..91aeb0fb9 100644 --- a/cmd/integrationArtifactUpload.go +++ b/cmd/integrationArtifactUpload.go @@ -14,7 +14,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func integrationArtifactUpload(config integrationArtifactUploadOptions, telemetryData *telemetry.CustomData) { @@ -48,7 +47,7 @@ func runIntegrationArtifactUpload(config *integrationArtifactUploadOptions, tele tokenParameters := cpi.TokenParameters{TokenURL: serviceKey.OAuth.OAuthTokenProviderURL, Username: serviceKey.OAuth.ClientID, Password: serviceKey.OAuth.ClientSecret, Client: httpClient} token, err := cpi.CommonUtils.GetBearerToken(tokenParameters) if err != nil { - return errors.Wrap(err, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", err) } clientOptions.Token = fmt.Sprintf("Bearer %s", token) httpClient.SetOptions(clientOptions) @@ -67,18 +66,18 @@ func runIntegrationArtifactUpload(config *integrationArtifactUploadOptions, tele } if iFlowStatusResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if httpErr != nil { responseBody, readErr := io.ReadAll(iFlowStatusResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", iFlowStatusResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", iFlowStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", responseBody, iFlowStatusResp.StatusCode) - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpMethod, iFlowStatusServiceURL, string(responseBody)) + return fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpMethod, iFlowStatusServiceURL, string(responseBody), httpErr) } - return errors.Errorf("Failed to check integration flow availability, Response Status code: %v", iFlowStatusResp.StatusCode) + return fmt.Errorf("Failed to check integration flow availability, Response Status code: %v", iFlowStatusResp.StatusCode) } // UploadIntegrationArtifact - Upload new integration artifact @@ -89,7 +88,7 @@ func UploadIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli header.Add("content-type", "application/json") payload, jsonError := GetJSONPayloadAsByteArray(config, "create", fileUtils) if jsonError != nil { - return errors.Wrapf(jsonError, "Failed to get json payload for file %v, failed with error", config.FilePath) + return fmt.Errorf("Failed to get json payload for file %v, failed with error: %w", config.FilePath, jsonError) } uploadIflowStatusResp, httpErr := httpClient.SendRequest(httpMethod, uploadIflowStatusURL, payload, header, nil) @@ -99,7 +98,7 @@ func UploadIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli } if uploadIflowStatusResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if uploadIflowStatusResp.StatusCode == http.StatusCreated { @@ -111,12 +110,12 @@ func UploadIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli if httpErr != nil { responseBody, readErr := io.ReadAll(uploadIflowStatusResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", uploadIflowStatusResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", uploadIflowStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", responseBody, uploadIflowStatusResp.StatusCode) - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpMethod, uploadIflowStatusURL, string(responseBody)) + return fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpMethod, uploadIflowStatusURL, string(responseBody), httpErr) } - return errors.Errorf("Failed to create Integration Flow artefact, Response Status code: %v", uploadIflowStatusResp.StatusCode) + return fmt.Errorf("Failed to create Integration Flow artefact, Response Status code: %v", uploadIflowStatusResp.StatusCode) } // UpdateIntegrationArtifact - Update existing integration artifact @@ -127,7 +126,7 @@ func UpdateIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli updateIflowStatusURL := fmt.Sprintf("%s/api/v1/IntegrationDesigntimeArtifacts(Id='%s',Version='%s')", apiHost, config.IntegrationFlowID, "Active") payload, jsonError := GetJSONPayloadAsByteArray(config, "update", fileUtils) if jsonError != nil { - return errors.Wrapf(jsonError, "Failed to get json payload for file %v, failed with error", config.FilePath) + return fmt.Errorf("Failed to get json payload for file %v, failed with error: %w", config.FilePath, jsonError) } updateIflowStatusResp, httpErr := httpClient.SendRequest(httpMethod, updateIflowStatusURL, payload, header, nil) @@ -136,7 +135,7 @@ func UpdateIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli } if updateIflowStatusResp == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if updateIflowStatusResp.StatusCode == http.StatusOK { @@ -148,19 +147,19 @@ func UpdateIntegrationArtifact(config *integrationArtifactUploadOptions, httpCli if httpErr != nil { responseBody, readErr := io.ReadAll(updateIflowStatusResp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", updateIflowStatusResp.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", updateIflowStatusResp.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), updateIflowStatusResp.StatusCode) - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpMethod, updateIflowStatusURL, string(responseBody)) + return fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpMethod, updateIflowStatusURL, string(responseBody), httpErr) } - return errors.Errorf("Failed to update Integration Flow artefact, Response Status code: %v", updateIflowStatusResp.StatusCode) + return fmt.Errorf("Failed to update Integration Flow artefact, Response Status code: %v", updateIflowStatusResp.StatusCode) } // GetJSONPayloadAsByteArray -return http payload as byte array func GetJSONPayloadAsByteArray(config *integrationArtifactUploadOptions, mode string, fileUtils piperutils.FileUtils) (*bytes.Buffer, error) { fileContent, readError := fileUtils.FileRead(config.FilePath) if readError != nil { - return nil, errors.Wrapf(readError, "Error reading file") + return nil, fmt.Errorf("Error reading file: %w", readError) } jsonObj := gabs.New() if mode == "create" { @@ -178,7 +177,7 @@ func GetJSONPayloadAsByteArray(config *integrationArtifactUploadOptions, mode st jsonBody, jsonErr := json.Marshal(jsonObj) if jsonErr != nil { - return nil, errors.Wrapf(jsonErr, "json payload is invalid for integration flow artifact %q", config.IntegrationFlowID) + return nil, fmt.Errorf("json payload is invalid for integration flow artifact %q: %w", config.IntegrationFlowID, jsonErr) } return bytes.NewBuffer(jsonBody), nil } diff --git a/cmd/jsonApplyPatch_test.go b/cmd/jsonApplyPatch_test.go index 4f219309f..f97d59589 100644 --- a/cmd/jsonApplyPatch_test.go +++ b/cmd/jsonApplyPatch_test.go @@ -4,9 +4,10 @@ package cmd import ( + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/stretchr/testify/assert" - "testing" ) var schema = []byte(` diff --git a/cmd/kanikoExecute.go b/cmd/kanikoExecute.go index af7495b2d..367959e45 100644 --- a/cmd/kanikoExecute.go +++ b/cmd/kanikoExecute.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/build" "github.com/SAP/jenkins-library/pkg/buildsettings" @@ -69,14 +68,14 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus if len(config.ContainerPreparationCommand) > 0 { prepCommand := strings.Split(config.ContainerPreparationCommand, " ") if err := execRunner.RunExecutable(prepCommand[0], prepCommand[1:]...); err != nil { - return errors.Wrap(err, "failed to initialize Kaniko container") + return fmt.Errorf("failed to initialize Kaniko container: %w", err) } } if len(config.CustomTLSCertificateLinks) > 0 { err := certutils.CertificateUpdate(config.CustomTLSCertificateLinks, httpClient, fileUtils, "/kaniko/ssl/certs/ca-certificates.crt") if err != nil { - return errors.Wrap(err, "failed to update certificates") + return fmt.Errorf("failed to update certificates: %w", err) } } else { log.Entry().Info("skipping updation of certificates") @@ -89,7 +88,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus var err error dockerConfig, err = fileUtils.FileRead(config.DockerConfigJSON) if err != nil { - return errors.Wrapf(err, "failed to read existing docker config json at '%v'", config.DockerConfigJSON) + return fmt.Errorf("failed to read existing docker config json at '%v': %w", config.DockerConfigJSON, err) } } @@ -98,27 +97,27 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus if len(config.DockerConfigJSON) > 0 && len(config.ContainerRegistryURL) > 0 && len(config.ContainerRegistryPassword) > 0 && len(config.ContainerRegistryUser) > 0 { targetConfigJson, err := docker.CreateDockerConfigJSON(config.ContainerRegistryURL, config.ContainerRegistryUser, config.ContainerRegistryPassword, "", config.DockerConfigJSON, fileUtils) if err != nil { - return errors.Wrapf(err, "failed to update existing docker config json file '%v'", config.DockerConfigJSON) + return fmt.Errorf("failed to update existing docker config json file '%v': %w", config.DockerConfigJSON, err) } dockerConfig, err = fileUtils.FileRead(targetConfigJson) if err != nil { - return errors.Wrapf(err, "failed to read enhanced file '%v'", config.DockerConfigJSON) + return fmt.Errorf("failed to read enhanced file '%v': %w", config.DockerConfigJSON, err) } } else if len(config.DockerConfigJSON) == 0 && len(config.ContainerRegistryURL) > 0 && len(config.ContainerRegistryPassword) > 0 && len(config.ContainerRegistryUser) > 0 { targetConfigJson, err := docker.CreateDockerConfigJSON(config.ContainerRegistryURL, config.ContainerRegistryUser, config.ContainerRegistryPassword, "", "/kaniko/.docker/config.json", fileUtils) if err != nil { - return errors.Wrap(err, "failed to create new docker config json at /kaniko/.docker/config.json") + return fmt.Errorf("failed to create new docker config json at /kaniko/.docker/config.json: %w", err) } dockerConfig, err = fileUtils.FileRead(targetConfigJson) if err != nil { - return errors.Wrapf(err, "failed to read new docker config file at /kaniko/.docker/config.json") + return fmt.Errorf("failed to read new docker config file at /kaniko/.docker/config.json: %w", err) } } if err := fileUtils.FileWrite("/kaniko/.docker/config.json", dockerConfig, 0644); err != nil { - return errors.Wrap(err, "failed to write file '/kaniko/.docker/config.json'") + return fmt.Errorf("failed to write file '/kaniko/.docker/config.json': %w", err) } log.Entry().Debugf("preparing build settings information...") @@ -158,7 +157,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerRegistry, err := docker.ContainerRegistryFromURL(config.ContainerRegistryURL) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to read registry url %v", config.ContainerRegistryURL) + return fmt.Errorf("failed to read registry url %v: %w", config.ContainerRegistryURL, err) } commonPipelineEnvironment.container.registryURL = config.ContainerRegistryURL @@ -212,7 +211,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus parsedMultipleImages, err := parseMultipleImages(config.MultipleImages) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "failed to parse multipleImages param") + return fmt.Errorf("failed to parse multipleImages param: %w", err) } for _, entry := range parsedMultipleImages { @@ -223,7 +222,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerRegistry, err := docker.ContainerRegistryFromURL(config.ContainerRegistryURL) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "multipleImages: failed to read registry url %v", config.ContainerRegistryURL) + return fmt.Errorf("multipleImages: failed to read registry url %v: %w", config.ContainerRegistryURL, err) } if entry.ContainerImageTag == "" { @@ -259,12 +258,12 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerImageName, err := docker.ContainerImageNameFromImage(entry.ContainerImage) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "invalid name part in image %v", entry.ContainerImage) + return fmt.Errorf("invalid name part in image %v: %w", entry.ContainerImage, err) } containerImageNameTag, err := docker.ContainerImageNameTagFromImage(entry.ContainerImage) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "invalid tag part in image %v", entry.ContainerImage) + return fmt.Errorf("invalid tag part in image %v: %w", entry.ContainerImage, err) } log.Entry().Debugf("multipleImages: image build '%v'", containerImageName) @@ -324,7 +323,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerRegistry, err := docker.ContainerRegistryFromImage(destination) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "invalid registry part in image %v", destination) + return fmt.Errorf("invalid registry part in image %v: %w", destination, err) } if commonPipelineEnvironment.container.registryURL == "" { commonPipelineEnvironment.container.registryURL = fmt.Sprintf("https://%v", containerRegistry) @@ -348,7 +347,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerRegistry, err := docker.ContainerRegistryFromURL(config.ContainerRegistryURL) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to read registry url %v", config.ContainerRegistryURL) + return fmt.Errorf("failed to read registry url %v: %w", config.ContainerRegistryURL, err) } // Docker image tags don't allow plus signs in tags, thus replacing with dash @@ -367,7 +366,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus containerRegistry, err := docker.ContainerRegistryFromImage(config.ContainerImage) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "invalid registry part in image %v", config.ContainerImage) + return fmt.Errorf("invalid registry part in image %v: %w", config.ContainerImage, err) } // errors are already caught with previous call to docker.ContainerRegistryFromImage @@ -439,13 +438,13 @@ func runKaniko(config *kanikoExecuteOptions, dockerFilepath string, buildOptions err = execRunner.RunExecutable("/kaniko/executor", kanikoOpts...) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrap(err, "execution of '/kaniko/executor' failed") + return fmt.Errorf("execution of '/kaniko/executor' failed: %w", err) } if b, err := fileUtils.FileExists(digestFilePath); err == nil && b { digest, err := fileUtils.FileRead(digestFilePath) if err != nil { - return errors.Wrap(err, "error while reading image digest") + return fmt.Errorf("error while reading image digest: %w", err) } digestStr := string(digest) diff --git a/cmd/kubernetesDeploy.go b/cmd/kubernetesDeploy.go index 57ee06a28..0641ed05e 100644 --- a/cmd/kubernetesDeploy.go +++ b/cmd/kubernetesDeploy.go @@ -18,7 +18,7 @@ import ( "github.com/SAP/jenkins-library/pkg/kubernetes" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" + "helm.sh/helm/v3/pkg/cli/values" ) @@ -81,7 +81,7 @@ func runHelmDeploy(config kubernetesDeployOptions, utils kubernetes.DeployUtils, helmValues, err := defineDeploymentValues(config, containerRegistry) if err != nil { - return errors.Wrap(err, "failed to process deployment values") + return fmt.Errorf("failed to process deployment values: %w", err) } helmLogFields := map[string]interface{}{} @@ -169,7 +169,7 @@ func runHelmDeploy(config kubernetesDeployOptions, utils kubernetes.DeployUtils, err = helmValues.mapValues() if err != nil { - return errors.Wrap(err, "failed to map values using 'valuesMapping' configuration") + return fmt.Errorf("failed to map values using 'valuesMapping' configuration: %w", err) } upgradeParams = append( @@ -341,11 +341,11 @@ func runKubectlDeploy(config kubernetesDeployOptions, utils kubernetes.DeployUti values, err := defineDeploymentValues(config, containerRegistry) if err != nil { - return errors.Wrap(err, "failed to process deployment values") + return fmt.Errorf("failed to process deployment values: %w", err) } err = values.mapValues() if err != nil { - return errors.Wrap(err, "failed to map values using 'valuesMapping' configuration") + return fmt.Errorf("failed to map values using 'valuesMapping' configuration: %w", err) } re := regexp.MustCompile(`image:[ ]*`) @@ -364,16 +364,16 @@ func runKubectlDeploy(config kubernetesDeployOptions, utils kubernetes.DeployUti buf := bytes.NewBufferString("") tpl, err := template.New("appTemplate").Parse(string(appTemplate)) if err != nil { - return errors.Wrap(err, "failed to parse app-template file") + return fmt.Errorf("failed to parse app-template file: %w", err) } err = tpl.Execute(buf, values.asHelmValues()) if err != nil { - return errors.Wrap(err, "failed to render app-template file") + return fmt.Errorf("failed to render app-template file: %w", err) } err = utils.FileWrite(config.AppTemplate, buf.Bytes(), 0700) if err != nil { - return errors.Wrapf(err, "Error when updating appTemplate '%v'", config.AppTemplate) + return fmt.Errorf("Error when updating appTemplate '%v': %w", config.AppTemplate, err) } kubeParams = append(kubeParams, config.DeployCommand, "--filename", config.AppTemplate) diff --git a/cmd/malwareExecuteScan.go b/cmd/malwareExecuteScan.go index ec76c921f..b5d4a19bc 100644 --- a/cmd/malwareExecuteScan.go +++ b/cmd/malwareExecuteScan.go @@ -15,7 +15,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/toolrecord" - "github.com/pkg/errors" ) type malwareScanUtils interface { @@ -163,7 +162,7 @@ func selectAndPrepareFileForMalwareScan(config *malwareExecuteScanOptions, utils if strings.Contains(fmt.Sprint(err), "no image found") { log.SetErrorCategory(log.ErrorConfiguration) } - return "", errors.Wrapf(err, "failed to download Docker image %v", config.ScanImage) + return "", fmt.Errorf("failed to download Docker image %v: %w", config.ScanImage, err) } return tarFile, nil } diff --git a/cmd/mavenBuild.go b/cmd/mavenBuild.go index ad3c04b81..14f75c452 100644 --- a/cmd/mavenBuild.go +++ b/cmd/mavenBuild.go @@ -2,6 +2,7 @@ package cmd import ( "encoding/json" + "fmt" "os" "path" "path/filepath" @@ -16,7 +17,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/versioning" - "github.com/pkg/errors" piperhttp "github.com/SAP/jenkins-library/pkg/http" ) @@ -148,13 +148,13 @@ func runMavenBuild(config *mavenBuildOptions, _ *telemetry.CustomData, utils mav _, err := maven.Execute(&mavenOptions, utils) if err != nil { - return errors.Wrapf(err, "failed to execute maven build for goal(s) '%v'", goals) + return fmt.Errorf("failed to execute maven build for goal(s) '%v': %w", goals, err) } if config.CreateBOM { // Separate run for makeBOM goal if err := runMakeBOMGoal(config, utils); err != nil { - return errors.Wrap(err, "failed to execute makeBOM goal") + return fmt.Errorf("failed to execute makeBOM goal: %w", err) } } @@ -187,7 +187,7 @@ func runMavenBuild(config *mavenBuildOptions, _ *telemetry.CustomData, utils mav if (len(config.AltDeploymentRepositoryID) > 0) && (len(config.AltDeploymentRepositoryPassword) > 0) && (len(config.AltDeploymentRepositoryUser) > 0) { projectSettingsFilePath, err := createOrUpdateProjectSettingsXML(config.ProjectSettingsFile, config.AltDeploymentRepositoryID, config.AltDeploymentRepositoryUser, config.AltDeploymentRepositoryPassword, utils) if err != nil { - return errors.Wrap(err, "Could not create or update project settings xml") + return fmt.Errorf("Could not create or update project settings xml: %w", err) } mavenOptions.ProjectSettingsFile = projectSettingsFilePath } @@ -280,13 +280,13 @@ func createOrUpdateProjectSettingsXML(projectSettingsFile string, altDeploymentR if len(projectSettingsFile) > 0 { projectSettingsFilePath, err := maven.UpdateProjectSettingsXML(projectSettingsFile, altDeploymentRepositoryID, altDeploymentRepositoryUser, altDeploymentRepositoryPassword, utils) if err != nil { - return "", errors.Wrap(err, "Could not update settings xml") + return "", fmt.Errorf("Could not update settings xml: %w", err) } return projectSettingsFilePath, nil } else { projectSettingsFilePath, err := maven.CreateNewProjectSettingsXML(altDeploymentRepositoryID, altDeploymentRepositoryUser, altDeploymentRepositoryPassword, utils) if err != nil { - return "", errors.Wrap(err, "Could not create settings xml") + return "", fmt.Errorf("Could not create settings xml: %w", err) } return projectSettingsFilePath, nil } @@ -302,11 +302,11 @@ func loadRemoteRepoCertificates(certificateList []string, client piperhttp.Downl exists, err := fileUtils.FileExists(existingJavaCaCerts) if err != nil { - return errors.Wrap(err, "Could not find the existing java cacerts") + return fmt.Errorf("Could not find the existing java cacerts: %w", err) } if !exists { - return errors.Wrap(err, "Could not find the existing java cacerts") + return fmt.Errorf("Could not find the existing java cacerts: %w", err) } trustStore := filepath.Join(".pipeline", "mavenCaCerts") @@ -315,11 +315,11 @@ func loadRemoteRepoCertificates(certificateList []string, client piperhttp.Downl _, fileUtilserr := fileUtils.Copy(existingJavaCaCerts, trustStore) if fileUtilserr != nil { - return errors.Wrap(err, "Could not copy existing cacerts into new cacerts location ") + return fmt.Errorf("Could not copy existing cacerts into new cacerts location : %w", err) } if err := fileUtils.Chmod(trustStore, 0666); err != nil { - return errors.Wrap(err, "unable to provide correct permission to trust store") + return fmt.Errorf("unable to provide correct permission to trust store: %w", err) } log.Entry().Infof("using trust store %s", trustStore) @@ -328,7 +328,7 @@ func loadRemoteRepoCertificates(certificateList []string, client piperhttp.Downl maven_opts := "-Djavax.net.ssl.trustStore=.pipeline/mavenCaCerts -Djavax.net.ssl.trustStorePassword=changeit" err := os.Setenv("MAVEN_OPTS", maven_opts) if err != nil { - return errors.Wrap(err, "Could not create MAVEN_OPTS environment variable ") + return fmt.Errorf("Could not create MAVEN_OPTS environment variable : %w", err) } log.Entry().WithField("trust store", trustStore).Info("Using local trust store") } @@ -350,13 +350,13 @@ func loadRemoteRepoCertificates(certificateList []string, client piperhttp.Downl log.Entry().WithField("source", certificate).WithField("target", target).Info("Downloading TLS certificate") // download certificate if err := client.DownloadFile(certificate, target, nil, nil); err != nil { - return errors.Wrapf(err, "Download of TLS certificate failed") + return fmt.Errorf("Download of TLS certificate failed: %w", err) } options := append(keytoolOptions, "-file", target) options = append(options, "-alias", filename) // add certificate to keystore if err := runner.RunExecutable("keytool", options...); err != nil { - return errors.Wrap(err, "Adding certificate to keystore failed") + return fmt.Errorf("Adding certificate to keystore failed: %w", err) } } log.Entry().Infof("custom tls certificates successfully added to the trust store %s", trustStore) diff --git a/cmd/mavenExecute_test.go b/cmd/mavenExecute_test.go index 2f8b8f596..5c906ed19 100644 --- a/cmd/mavenExecute_test.go +++ b/cmd/mavenExecute_test.go @@ -5,10 +5,11 @@ package cmd import ( "errors" - "github.com/SAP/jenkins-library/pkg/mock" - "github.com/stretchr/testify/assert" "net/http" "testing" + + "github.com/SAP/jenkins-library/pkg/mock" + "github.com/stretchr/testify/assert" ) type mavenMockUtils struct { diff --git a/cmd/mtaBuild.go b/cmd/mtaBuild.go index 181fe0c14..6924d4e6f 100644 --- a/cmd/mtaBuild.go +++ b/cmd/mtaBuild.go @@ -20,6 +20,8 @@ import ( "github.com/SAP/jenkins-library/pkg/npm" "github.com/SAP/jenkins-library/pkg/versioning" + "errors" + "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" @@ -27,7 +29,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/ghodss/yaml" - "github.com/pkg/errors" ) const templateMtaYml = `_schema-version: "3.1" @@ -304,12 +305,12 @@ func handlePublish(config mtaBuildOptions, commonPipelineEnvironment *mtaBuildCo mtarPath := getMtarFilePath(config, mtarName) data, err := utils.Open(mtarPath) if err != nil { - return errors.Wrap(err, "failed to open mtar archive for upload") + return fmt.Errorf("failed to open mtar archive for upload: %w", err) } defer data.Close() if _, httpErr := utils.SendRequest("PUT", config.MtaDeploymentRepositoryURL, data, headers, nil); httpErr != nil { - return errors.Wrap(httpErr, "failed to upload mtar to repository") + return fmt.Errorf("failed to upload mtar to repository: %w", httpErr) } if config.CreateBuildArtifactsMetadata { diff --git a/cmd/newmanExecute.go b/cmd/newmanExecute.go index db1be0311..542c0fe2d 100644 --- a/cmd/newmanExecute.go +++ b/cmd/newmanExecute.go @@ -12,7 +12,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type newmanExecuteUtils interface { @@ -68,7 +67,7 @@ func runNewmanExecute(config *newmanExecuteOptions, utils newmanExecuteUtils) er collectionList, err := utils.Glob(config.NewmanCollection) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "Could not execute global search for '%v'", config.NewmanCollection) + return fmt.Errorf("Could not execute global search for '%v': %w", config.NewmanCollection, err) } if collectionList == nil { @@ -108,7 +107,7 @@ func runNewmanExecute(config *newmanExecuteOptions, utils newmanExecuteUtils) er newmanPath := filepath.Join(utils.Getenv("HOME"), "/.npm-global/bin/newman") err = utils.RunExecutable(newmanPath, runOptions...) if err != nil { - return errors.Wrap(err, "The execution of the newman tests failed, see the log for details.") + return fmt.Errorf("The execution of the newman tests failed, see the log for details.: %w", err) } } return nil @@ -118,12 +117,12 @@ func logVersions(utils newmanExecuteUtils) error { err := utils.RunExecutable("node", "--version") if err != nil { log.SetErrorCategory(log.ErrorInfrastructure) - return errors.Wrap(err, "error logging node version") + return fmt.Errorf("error logging node version: %w", err) } err = utils.RunExecutable("npm", "--version") if err != nil { log.SetErrorCategory(log.ErrorInfrastructure) - return errors.Wrap(err, "error logging npm version") + return fmt.Errorf("error logging npm version: %w", err) } return nil } @@ -134,7 +133,7 @@ func installNewman(newmanInstallCommand string, utils newmanExecuteUtils) error err := utils.RunExecutable(installCommandTokens[0], installCommandTokens[1:]...) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrap(err, "error installing newman") + return fmt.Errorf("error installing newman: %w", err) } return nil } @@ -170,7 +169,7 @@ func resolveTemplate(config *newmanExecuteOptions, collection string) ([]string, }).Parse(runOption) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return nil, errors.Wrap(err, "could not parse newman command template") + return nil, fmt.Errorf("could not parse newman command template: %w", err) } buf := new(bytes.Buffer) err = templ.Execute(buf, TemplateConfig{ @@ -180,7 +179,7 @@ func resolveTemplate(config *newmanExecuteOptions, collection string) ([]string, }) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return nil, errors.Wrap(err, "error on executing template") + return nil, fmt.Errorf("error on executing template: %w", err) } cmd = append(cmd, buf.String()) } diff --git a/cmd/newmanExecute_test.go b/cmd/newmanExecute_test.go index ffb742988..c5ec728e1 100644 --- a/cmd/newmanExecute_test.go +++ b/cmd/newmanExecute_test.go @@ -10,8 +10,9 @@ import ( "strings" "testing" + "errors" + "github.com/google/uuid" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/nexusUpload.go b/cmd/nexusUpload.go index 16930b9ff..dcc29158a 100644 --- a/cmd/nexusUpload.go +++ b/cmd/nexusUpload.go @@ -8,8 +8,9 @@ import ( "path/filepath" "strings" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/pkg/errors" b64 "encoding/base64" diff --git a/cmd/npmExecuteLint_test.go b/cmd/npmExecuteLint_test.go index 0ccd988b1..37b96288e 100644 --- a/cmd/npmExecuteLint_test.go +++ b/cmd/npmExecuteLint_test.go @@ -5,12 +5,13 @@ package cmd import ( "errors" + "path/filepath" + "testing" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/npm" "github.com/stretchr/testify/assert" - "path/filepath" - "testing" ) type mockLintUtilsBundle struct { diff --git a/cmd/pipelineCreateScanSummary.go b/cmd/pipelineCreateScanSummary.go index 13adfb582..f0b373321 100644 --- a/cmd/pipelineCreateScanSummary.go +++ b/cmd/pipelineCreateScanSummary.go @@ -9,7 +9,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) type pipelineCreateScanSummaryUtils interface { @@ -49,11 +48,11 @@ func runPipelineCreateScanSummary(config *pipelineCreateScanSummaryOptions, tele reportContent, err := utils.FileRead(report) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to read report %v", report) + return fmt.Errorf("failed to read report %v: %w", report, err) } scanReport := reporting.ScanReport{} if err = json.Unmarshal(reportContent, &scanReport); err != nil { - return errors.Wrapf(err, "failed to parse report %v", report) + return fmt.Errorf("failed to parse report %v: %w", report, err) } scanReports = append(scanReports, scanReport) } @@ -71,7 +70,7 @@ func runPipelineCreateScanSummary(config *pipelineCreateScanSummaryOptions, tele if err := utils.FileWrite(config.OutputFilePath, output, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "failed to write %v", config.OutputFilePath) + return fmt.Errorf("failed to write %v: %w", config.OutputFilePath, err) } return nil diff --git a/cmd/piper.go b/cmd/piper.go index bdfff13a0..017a00cef 100644 --- a/cmd/piper.go +++ b/cmd/piper.go @@ -14,7 +14,7 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" + "github.com/spf13/cobra" ) @@ -401,7 +401,7 @@ func PrepareConfig(cmd *cobra.Command, metadata *config.StepData, stepName strin if exists, err := piperutils.FileExists(projectConfigFile); exists { log.Entry().Debugf("Project config: '%s'", projectConfigFile) if customConfig, err = openFile(projectConfigFile, GeneralConfig.GitHubAccessTokens); err != nil { - return errors.Wrapf(err, "Cannot read '%s'", projectConfigFile) + return fmt.Errorf("Cannot read '%s': %w", projectConfigFile, err) } } else { log.Entry().Infof("Project config: NONE ('%s' does not exist)", projectConfigFile) @@ -418,7 +418,7 @@ func PrepareConfig(cmd *cobra.Command, metadata *config.StepData, stepName strin if err != nil { if projectDefaultFile != ".pipeline/defaults.yaml" { log.Entry().Debugf("Project defaults: '%s'", projectDefaultFile) - return errors.Wrapf(err, "Cannot read '%s'", projectDefaultFile) + return fmt.Errorf("Cannot read '%s': %w", projectDefaultFile, err) } } else { log.Entry().Debugf("Project defaults: '%s'", projectDefaultFile) @@ -433,7 +433,7 @@ func PrepareConfig(cmd *cobra.Command, metadata *config.StepData, stepName strin log.Entry().Warnf("invalid value for parameter verbose: '%v'", stepConfig.Config["verbose"]) } if err != nil { - return errors.Wrap(err, "retrieving step configuration failed") + return fmt.Errorf("retrieving step configuration failed: %w", err) } } diff --git a/cmd/piper_test.go b/cmd/piper_test.go index da711144e..0083e3ec2 100644 --- a/cmd/piper_test.go +++ b/cmd/piper_test.go @@ -7,12 +7,13 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/SAP/jenkins-library/pkg/orchestrator" "os" "path/filepath" "strings" "testing" + "github.com/SAP/jenkins-library/pkg/orchestrator" + "github.com/ghodss/yaml" "github.com/spf13/cobra" flag "github.com/spf13/pflag" diff --git a/cmd/protecodeExecuteScan.go b/cmd/protecodeExecuteScan.go index d8c2e24bb..4030dbbf8 100644 --- a/cmd/protecodeExecuteScan.go +++ b/cmd/protecodeExecuteScan.go @@ -12,8 +12,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/docker" piperDocker "github.com/SAP/jenkins-library/pkg/docker" @@ -85,7 +83,7 @@ func runProtecodeScan(config *protecodeExecuteScanOptions, influx *protecodeExec log.Entry().Debugf("Get docker image: %v, %v, %v", config.ScanImage, config.DockerRegistryURL, config.FilePath) fileName, filePath, err = getDockerImage(utils, config, cachePath) if err != nil { - return errors.Wrap(err, "failed to get Docker image") + return fmt.Errorf("failed to get Docker image: %w", err) } if len(config.FilePath) <= 0 { (*config).FilePath = filePath @@ -143,7 +141,7 @@ func getDockerImage(utils protecodeUtils, config *protecodeExecuteScanOptions, c } if _, err = utils.DownloadImage(config.ScanImage, tarFilePath); err != nil { - return "", "", errors.Wrap(err, "failed to download docker image") + return "", "", fmt.Errorf("failed to download docker image: %w", err) } return filepath.Base(tarFilePath), filepath.Dir(tarFilePath), nil @@ -385,7 +383,7 @@ func correctDockerConfigEnvVar(config *protecodeExecuteScanOptions, utils protec } if err != nil { - return errors.Wrap(err, "failed to create / update docker config json file") + return fmt.Errorf("failed to create / update docker config json file: %w", err) } if len(path) > 0 { diff --git a/cmd/shellExecute.go b/cmd/shellExecute.go index 3497f5ae3..26d03461b 100644 --- a/cmd/shellExecute.go +++ b/cmd/shellExecute.go @@ -5,8 +5,6 @@ import ( "os/exec" "strings" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" @@ -58,7 +56,7 @@ func runShellExecute(config *shellExecuteOptions, telemetryData *telemetry.Custo if strings.Contains(source, "https") { scriptLocation, err := piperhttp.DownloadExecutable(config.GithubToken, utils, utils, scriptPath) if err != nil { - return errors.Wrap(err, "script download error") + return fmt.Errorf("script download error: %w", err) } scriptPath = scriptLocation } @@ -91,13 +89,13 @@ func runShellExecute(config *shellExecuteOptions, telemetryData *telemetry.Custo // success return nil case 1: - return errors.Wrap(err, "an error occurred while executing the script") + return fmt.Errorf("an error occurred while executing the script: %w", err) default: // exit code 2 or >2 - unstable - return errors.Wrap(err, "script execution unstable or something went wrong") + return fmt.Errorf("script execution unstable or something went wrong: %w", err) } } else if err != nil { - return errors.Wrap(err, "script execution error occurred") + return fmt.Errorf("script execution error occurred: %w", err) } } diff --git a/cmd/sonarExecuteScan.go b/cmd/sonarExecuteScan.go index c198fbe1b..afc84c7b0 100644 --- a/cmd/sonarExecuteScan.go +++ b/cmd/sonarExecuteScan.go @@ -12,8 +12,9 @@ import ( "strings" "time" + "errors" + "github.com/bmatcuk/doublestar" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" @@ -392,19 +393,19 @@ func loadSonarScanner(url string, client piperhttp.Downloader) error { defer os.RemoveAll(tmpFolder) // clean up archive := filepath.Join(tmpFolder, path.Base(url)) if err := client.DownloadFile(url, archive, nil, nil); err != nil { - return errors.Wrap(err, "Download of sonar-scanner failed") + return fmt.Errorf("Download of sonar-scanner failed: %w", err) } // unzip sonar-scanner-cli log.Entry().WithField("source", archive).WithField("target", tmpFolder).Debug("Extracting sonar-scanner") if _, err := fileUtilsUnzip(archive, tmpFolder); err != nil { - return errors.Wrap(err, "Extraction of sonar-scanner failed") + return fmt.Errorf("Extraction of sonar-scanner failed: %w", err) } // move sonar-scanner-cli to .sonar-scanner/ toolPath := ".sonar-scanner" foldername := strings.ReplaceAll(strings.ReplaceAll(archive, ".zip", ""), "cli-", "") log.Entry().WithField("source", foldername).WithField("target", toolPath).Debug("Moving sonar-scanner") if err := osRename(foldername, toolPath); err != nil { - return errors.Wrap(err, "Moving of sonar-scanner failed") + return fmt.Errorf("Moving of sonar-scanner failed: %w", err) } // update binary path sonar.binary = filepath.Join(getWorkingDir(), toolPath, "bin", sonar.binary) @@ -442,7 +443,7 @@ func loadCertificates(certificateList []string, client piperhttp.Downloader, run defaultTruststorePath := keytool.GetDefaultTruststorePath() if exists, _ := fileUtilsExists(defaultTruststorePath); exists { if err := keytool.ImportTruststore(runner, truststoreFile, defaultTruststorePath); err != nil { - return errors.Wrap(err, "Copying existing keystore failed") + return fmt.Errorf("Copying existing keystore failed: %w", err) } } // use local created trust store with downloaded certificates @@ -451,7 +452,7 @@ func loadCertificates(certificateList []string, client piperhttp.Downloader, run log.Entry().WithField("source", certificate).WithField("target", target).Info("Downloading TLS certificate") // download certificate if err := client.DownloadFile(certificate, target, nil, nil); err != nil { - return errors.Wrap(err, "Download of TLS certificate failed") + return fmt.Errorf("Download of TLS certificate failed: %w", err) } // add certificate to keystore if err := keytool.ImportCert(runner, truststoreFile, target); err != nil { diff --git a/cmd/sonarExecuteScan_test.go b/cmd/sonarExecuteScan_test.go index 8327b6134..5eb54f797 100644 --- a/cmd/sonarExecuteScan_test.go +++ b/cmd/sonarExecuteScan_test.go @@ -12,9 +12,10 @@ import ( "path/filepath" "testing" + "errors" + "github.com/bmatcuk/doublestar" "github.com/jarcoal/httpmock" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/cmd/terraformExecute_test.go b/cmd/terraformExecute_test.go index 36ba23e16..c6da15b7e 100644 --- a/cmd/terraformExecute_test.go +++ b/cmd/terraformExecute_test.go @@ -5,9 +5,10 @@ package cmd import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/stretchr/testify/assert" - "testing" ) type terraformExecuteMockUtils struct { diff --git a/cmd/tmsExport_test.go b/cmd/tmsExport_test.go index 2c64aa90f..c81ecc9d1 100644 --- a/cmd/tmsExport_test.go +++ b/cmd/tmsExport_test.go @@ -7,9 +7,10 @@ import ( "strconv" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/tms" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/tmsUpload_test.go b/cmd/tmsUpload_test.go index 40a1c0f63..e521b4314 100644 --- a/cmd/tmsUpload_test.go +++ b/cmd/tmsUpload_test.go @@ -10,9 +10,10 @@ import ( "strconv" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/tms" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/transportRequestDocIDFromGit_test.go b/cmd/transportRequestDocIDFromGit_test.go index c6c59498e..fc8a1bb37 100644 --- a/cmd/transportRequestDocIDFromGit_test.go +++ b/cmd/transportRequestDocIDFromGit_test.go @@ -5,8 +5,9 @@ package cmd import ( "errors" - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestTrGitGetChangeDocumentID(t *testing.T) { diff --git a/cmd/transportRequestReqIDFromGit_test.go b/cmd/transportRequestReqIDFromGit_test.go index 93d32d667..922b3d151 100644 --- a/cmd/transportRequestReqIDFromGit_test.go +++ b/cmd/transportRequestReqIDFromGit_test.go @@ -6,9 +6,10 @@ package cmd import ( "errors" "fmt" - "github.com/stretchr/testify/assert" "strings" "testing" + + "github.com/stretchr/testify/assert" ) type transportRequestUtilsMock struct { diff --git a/cmd/transportRequestUploadCTS_test.go b/cmd/transportRequestUploadCTS_test.go index 6c4fe87c0..d935af95e 100644 --- a/cmd/transportRequestUploadCTS_test.go +++ b/cmd/transportRequestUploadCTS_test.go @@ -5,11 +5,12 @@ package cmd import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/mock" transportrequest "github.com/SAP/jenkins-library/pkg/transportrequest/cts" "github.com/stretchr/testify/assert" - "testing" ) type UploadActionMock struct { diff --git a/cmd/transportRequestUploadRFC_test.go b/cmd/transportRequestUploadRFC_test.go index 4cb6a5cb0..4cb94d359 100644 --- a/cmd/transportRequestUploadRFC_test.go +++ b/cmd/transportRequestUploadRFC_test.go @@ -5,10 +5,11 @@ package cmd import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/transportrequest/rfc" "github.com/stretchr/testify/assert" - "testing" ) type transportRequestUploadRFCMockUtils struct { diff --git a/cmd/transportRequestUploadSOLMAN_test.go b/cmd/transportRequestUploadSOLMAN_test.go index 5fc02c9ed..196bb272e 100644 --- a/cmd/transportRequestUploadSOLMAN_test.go +++ b/cmd/transportRequestUploadSOLMAN_test.go @@ -5,10 +5,11 @@ package cmd import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/transportrequest/solman" "github.com/stretchr/testify/assert" - "testing" ) type transportRequestUploadSOLMANMockUtils struct { diff --git a/cmd/uiVeri5ExecuteTests.go b/cmd/uiVeri5ExecuteTests.go index be9bbc92c..43bbd070c 100644 --- a/cmd/uiVeri5ExecuteTests.go +++ b/cmd/uiVeri5ExecuteTests.go @@ -1,13 +1,13 @@ package cmd import ( + "fmt" "os" "strings" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) func uiVeri5ExecuteTests(config uiVeri5ExecuteTestsOptions, telemetryData *telemetry.CustomData) { @@ -36,16 +36,16 @@ func runUIVeri5(config *uiVeri5ExecuteTestsOptions, command command.ExecRunner) installCommandTokens := strings.Split(config.InstallCommand, " ") if err := command.RunExecutable(installCommandTokens[0], installCommandTokens[1:]...); err != nil { log.SetErrorCategory(log.ErrorCustom) - return errors.Wrapf(err, "failed to execute install command: %v", config.InstallCommand) + return fmt.Errorf("failed to execute install command: %v: %w", config.InstallCommand, err) } if config.TestOptions != "" { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("parameter testOptions no longer supported, please use runOptions parameter instead.") + return fmt.Errorf("parameter testOptions no longer supported, please use runOptions parameter instead.") } if err := command.RunExecutable(config.RunCommand, config.RunOptions...); err != nil { log.SetErrorCategory(log.ErrorTest) - return errors.Wrapf(err, "failed to execute run command: %v %v", config.RunCommand, strings.Join(config.RunOptions, " ")) + return fmt.Errorf("failed to execute run command: %v %v: %w", config.RunCommand, strings.Join(config.RunOptions, " "), err) } return nil } diff --git a/cmd/uiVeri5ExecuteTests_test.go b/cmd/uiVeri5ExecuteTests_test.go index dbef5a290..1026f8c7d 100644 --- a/cmd/uiVeri5ExecuteTests_test.go +++ b/cmd/uiVeri5ExecuteTests_test.go @@ -6,8 +6,9 @@ package cmd import ( "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/cmd/whitesourceExecuteScan.go b/cmd/whitesourceExecuteScan.go index a4ca98b00..14ae58077 100644 --- a/cmd/whitesourceExecuteScan.go +++ b/cmd/whitesourceExecuteScan.go @@ -16,6 +16,8 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" ws "github.com/SAP/jenkins-library/pkg/whitesource" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/format" "github.com/SAP/jenkins-library/pkg/golang" @@ -26,7 +28,6 @@ import ( "github.com/SAP/jenkins-library/pkg/telemetry" "github.com/SAP/jenkins-library/pkg/toolrecord" "github.com/SAP/jenkins-library/pkg/versioning" - "github.com/pkg/errors" "github.com/xuri/excelize/v2" "github.com/google/go-github/v68/github" @@ -220,14 +221,14 @@ func runWhitesourceExecuteScan(ctx context.Context, config *ScanOptions, scan *w } if err := resolveAggregateProjectName(config, scan, sys); err != nil { - return errors.Wrapf(err, "failed to resolve and aggregate project name") + return fmt.Errorf("failed to resolve and aggregate project name: %w", err) } if err := resolveProjectIdentifiers(config, scan, utils, sys); err != nil { if strings.Contains(fmt.Sprint(err), "User is not allowed to perform this action") { log.SetErrorCategory(log.ErrorConfiguration) } - return errors.Wrapf(err, "failed to resolve project identifiers") + return fmt.Errorf("failed to resolve project identifiers: %w", err) } if config.AggregateVersionWideReport { @@ -236,14 +237,14 @@ func runWhitesourceExecuteScan(ctx context.Context, config *ScanOptions, scan *w // For example, if a module was removed from the source code, the project may still // exist in the WhiteSource system. if err := aggregateVersionWideLibraries(config, utils, sys); err != nil { - return errors.Wrapf(err, "failed to aggregate version wide libraries") + return fmt.Errorf("failed to aggregate version wide libraries: %w", err) } if err := aggregateVersionWideVulnerabilities(config, utils, sys); err != nil { - return errors.Wrapf(err, "failed to aggregate version wide vulnerabilities") + return fmt.Errorf("failed to aggregate version wide vulnerabilities: %w", err) } } else { if err := runWhitesourceScan(ctx, config, scan, utils, sys, commonPipelineEnvironment, influx); err != nil { - return errors.Wrapf(err, "failed to execute WhiteSource scan") + return fmt.Errorf("failed to execute WhiteSource scan: %w", err) } } return nil @@ -259,28 +260,28 @@ func runWhitesourceScan(ctx context.Context, config *ScanOptions, scan *ws.Scan, config.ScanImage = image err := downloadMultipleDockerImageAsTar(config, utils) if err != nil { - return errors.Wrapf(err, "failed to download docker image") + return fmt.Errorf("failed to download docker image: %w", err) } } } else { err := downloadDockerImageAsTar(config, utils) if err != nil { - return errors.Wrapf(err, "failed to download docker image") + return fmt.Errorf("failed to download docker image: %w", err) } } } // Start the scan if err := executeScan(config, scan, utils); err != nil { - return errors.Wrapf(err, "failed to execute Scan") + return fmt.Errorf("failed to execute Scan: %w", err) } // ToDo: Check this: // Why is this required at all, resolveProjectIdentifiers() is already called before the scan in runWhitesourceExecuteScan() // Could perhaps use scan.updateProjects(sys) directly... have not investigated what could break if err := resolveProjectIdentifiers(config, scan, utils, sys); err != nil { - return errors.Wrapf(err, "failed to resolve project identifiers") + return fmt.Errorf("failed to resolve project identifiers: %w", err) } log.Entry().Info("-----------------------------------------------------") @@ -295,7 +296,7 @@ func runWhitesourceScan(ctx context.Context, config *ScanOptions, scan *ws.Scan, piperutils.PersistReportsAndLinks("whitesourceExecuteScan", "", utils, paths, nil) persistScannedProjects(config, scan, commonPipelineEnvironment) if err != nil { - return errors.Wrapf(err, "failed to check and report scan results") + return fmt.Errorf("failed to check and report scan results: %w", err) } return nil } @@ -401,7 +402,7 @@ func resolveProjectIdentifiers(config *ScanOptions, scan *ws.Scan, utils whiteso } coordinates, err := utils.GetArtifactCoordinates(config.BuildTool, config.BuildDescriptorFile, options) if err != nil { - return errors.Wrap(err, "failed to get build artifact description") + return fmt.Errorf("failed to get build artifact description: %w", err) } scan.Coordinates = coordinates @@ -424,12 +425,12 @@ func resolveProjectIdentifiers(config *ScanOptions, scan *ws.Scan, utils whiteso scan.ProductVersion = validateProductVersion(config.Version) if err := resolveProductToken(config, sys); err != nil { - return errors.Wrap(err, "error resolving product token") + return fmt.Errorf("error resolving product token: %w", err) } if !config.SkipParentProjectResolution { if err := resolveAggregateProjectToken(config, sys); err != nil { - return errors.Wrap(err, "error resolving aggregate project token") + return fmt.Errorf("error resolving aggregate project token: %w", err) } } @@ -453,11 +454,11 @@ func resolveProductToken(config *ScanOptions, sys whitesource) error { product = ws.Product{} product.Token, err = createWhiteSourceProduct(config, sys) if err != nil { - return errors.Wrapf(err, "failed to create whitesource product") + return fmt.Errorf("failed to create whitesource product: %w", err) } } if err != nil { - return errors.Wrapf(err, "failed to get product by name") + return fmt.Errorf("failed to get product by name: %w", err) } log.Entry().Infof("Resolved product token: '%s'..", product.Token) config.ProductToken = product.Token @@ -475,7 +476,7 @@ func resolveAggregateProjectName(config *ScanOptions, scan *ws.Scan, sys whiteso // If the user configured the "projectToken" parameter, we expect this project to exist in the backend. project, err := sys.GetProjectByToken(config.ProjectToken) if err != nil { - return errors.Wrapf(err, "failed to get project by token") + return fmt.Errorf("failed to get project by token: %w", err) } nameVersion := strings.Split(project.Name, " - ") scan.AggregateProjectName = nameVersion[0] @@ -494,7 +495,7 @@ func resolveAggregateProjectToken(config *ScanOptions, sys whitesource) error { fullProjName := fmt.Sprintf("%s - %s", config.ProjectName, config.Version) projectToken, err := sys.GetProjectToken(config.ProductToken, fullProjName) if err != nil { - return errors.Wrapf(err, "failed to get project token") + return fmt.Errorf("failed to get project token: %w", err) } // A project may not yet exist for this project name-version combo. // It will be created by the scan, we retrieve the token again after scanning. @@ -562,13 +563,13 @@ func executeScan(config *ScanOptions, scan *ws.Scan, utils whitesourceUtils) err installCommandTokens := strings.Split(config.InstallCommand, " ") if err := utils.RunExecutable(installCommandTokens[0], installCommandTokens[1:]...); err != nil { log.SetErrorCategory(log.ErrorCustom) - return errors.Wrapf(err, "failed to execute install command: %v", config.InstallCommand) + return fmt.Errorf("failed to execute install command: %v: %w", config.InstallCommand, err) } } // Execute scan with Unified Agent jar file if err := scan.ExecuteUAScan(options, utils); err != nil { - return errors.Wrapf(err, "failed to execute Unified Agent scan") + return fmt.Errorf("failed to execute Unified Agent scan: %w", err) } return nil } @@ -631,11 +632,11 @@ func checkPolicyViolations(ctx context.Context, config *ScanOptions, scan *ws.Sc if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0o777) if err != nil { - return policyReport, errors.Wrap(err, "failed to create reporting directory") + return policyReport, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("whitesourceExecuteScan_ip_%v.json", ws.ReportSha(config.ProductName, scan))), jsonReport, 0o666); err != nil { - return policyReport, errors.Wrap(err, "failed to write json report") + return policyReport, fmt.Errorf("failed to write json report: %w", err) } // we do not add the json report to the overall list of reports for now, // since it is just an intermediary report used as input for later @@ -929,7 +930,7 @@ func aggregateVersionWideLibraries(config *ScanOptions, utils whitesourceUtils, projects, err := sys.GetProjectsMetaInfo(config.ProductToken) if err != nil { - return errors.Wrapf(err, "failed to get projects meta info") + return fmt.Errorf("failed to get projects meta info: %w", err) } versionWideLibraries := map[string][]ws.Library{} // maps project name to slice of libraries @@ -939,14 +940,14 @@ func aggregateVersionWideLibraries(config *ScanOptions, utils whitesourceUtils, if projectVersion == config.Version { libs, err := sys.GetProjectLibraryLocations(project.Token) if err != nil { - return errors.Wrapf(err, "failed to get project library locations") + return fmt.Errorf("failed to get project library locations: %w", err) } log.Entry().Infof("Found project: %s with %v libraries.", project.Name, len(libs)) versionWideLibraries[projectName] = libs } } if err := newLibraryCSVReport(versionWideLibraries, config, utils); err != nil { - return errors.Wrapf(err, "failed toget new libary CSV report") + return fmt.Errorf("failed toget new libary CSV report: %w", err) } return nil } @@ -956,7 +957,7 @@ func aggregateVersionWideVulnerabilities(config *ScanOptions, utils whitesourceU projects, err := sys.GetProjectsMetaInfo(config.ProductToken) if err != nil { - return errors.Wrapf(err, "failed to get projects meta info") + return fmt.Errorf("failed to get projects meta info: %w", err) } var versionWideAlerts []ws.Alert // all alerts for a given project version @@ -967,7 +968,7 @@ func aggregateVersionWideVulnerabilities(config *ScanOptions, utils whitesourceU projectNames += project.Name + "\n" alerts, err := sys.GetProjectAlertsByType(project.Token, "SECURITY_VULNERABILITY") if err != nil { - return errors.Wrapf(err, "failed to get project alerts by type") + return fmt.Errorf("failed to get project alerts by type: %w", err) } log.Entry().Infof("Found project: %s with %v vulnerabilities.", project.Name, len(alerts)) @@ -977,10 +978,10 @@ func aggregateVersionWideVulnerabilities(config *ScanOptions, utils whitesourceU reportPath := filepath.Join(ws.ReportsDirectory, "project-names-aggregated.txt") if err := utils.FileWrite(reportPath, []byte(projectNames), 0o666); err != nil { - return errors.Wrapf(err, "failed to write report: %s", reportPath) + return fmt.Errorf("failed to write report: %s: %w", reportPath, err) } if err := newVulnerabilityExcelReport(versionWideAlerts, config, utils); err != nil { - return errors.Wrapf(err, "failed to create new vulnerability excel report") + return fmt.Errorf("failed to create new vulnerability excel report: %w", err) } return nil } @@ -1071,14 +1072,14 @@ func newLibraryCSVReport(libraries map[string][]ws.Library, config *ScanOptions, // Ensure reporting directory exists if err := utils.MkdirAll(ws.ReportsDirectory, 0o777); err != nil { - return errors.Wrapf(err, "failed to create directories: %s", ws.ReportsDirectory) + return fmt.Errorf("failed to create directories: %s: %w", ws.ReportsDirectory, err) } // Write result to file fileName := fmt.Sprintf("%s/libraries-%s.csv", ws.ReportsDirectory, utils.Now().Format(wsReportTimeStampLayout)) if err := utils.FileWrite(fileName, []byte(output), 0o666); err != nil { - return errors.Wrapf(err, "failed to write file: %s", fileName) + return fmt.Errorf("failed to write file: %s: %w", fileName, err) } filePath := piperutils.Path{Name: "aggregated-libraries", Target: fileName} piperutils.PersistReportsAndLinks("whitesourceExecuteScan", "", utils, []piperutils.Path{filePath}, nil) @@ -1169,11 +1170,11 @@ func downloadMultipleDockerImageAsTar(config *ScanOptions, utils whitesourceUtil if strings.Contains(fmt.Sprint(err), "no image found") { log.SetErrorCategory(log.ErrorConfiguration) } - return errors.Wrapf(err, "failed to download Docker image %v", config.ScanImage) + return fmt.Errorf("failed to download Docker image %v: %w", config.ScanImage, err) } // remove contents after : in the image name if err := renameTarfilePath(tarFilePath); err != nil { - return errors.Wrapf(err, "failed to rename image %v", err) + return fmt.Errorf("failed to rename image %v: %w", err, err) } return nil @@ -1197,7 +1198,7 @@ func downloadDockerImageAsTar(config *ScanOptions, utils whitesourceUtils) error if strings.Contains(fmt.Sprint(err), "no image found") { log.SetErrorCategory(log.ErrorConfiguration) } - return errors.Wrapf(err, "failed to download Docker image %v", config.ScanImage) + return fmt.Errorf("failed to download Docker image %v: %w", config.ScanImage, err) } return nil diff --git a/cmd/whitesourceExecuteScan_test.go b/cmd/whitesourceExecuteScan_test.go index b485a1baf..92c1ba4dc 100644 --- a/cmd/whitesourceExecuteScan_test.go +++ b/cmd/whitesourceExecuteScan_test.go @@ -7,13 +7,14 @@ import ( "testing" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/format" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" "github.com/SAP/jenkins-library/pkg/versioning" ws "github.com/SAP/jenkins-library/pkg/whitesource" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/google/go-github/v68/github" diff --git a/cmd/xsDeploy.go b/cmd/xsDeploy.go index 924737ea4..38d04cfdc 100644 --- a/cmd/xsDeploy.go +++ b/cmd/xsDeploy.go @@ -11,11 +11,12 @@ import ( "sync" "text/template" + "errors" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" ) // DeployMode ... @@ -40,7 +41,7 @@ func ValueOfMode(str string) (DeployMode, error) { case "BG_DEPLOY": return BGDeploy, nil default: - return NoDeploy, errors.New(fmt.Sprintf("Unknown DeployMode: '%s'", str)) + return NoDeploy, fmt.Errorf("Unknown DeployMode: '%s'", str) } } @@ -80,7 +81,7 @@ func ValueOfAction(str string) (Action, error) { return Retry, nil default: - return None, errors.New(fmt.Sprintf("Unknown Action: '%s'", str)) + return None, fmt.Errorf("Unknown Action: '%s'", str) } } @@ -126,7 +127,7 @@ func runXsDeploy(XsDeployOptions xsDeployOptions, piperEnvironment *xsDeployComm mode, err := ValueOfMode(XsDeployOptions.Mode) if err != nil { - return errors.Wrapf(err, "Extracting mode failed: '%s'", XsDeployOptions.Mode) + return fmt.Errorf("Extracting mode failed: '%s': %w", XsDeployOptions.Mode, err) } if mode == NoDeploy { @@ -136,11 +137,11 @@ func runXsDeploy(XsDeployOptions xsDeployOptions, piperEnvironment *xsDeployComm action, err := ValueOfAction(XsDeployOptions.Action) if err != nil { - return errors.Wrapf(err, "Extracting action failed: '%s'", XsDeployOptions.Action) + return fmt.Errorf("Extracting action failed: '%s': %w", XsDeployOptions.Action, err) } if mode == Deploy && action != None { - return errors.New(fmt.Sprintf("Cannot perform action '%s' in mode '%s'. Only action '%s' is allowed.", action, mode, None)) + return fmt.Errorf("Cannot perform action '%s' in mode '%s'. Only action '%s' is allowed.", action, mode, None) } log.Entry().Debugf("Mode: '%s', Action: '%s'", mode, action) @@ -155,12 +156,12 @@ func runXsDeploy(XsDeployOptions xsDeployOptions, piperEnvironment *xsDeployComm return e } if action == None && !exists { - return errors.New(fmt.Sprintf("Deployable '%s' does not exist", XsDeployOptions.MtaPath)) + return fmt.Errorf("Deployable '%s' does not exist", XsDeployOptions.MtaPath) } } if action != None && len(XsDeployOptions.OperationID) == 0 { - return errors.New(fmt.Sprintf("OperationID was not provided. This is required for action '%s'.", action)) + return fmt.Errorf("OperationID was not provided. This is required for action '%s'.", action) } prOut, pwOut := io.Pipe() @@ -449,7 +450,7 @@ func copyFileFromHomeToPwd(xsSessionFile string, fileUtils piperutils.FileUtils) src, dest := fmt.Sprintf("%s/%s", os.Getenv("HOME"), xsSessionFile), xsSessionFile log.Entry().Debugf("Copying xs session file from home directory ('%s') to workspace ('%s')", src, dest) if _, err := fileUtils.Copy(src, dest); err != nil { - return errors.Wrapf(err, "Cannot copy xssession file from home directory ('%s') to workspace ('%s')", src, dest) + return fmt.Errorf("Cannot copy xssession file from home directory ('%s') to workspace ('%s'): %w", src, dest, err) } log.Entry().Debugf("xs session file copied from home directory ('%s') to workspace ('%s')", src, dest) return nil @@ -467,7 +468,7 @@ func copyFileFromPwdToHome(xsSessionFile string, fileUtils piperutils.FileUtils) src, dest := xsSessionFile, fmt.Sprintf("%s/%s", os.Getenv("HOME"), xsSessionFile) log.Entry().Debugf("Copying xs session file from workspace ('%s') to home directory ('%s')", src, dest) if _, err := fileUtils.Copy(src, dest); err != nil { - return errors.Wrapf(err, "Cannot copy xssession file from workspace ('%s') to home directory ('%s')", src, dest) + return fmt.Errorf("Cannot copy xssession file from workspace ('%s') to home directory ('%s'): %w", src, dest, err) } log.Entry().Debugf("xs session file copied from workspace ('%s') to home directory ('%s')", src, dest) return nil @@ -479,7 +480,7 @@ func (a Action) GetAction() (string, error) { case Resume, Abort, Retry: return strings.ToLower(a.String()), nil } - return "", errors.New(fmt.Sprintf("Invalid deploy mode: '%s'.", a)) + return "", fmt.Errorf("Invalid deploy mode: '%s'.", a) } @@ -492,5 +493,5 @@ func (m DeployMode) GetDeployCommand() (string, error) { case BGDeploy: return "bg-deploy", nil } - return "", errors.New(fmt.Sprintf("Invalid deploy mode: '%s'.", m)) + return "", fmt.Errorf("Invalid deploy mode: '%s'.", m) } diff --git a/documentation/DEVELOPMENT.md b/documentation/DEVELOPMENT.md index 2eefc6dc9..d41db54c6 100644 --- a/documentation/DEVELOPMENT.md +++ b/documentation/DEVELOPMENT.md @@ -214,12 +214,12 @@ In order to better understand the root cause of errors that occur, we wrap error ```golang f, err := os.Open(path) if err != nil { - return errors.Wrapf(err, "open failed for %v", path) + return fmt.Errorf("open failed for %v: %w", path, err) } defer f.Close() ``` -We use [github.com/pkg/errors](https://github.com/pkg/errors) for that. +We use standard library fmt.Error for that. It has proven a good practice to bubble up errors until the runtime entry function and only there exit via the logging framework (see also [logging](#logging)). @@ -581,7 +581,7 @@ void call(Map piperParams) { // e.g. only this singele step of the stage somePiperStep( script: piperParams.script, someConfigParameter: '<...>' ) } - + echo "End - Extension for stage: ${piperParams.stageName}" } return this diff --git a/go.mod b/go.mod index 065ef257e..86e7a535f 100644 --- a/go.mod +++ b/go.mod @@ -49,7 +49,6 @@ require ( github.com/motemen/go-nuts v0.0.0-20220604134737-2658d0104f31 github.com/package-url/packageurl-go v0.1.1 github.com/piper-validation/fortify-client-go v0.0.0-20220126145513-7b3e9a72af01 - github.com/pkg/errors v0.9.1 github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.9.1 @@ -125,6 +124,7 @@ require ( github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/oapi-codegen/runtime v1.0.0 // indirect github.com/pjbgf/sha1cd v0.3.0 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect diff --git a/integration/docker_test_executor.go b/integration/docker_test_executor.go index 09a371520..d68ed3ed5 100644 --- a/integration/docker_test_executor.go +++ b/integration/docker_test_executor.go @@ -18,8 +18,9 @@ import ( "testing" "time" + "errors" + "github.com/magiconair/properties/assert" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" @@ -190,9 +191,9 @@ func (d *IntegrationTestDockerExecRunner) whenRunningPiperCommand(command string if err != nil { stdOut, outputErr := d.getPiperOutput() if outputErr != nil { - return errors.Wrap(outputErr, "unable to get output after Piper command failure") + return fmt.Errorf("unable to get output after Piper command failure: %w", outputErr) } - return errors.Wrapf(err, "piper output: \n%s", stdOut.String()) + return fmt.Errorf("piper output: \n%s: %w", stdOut.String(), err) } return err } diff --git a/pkg/abap/aakaas/aakUtils_mock.go b/pkg/abap/aakaas/aakUtils_mock.go index 5e4de0a8f..f9e4c990b 100644 --- a/pkg/abap/aakaas/aakUtils_mock.go +++ b/pkg/abap/aakaas/aakUtils_mock.go @@ -6,11 +6,12 @@ package aakaas import ( "time" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) type AakBundleMock struct { diff --git a/pkg/abap/aakaas/componentVersion.go b/pkg/abap/aakaas/componentVersion.go index 4d8dc6df9..3d3343cca 100644 --- a/pkg/abap/aakaas/componentVersion.go +++ b/pkg/abap/aakaas/componentVersion.go @@ -2,12 +2,12 @@ package aakaas import ( "encoding/json" + "fmt" "net/url" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const cvQueryURL string = "/odata/aas_ocs_package/xSSDAxC_Component_Version" @@ -49,7 +49,7 @@ func (c *ComponentVersion) Validate() error { } var response jsonComponentVersionValidationResponse if err := json.Unmarshal(body, &response); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for Validate Component Version: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for Validate Component Version: "+string(body), err) } c.Name = response.Wrapper.Name c.TechRelease = response.Wrapper.TechRelease diff --git a/pkg/abap/aakaas/componentVersion_test.go b/pkg/abap/aakaas/componentVersion_test.go index cd08f0eef..e20e30420 100644 --- a/pkg/abap/aakaas/componentVersion_test.go +++ b/pkg/abap/aakaas/componentVersion_test.go @@ -6,9 +6,10 @@ package aakaas import ( "testing" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/pkg/abap/aakaas/package.go b/pkg/abap/aakaas/package.go index 75a244f3e..c0dff2fab 100644 --- a/pkg/abap/aakaas/package.go +++ b/pkg/abap/aakaas/package.go @@ -2,12 +2,14 @@ package aakaas import ( "encoding/json" + "fmt" "net/url" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) // PackageStatus : Status of an ABAP delivery package @@ -85,7 +87,7 @@ func (p *Package) ReserveNext() error { } var jPck jsonPackageDeterminePackageForScv if err := json.Unmarshal(body, &jPck); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for reserve package: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for reserve package: "+string(body), err) } p.PackageName = jPck.DeterminePackage.Package.PackageName p.Type = jPck.DeterminePackage.Package.Type @@ -111,7 +113,7 @@ func (p *Package) GetPackageAndNamespace() error { var jPck jsonPackage if err := json.Unmarshal(body, &jPck); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for check of package status: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for check of package status: "+string(body), err) } p.Status = jPck.Package.Status @@ -140,7 +142,7 @@ func (p *Package) Register() error { var jPck jsonPackage if err := json.Unmarshal(body, &jPck); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for register package: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for register package: "+string(body), err) } p.Status = jPck.Package.Status log.Entry().Infof("Package status %s", p.Status) @@ -160,7 +162,7 @@ func (p *Package) Release() error { } var jPck jsonPackage if err := json.Unmarshal(body, &jPck); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for release package: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for release package: "+string(body), err) } p.Status = jPck.Package.Status return nil diff --git a/pkg/abap/aakaas/productVersion.go b/pkg/abap/aakaas/productVersion.go index 8f5c58504..487bdc106 100644 --- a/pkg/abap/aakaas/productVersion.go +++ b/pkg/abap/aakaas/productVersion.go @@ -2,12 +2,12 @@ package aakaas import ( "encoding/json" + "fmt" "net/url" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const pvQueryURL string = "/odata/aas_ocs_package/xSSDAxC_Product_Version" @@ -48,7 +48,7 @@ func (p *ProductVersion) ValidateAndResolveVersionFields() error { } var response jsonProductVersionValidationResponse if err := json.Unmarshal(body, &response); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for Validate Product Version: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for Validate Product Version: "+string(body), err) } p.Name = response.Wrapper.Name p.TechRelease = response.Wrapper.TechRelease diff --git a/pkg/abap/aakaas/productVersionHeader.go b/pkg/abap/aakaas/productVersionHeader.go index 444e04ad3..b1612c248 100644 --- a/pkg/abap/aakaas/productVersionHeader.go +++ b/pkg/abap/aakaas/productVersionHeader.go @@ -2,10 +2,12 @@ package aakaas import ( "encoding/json" + "fmt" + + "errors" abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" ) type jsonProductVersionHeader struct { @@ -85,12 +87,12 @@ func (pv *ProductVersionHeader) CheckAndResolveVersion(conn *abapbuild.Connector appendum := "/odata/aas_ocs_package/ProductVersionHeaderSet" responseBody, err := conn.Post(appendum, string(requestJson)) if err != nil { - return errors.Wrap(err, "Checking Product Modeling in AAkaaS failed") + return fmt.Errorf("Checking Product Modeling in AAkaaS failed: %w", err) } var resultPv jsonProductVersionHeader if err := json.Unmarshal(responseBody, &resultPv); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for checking Product Modeling "+string(responseBody)) + return fmt.Errorf("Unexpected AAKaaS response for checking Product Modeling "+string(responseBody), err) } pv.ProductVersion = resultPv.Pvh.ProductVersion diff --git a/pkg/abap/aakaas/productVersion_test.go b/pkg/abap/aakaas/productVersion_test.go index 1b4d73991..d460d309c 100644 --- a/pkg/abap/aakaas/productVersion_test.go +++ b/pkg/abap/aakaas/productVersion_test.go @@ -6,9 +6,10 @@ package aakaas import ( "testing" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/pkg/abap/aakaas/targetVector.go b/pkg/abap/aakaas/targetVector.go index 6043d29fd..ee4b0db19 100644 --- a/pkg/abap/aakaas/targetVector.go +++ b/pkg/abap/aakaas/targetVector.go @@ -2,13 +2,15 @@ package aakaas import ( "encoding/json" + "fmt" "net/http" "net/url" "time" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/abaputils" - "github.com/pkg/errors" ) // TargetVectorStatus : Status of TargetVector in AAKaaS @@ -97,16 +99,16 @@ func (tv *TargetVector) CreateTargetVector(conn *abapbuild.Connector) error { conn.GetToken("/odata/aas_ocs_package") tvJSON, err := json.Marshal(tv) if err != nil { - return errors.Wrap(err, "Generating Request Data for Create Target Vector failed") + return fmt.Errorf("Generating Request Data for Create Target Vector failed: %w", err) } appendum := "/odata/aas_ocs_package/TargetVectorSet" body, err := conn.Post(appendum, string(tvJSON)) if err != nil { - return errors.Wrap(err, "Creating Target Vector in AAKaaS failed") + return fmt.Errorf("Creating Target Vector in AAKaaS failed: %w", err) } var jTV jsonTargetVector if err := json.Unmarshal(body, &jTV); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for create target vector: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for create target vector: "+string(body), err) } tv.ID = jTV.Tv.ID tv.Status = jTV.Tv.Status @@ -118,12 +120,12 @@ func (tv *TargetVector) PublishTargetVector(conn *abapbuild.Connector, targetVec appendum := "/odata/aas_ocs_package/PublishTargetVector?Id='" + url.QueryEscape(tv.ID) + "'&Scope='" + url.QueryEscape(string(targetVectorScope)) + "'" body, err := conn.Post(appendum, "") if err != nil { - return errors.Wrap(err, "Publish Target Vector in AAKaaS failed") + return fmt.Errorf("Publish Target Vector in AAKaaS failed: %w", err) } var jTV jsonTargetVector if err := json.Unmarshal(body, &jTV); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for publish target vector: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for publish target vector: "+string(body), err) } tv.Status = jTV.Tv.Status @@ -139,12 +141,12 @@ func (tv *TargetVector) GetTargetVector(conn *abapbuild.Connector) error { appendum := "/odata/aas_ocs_package/TargetVectorSet('" + url.QueryEscape(tv.ID) + "')" body, err := conn.Get(appendum) if err != nil { - return errors.Wrap(err, "Getting Target Vector details from AAKaaS failed") + return fmt.Errorf("Getting Target Vector details from AAKaaS failed: %w", err) } var jTV jsonTargetVector if err := json.Unmarshal(body, &jTV); err != nil { - return errors.Wrap(err, "Unexpected AAKaaS response for getting target vector details: "+string(body)) + return fmt.Errorf("Unexpected AAKaaS response for getting target vector details: "+string(body), err) } tv.Status = jTV.Tv.Status @@ -168,7 +170,7 @@ func (tv *TargetVector) PollForStatus(conn *abapbuild.Connector, targetStatus Ta } case <-ticker: if err := tv.GetTargetVector(conn); err != nil { - return errors.Wrap(err, "Getting TargetVector status during polling resulted in an error") + return fmt.Errorf("Getting TargetVector status during polling resulted in an error: %w", err) } switch TargetVectorStatus(tv.PublishStatus) { case TargetVectorPublishStatusRunning: diff --git a/pkg/abap/aakaas/versionables.go b/pkg/abap/aakaas/versionables.go index 45f5ca5ec..97c77b464 100644 --- a/pkg/abap/aakaas/versionables.go +++ b/pkg/abap/aakaas/versionables.go @@ -7,9 +7,10 @@ import ( "strconv" "strings" + "errors" + abapbuild "github.com/SAP/jenkins-library/pkg/abap/build" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const wildCardNext string = "NEXT" @@ -177,7 +178,7 @@ func (v *versionable) queryVersion(filter string, orderBy string) (*versionable, } else { Versions := versionables{} if err := json.Unmarshal(body, &Versions); err != nil { - return &result, errors.Wrap(err, "Unexpected AAKaaS response for Component Version Query: "+string(body)) + return &result, fmt.Errorf("Unexpected AAKaaS response for Component Version Query: "+string(body), err) } switch len(Versions.Wrapper.Vs) { case 0: diff --git a/pkg/abap/build/bfw.go b/pkg/abap/build/bfw.go index b1d19ba62..9b3a8f804 100644 --- a/pkg/abap/build/bfw.go +++ b/pkg/abap/build/bfw.go @@ -11,9 +11,10 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) // RunState : Current Status of the Build @@ -174,17 +175,17 @@ func (b *Build) Start(phase string, inputValues Values) error { } importBody, err := json.Marshal(inputForPost) if err != nil { - return errors.Wrap(err, "Generating Post Request Body failed") + return fmt.Errorf("Generating Post Request Body failed: %w", err) } body, err := b.Connector.Post("/builds", string(importBody)) if err != nil { - return errors.Wrap(err, "Start of build failed: "+string(body)) + return fmt.Errorf("Start of build failed: "+string(body), err) } var jBuild jsonBuild if err := json.Unmarshal(body, &jBuild); err != nil { - return errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } b.BuildID = jBuild.Build.BuildID b.RunState = jBuild.Build.RunState @@ -204,7 +205,7 @@ func (b *Build) Poll() error { for { select { case <-timeout: - return errors.Errorf("Timed out: (max Runtime %v reached)", b.Connector.MaxRuntime) + return fmt.Errorf("Timed out: (max Runtime %v reached)", b.Connector.MaxRuntime) case <-ticker: b.Get() if !b.IsFinished() { @@ -219,13 +220,13 @@ func (b *Build) Poll() error { // EvaluteIfBuildSuccessful : Checks the finale state of the build framework func (b *Build) EvaluteIfBuildSuccessful(treatWarningsAsError bool) error { if b.RunState == Failed { - return errors.Errorf("Build ended with runState failed") + return fmt.Errorf("Build ended with runState failed") } if treatWarningsAsError && b.ResultState == Warning { - return errors.Errorf("Build ended with ResultState warning, setting to failed as configured") + return fmt.Errorf("Build ended with ResultState warning, setting to failed as configured") } if (b.ResultState == Aborted) || (b.ResultState == Erroneous) { - return errors.Errorf("Build ended with ResultState %s", b.ResultState) + return fmt.Errorf("Build ended with ResultState %s", b.ResultState) } return nil } @@ -239,7 +240,7 @@ func (b *Build) Get() error { } var jBuild jsonBuild if err := json.Unmarshal(body, &jBuild); err != nil { - return errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } b.RunState = jBuild.Build.RunState b.ResultState = jBuild.Build.ResultState @@ -279,7 +280,7 @@ func (b *Build) GetValues() error { } var jValues jsonValues if err := json.Unmarshal(body, &jValues); err != nil { - return errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } b.Values = jValues.ResultValues.Values for i := range b.Values { @@ -407,7 +408,7 @@ func (t *task) getLogs() error { } var jLogs jsonLogs if err := json.Unmarshal(body, &jLogs); err != nil { - return errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } t.Logs = jLogs.ResultLogs.Logs } @@ -423,7 +424,7 @@ func (t *task) getResults() error { } var jResults jsonResults if err := json.Unmarshal(body, &jResults); err != nil { - return errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } t.Results = jResults.ResultResults.Results for i := range t.Results { @@ -447,7 +448,7 @@ func (b *Build) DownloadAllResults(basePath string, filenamePrefix string) error if b.Tasks[i_task].Results[0].Name != dummyResultName { for i_result := range b.Tasks[i_task].Results { if err := b.Tasks[i_task].Results[i_result].DownloadWithFilenamePrefixAndTargetDirectory(basePath, filenamePrefix); err != nil { - return errors.Wrapf(err, "Error during the download of file %s", b.Tasks[i_task].Results[i_result].Name) + return fmt.Errorf("Error during the download of file %s: %w", b.Tasks[i_task].Results[i_result].Name, err) } } } @@ -461,10 +462,10 @@ func (b *Build) DownloadResults(filenames []string, basePath string, filenamePre result, err := b.GetResult(name) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "Problems finding the file %s, please check your config whether this file is really a result file", name) + return fmt.Errorf("Problems finding the file %s, please check your config whether this file is really a result file: %w", name, err) } if err := result.DownloadWithFilenamePrefixAndTargetDirectory(basePath, filenamePrefix); err != nil { - return errors.Wrapf(err, "Error during the download of file %s", name) + return fmt.Errorf("Error during the download of file %s: %w", name, err) } } return nil @@ -495,13 +496,13 @@ func (b *Build) PublishDownloadedResults(stepname string, filenames []string, ut result, err := b.GetResult(filenames[i]) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Wrapf(err, "Problems finding the file %s, please check your config whether this file is really a result file", filenames[i]) + return fmt.Errorf("Problems finding the file %s, please check your config whether this file is really a result file: %w", filenames[i], err) } if result.wasDownloaded() { filesToPublish = append(filesToPublish, piperutils.Path{Target: result.DownloadPath, Name: result.SavedFilename, Mandatory: true}) } else { log.SetErrorCategory(log.ErrorConfiguration) - return errors.Errorf("Trying to publish the file %s which was not downloaded", result.Name) + return fmt.Errorf("Trying to publish the file %s which was not downloaded", result.Name) } } if len(filesToPublish) > 0 { @@ -523,18 +524,18 @@ func (result *Result) Download(downloadPath string) error { func (result *Result) DownloadWithFilenamePrefixAndTargetDirectory(basePath string, filenamePrefix string) error { basePath, err := result.resolveParamter(basePath) if err != nil { - return errors.Wrapf(err, "Could not resolve parameter %s for the target directory", basePath) + return fmt.Errorf("Could not resolve parameter %s for the target directory: %w", basePath, err) } filenamePrefix, err = result.resolveParamter(filenamePrefix) if err != nil { - return errors.Wrapf(err, "Could not resolve parameter %s for the filename prefix", filenamePrefix) + return fmt.Errorf("Could not resolve parameter %s for the filename prefix: %w", filenamePrefix, err) } appendum := fmt.Sprint("/results(build_id='", result.BuildID, "',task_id=", result.TaskID, ",name='", result.Name, "')/$value") filename := filenamePrefix + result.Name downloadPath := filepath.Join(path.Base(basePath), path.Base(filename)) if err := result.connector.Download(appendum, downloadPath); err != nil { log.SetErrorCategory(log.ErrorInfrastructure) - return errors.Wrapf(err, "Could not download %s", result.Name) + return fmt.Errorf("Could not download %s: %w", result.Name, err) } result.SavedFilename = filename result.DownloadPath = downloadPath @@ -555,7 +556,7 @@ func (result *Result) resolveParamter(parameter string) (string, error) { return strconv.Itoa(result.TaskID), nil default: log.SetErrorCategory(log.ErrorConfiguration) - return "", errors.Errorf("Unknown parameter %s", parameter) + return "", fmt.Errorf("Unknown parameter %s", parameter) } } else { return parameter, nil @@ -591,7 +592,7 @@ func unmarshalTasks(body []byte, connector Connector) ([]task, error) { var append_task task var jTasks jsonTasks if err := json.Unmarshal(body, &jTasks); err != nil { - return tasks, errors.Wrap(err, "Unexpected buildFrameWork response: "+string(body)) + return tasks, fmt.Errorf("Unexpected buildFrameWork response: "+string(body), err) } for _, jTask := range jTasks.ResultTasks.Tasks { append_task.connector = connector diff --git a/pkg/abap/build/connector.go b/pkg/abap/build/connector.go index bcd7fc4f7..e6998a1cd 100644 --- a/pkg/abap/build/connector.go +++ b/pkg/abap/build/connector.go @@ -6,6 +6,7 @@ import ( "crypto/x509" "encoding/base64" "encoding/pem" + "fmt" "io" "net/http" "net/http/cookiejar" @@ -14,10 +15,11 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/abaputils" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "golang.org/x/crypto/pkcs12" ) @@ -63,11 +65,11 @@ func (conn *Connector) GetToken(appendum string) error { response, err := conn.Client.SendRequest("HEAD", url, nil, conn.Header, nil) if err != nil { if response == nil { - return errors.Wrap(err, "Fetching X-CSRF-Token failed") + return fmt.Errorf("Fetching X-CSRF-Token failed: %w", err) } defer response.Body.Close() errorbody, _ := io.ReadAll(response.Body) - return errors.Wrapf(err, "Fetching X-CSRF-Token failed: %v", extractErrorStackFromJsonData(errorbody)) + return fmt.Errorf("Fetching X-CSRF-Token failed: %v: %w", extractErrorStackFromJsonData(errorbody), err) } defer response.Body.Close() @@ -92,11 +94,11 @@ func (conn Connector) Get(appendum string) ([]byte, error) { response, err := conn.Client.SendRequest("GET", url, nil, conn.Header, nil) if err != nil { if response == nil || response.Body == nil { - return nil, errors.Wrap(err, "Get failed") + return nil, fmt.Errorf("Get failed: %w", err) } defer response.Body.Close() errorbody, _ := io.ReadAll(response.Body) - return errorbody, errors.Wrapf(err, "Get failed: %v", extractErrorStackFromJsonData(errorbody)) + return errorbody, fmt.Errorf("Get failed: %v: %w", extractErrorStackFromJsonData(errorbody), err) } defer response.Body.Close() @@ -116,11 +118,11 @@ func (conn Connector) Post(appendum string, importBody string) ([]byte, error) { } if err != nil { if response == nil { - return nil, errors.Wrap(err, "Post failed") + return nil, fmt.Errorf("Post failed: %w", err) } defer response.Body.Close() errorbody, _ := io.ReadAll(response.Body) - return errorbody, errors.Wrapf(err, "Post failed: %v", extractErrorStackFromJsonData(errorbody)) + return errorbody, fmt.Errorf("Post failed: %v: %w", extractErrorStackFromJsonData(errorbody), err) } defer response.Body.Close() @@ -162,7 +164,7 @@ func (conn *Connector) InitAAKaaS(aAKaaSEndpoint string, username string, passwo tlsCertificates, err := conn.handleLogonCertificate(certFile, certPass) if err != nil { - return errors.Wrap(err, "Handling certificates for client logon failed") + return fmt.Errorf("Handling certificates for client logon failed: %w", err) } conn.Client.SetOptions(piperhttp.ClientOptions{ @@ -189,12 +191,12 @@ func (conn *Connector) handleLogonCertificate(certFile, certPass string) ([]tls. if certFile != "" && certPass != "" { certFileInBytes, err := base64.StdEncoding.DecodeString(certFile) if err != nil { - return nil, errors.Wrap(err, "Base64 decoding of certificate File string failed") + return nil, fmt.Errorf("Base64 decoding of certificate File string failed: %w", err) } pemBlocks, err := pkcs12.ToPEM(certFileInBytes, certPass) if err != nil { - return nil, errors.Wrap(err, "Decoding certificate File from PKCS12 to PEM failed") + return nil, fmt.Errorf("Decoding certificate File from PKCS12 to PEM failed: %w", err) } var key []byte @@ -208,7 +210,7 @@ func (conn *Connector) handleLogonCertificate(certFile, certPass string) ([]tls. if pemBlock.Type == "CERTIFICATE" { var tempCert, err = x509.ParseCertificate(pemBlock.Bytes) if err != nil { - return nil, errors.Wrap(err, "Parsing x509 Certificate from PEM Block failed") + return nil, fmt.Errorf("Parsing x509 Certificate from PEM Block failed: %w", err) } if tempCert.IsCA == false { //We ignore the 2 additional CA Certificates @@ -219,7 +221,7 @@ func (conn *Connector) handleLogonCertificate(certFile, certPass string) ([]tls. tlsCertificate, err = tls.X509KeyPair(userCertificate, key) if err != nil { - return nil, errors.Wrap(err, "Creating x509 Key Pair failed") + return nil, fmt.Errorf("Creating x509 Key Pair failed: %w", err) } return []tls.Certificate{tlsCertificate}, nil @@ -252,7 +254,7 @@ func (conn *Connector) InitBuildFramework(config ConnectorConfiguration, com aba // Determine the host, user and password, either via the input parameters or via a cloud foundry service key connectionDetails, err := com.GetAbapCommunicationArrangementInfo(subOptions, "/sap/opu/odata/BUILD/CORE_SRV") if err != nil { - return errors.Wrap(err, "Parameters for the ABAP Connection not available") + return fmt.Errorf("Parameters for the ABAP Connection not available: %w", err) } conn.DownloadClient.SetOptions(piperhttp.ClientOptions{ @@ -279,7 +281,7 @@ func (conn Connector) UploadSarFile(appendum string, sarFile []byte) error { if err != nil { defer response.Body.Close() errorbody, _ := io.ReadAll(response.Body) - return errors.Wrapf(err, "Upload of SAR file failed: %v", extractErrorStackFromJsonData(errorbody)) + return fmt.Errorf("Upload of SAR file failed: %v: %w", extractErrorStackFromJsonData(errorbody), err) } defer response.Body.Close() return nil @@ -315,7 +317,7 @@ func (conn Connector) UploadSarFileInChunks(appendum string, fileName string, sa if response != nil && response.Body != nil { errorbody, _ := io.ReadAll(response.Body) response.Body.Close() - return errors.Wrapf(err, "Upload of SAR file failed: %v", extractErrorStackFromJsonData(errorbody)) + return fmt.Errorf("Upload of SAR file failed: %v: %w", extractErrorStackFromJsonData(errorbody), err) } else { return err } diff --git a/pkg/abaputils/abaputils.go b/pkg/abaputils/abaputils.go index b2e9f9be9..b8a0d93dc 100644 --- a/pkg/abaputils/abaputils.go +++ b/pkg/abaputils/abaputils.go @@ -12,12 +12,13 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/cloudfoundry" "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/ghodss/yaml" - "github.com/pkg/errors" ) // AbapUtils Struct @@ -45,7 +46,7 @@ func (abaputils *AbapUtils) GetAbapCommunicationArrangementInfo(options AbapEnvi match, err := regexp.MatchString(`^(https|HTTPS):\/\/.*`, options.Host) if err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return connectionDetails, errors.Wrap(err, "Schema validation for host parameter failed. Check for https.") + return connectionDetails, fmt.Errorf("Schema validation for host parameter failed. Check for https.: %w", err) } var hostOdataURL = options.Host + oDataURL if match { @@ -66,7 +67,7 @@ func (abaputils *AbapUtils) GetAbapCommunicationArrangementInfo(options AbapEnvi // Url, User and Password should be read from a cf service key var abapServiceKey, error = ReadServiceKeyAbapEnvironment(options, c) if error != nil { - return connectionDetails, errors.Wrap(error, "Read service key failed") + return connectionDetails, fmt.Errorf("Read service key failed: %w", error) } connectionDetails.Host = abapServiceKey.URL connectionDetails.URL = abapServiceKey.URL + oDataURL @@ -211,8 +212,8 @@ func HandleHTTPError(resp *http.Response, err error, message string, connectionD if parsingError != nil { return "", err } - abapError := errors.New(fmt.Sprintf("%s - %s", errorCode, errorText)) - err = errors.Wrap(abapError, err.Error()) + abapError := fmt.Errorf("%s - %s", errorCode, errorText) + err = fmt.Errorf("%s: %w", err.Error(), abapError) } return errorCode, err diff --git a/pkg/abaputils/abaputils_test.go b/pkg/abaputils/abaputils_test.go index d9b0cafa2..19162fdfc 100644 --- a/pkg/abaputils/abaputils_test.go +++ b/pkg/abaputils/abaputils_test.go @@ -10,9 +10,10 @@ import ( "net/http" "testing" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/mock" - "github.com/pkg/errors" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" ) diff --git a/pkg/abaputils/descriptor.go b/pkg/abaputils/descriptor.go index 1a044d23e..6989a9fac 100644 --- a/pkg/abaputils/descriptor.go +++ b/pkg/abaputils/descriptor.go @@ -7,8 +7,9 @@ import ( "path/filepath" "reflect" + "errors" + "github.com/ghodss/yaml" - "github.com/pkg/errors" ) /* @@ -83,18 +84,18 @@ func ConstructAddonDescriptorFromJSON(JSON []byte) (AddonDescriptor, error) { func readFile(FileName string) ([]byte, error) { fileLocations, err := filepath.Glob(FileName) if err != nil || len(fileLocations) != 1 { - return nil, errors.New(fmt.Sprintf("Could not find %v", FileName)) + return nil, fmt.Errorf("Could not find %v", FileName) } absoluteFilename, err := filepath.Abs(fileLocations[0]) if err != nil { - return nil, errors.New(fmt.Sprintf("Could not get path of %v", FileName)) + return nil, fmt.Errorf("Could not get path of %v", FileName) } var fileContent []byte fileContent, err = os.ReadFile(absoluteFilename) if err != nil { - return nil, errors.New(fmt.Sprintf("Could not read %v", FileName)) + return nil, fmt.Errorf("Could not read %v", FileName) } return fileContent, nil @@ -110,12 +111,12 @@ func (me *AddonDescriptor) initFromYmlFile(FileName string, readFile readFileFun var jsonBytes []byte jsonBytes, err = yaml.YAMLToJSON(fileContent) if err != nil { - return errors.New(fmt.Sprintf("Could not parse %v", FileName)) + return fmt.Errorf("Could not parse %v", FileName) } err = me.initFromJSON(jsonBytes) if err != nil { - return errors.New(fmt.Sprintf("Could not unmarshal %v", FileName)) + return fmt.Errorf("Could not unmarshal %v", FileName) } return nil diff --git a/pkg/abaputils/manageGitRepositoryUtils.go b/pkg/abaputils/manageGitRepositoryUtils.go index 10d90cf9e..3d703b1af 100644 --- a/pkg/abaputils/manageGitRepositoryUtils.go +++ b/pkg/abaputils/manageGitRepositoryUtils.go @@ -8,9 +8,10 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) const numberOfEntriesPerPage = 100000 diff --git a/pkg/abaputils/sap_com_0510.go b/pkg/abaputils/sap_com_0510.go index 556fc1b74..788a37c71 100644 --- a/pkg/abaputils/sap_com_0510.go +++ b/pkg/abaputils/sap_com_0510.go @@ -11,9 +11,10 @@ import ( "strings" "time" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "k8s.io/utils/strings/slices" ) @@ -146,16 +147,16 @@ func (api *SAP_COM_0510) GetLogProtocol(logOverviewEntry LogResultsV2, page int) marshallError := json.Unmarshal(bodyText, &abapResp) if marshallError != nil { - return nil, 0, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, 0, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } marshallError = json.Unmarshal(*abapResp["d"], &body) if marshallError != nil { - return nil, 0, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, 0, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } count, errConv := strconv.Atoi(body.Count) if errConv != nil { - return nil, 0, errors.Wrap(errConv, "Could not parse response from the ABAP Environment system") + return nil, 0, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", errConv) } return body.Results, count, nil @@ -180,11 +181,11 @@ func (api *SAP_COM_0510) GetLogOverview() (result []LogResultsV2, err error) { marshallError := json.Unmarshal(bodyText, &abapResp) if marshallError != nil { - return nil, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } marshallError = json.Unmarshal(*abapResp["d"], &body) if marshallError != nil { - return nil, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } if reflect.DeepEqual(ActionEntity{}, body) { @@ -326,7 +327,7 @@ func (api *SAP_COM_0510) initialRequest() error { // Configuring the HTTP Client and CookieJar cookieJar, errorCookieJar := cookiejar.New(nil) if errorCookieJar != nil { - return errors.Wrap(errorCookieJar, "Could not create a Cookie Jar") + return fmt.Errorf("Could not create a Cookie Jar: %w", errorCookieJar) } api.client.SetOptions(piperhttp.ClientOptions{ diff --git a/pkg/abaputils/sap_com_0510_test.go b/pkg/abaputils/sap_com_0510_test.go index 1e953560c..38576e3b9 100644 --- a/pkg/abaputils/sap_com_0510_test.go +++ b/pkg/abaputils/sap_com_0510_test.go @@ -7,7 +7,8 @@ import ( "testing" "time" - "github.com/pkg/errors" + "errors" + "github.com/stretchr/testify/assert" ) diff --git a/pkg/abaputils/sap_com_0948.go b/pkg/abaputils/sap_com_0948.go index 7382058c1..ae61b269e 100644 --- a/pkg/abaputils/sap_com_0948.go +++ b/pkg/abaputils/sap_com_0948.go @@ -12,9 +12,10 @@ import ( "net/url" // add + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "k8s.io/utils/strings/slices" ) @@ -79,7 +80,7 @@ func (api *SAP_COM_0948) GetExecutionLog() (execLog ExecutionLog, err error) { marshallError := json.Unmarshal(bodyText, &execLog) if marshallError != nil { - return execLog, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return execLog, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } if reflect.DeepEqual(ExecutionLog{}, execLog) { @@ -174,7 +175,7 @@ func (api *SAP_COM_0948) GetLogProtocol(logOverviewEntry LogResultsV2, page int) marshallError := json.Unmarshal(bodyText, &body) if marshallError != nil { - return nil, 0, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, 0, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } return body.Results, body.Count, nil @@ -198,11 +199,11 @@ func (api *SAP_COM_0948) GetLogOverview() (result []LogResultsV2, err error) { marshallError := json.Unmarshal(bodyText, &abapResp) if marshallError != nil { - return nil, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } marshallError = json.Unmarshal(*abapResp["value"], &result) if marshallError != nil { - return nil, errors.Wrap(marshallError, "Could not parse response from the ABAP Environment system") + return nil, fmt.Errorf("Could not parse response from the ABAP Environment system: %w", marshallError) } if reflect.DeepEqual(LogResultsV2{}, result) { @@ -304,7 +305,7 @@ func (api *SAP_COM_0948) Clone() error { cloneConnectionDetails.URL = api.con.URL + api.path + api.softwareComponentEntity + api.getRepoNameForPath() + api.cloneAction body, err := api.repository.GetCloneRequestBody() if err != nil { - return errors.Wrap(err, "Failed to clone repository") + return fmt.Errorf("Failed to clone repository: %w", err) } return api.triggerRequest(cloneConnectionDetails, []byte(body)) @@ -374,7 +375,7 @@ func (api *SAP_COM_0948) initialRequest() error { // Configuring the HTTP Client and CookieJar cookieJar, errorCookieJar := cookiejar.New(nil) if errorCookieJar != nil { - return errors.Wrap(errorCookieJar, "Could not create a Cookie Jar") + return fmt.Errorf("Could not create a Cookie Jar: %w", errorCookieJar) } api.client.SetOptions(piperhttp.ClientOptions{ @@ -490,8 +491,8 @@ func handleHTTPError(resp *http.Response, err error, message string, connectionD if parsingError != nil { return "", err } - abapError := errors.New(fmt.Sprintf("%s - %s", errorCode, errorText)) - err = errors.Wrap(abapError, err.Error()) + abapError := fmt.Errorf("%s - %s", errorCode, errorText) + err = fmt.Errorf("%s: %w", err.Error(), abapError) } return errorCode, err diff --git a/pkg/abaputils/sap_com_0948_test.go b/pkg/abaputils/sap_com_0948_test.go index 41bd651b0..3e7059886 100644 --- a/pkg/abaputils/sap_com_0948_test.go +++ b/pkg/abaputils/sap_com_0948_test.go @@ -7,7 +7,8 @@ import ( "testing" "time" - "github.com/pkg/errors" + "errors" + "github.com/stretchr/testify/assert" ) diff --git a/pkg/ado/ado.go b/pkg/ado/ado.go index 095084eb5..32acf8d97 100644 --- a/pkg/ado/ado.go +++ b/pkg/ado/ado.go @@ -4,9 +4,10 @@ import ( "context" "fmt" + "errors" + "github.com/microsoft/azure-devops-go-api/azuredevops" "github.com/microsoft/azure-devops-go-api/azuredevops/build" - "github.com/pkg/errors" ) const azureUrl = "https://dev.azure.com" @@ -42,7 +43,7 @@ func (bc *BuildClientImpl) UpdateVariables(variables []Variable) error { // Get a build definition buildDefinition, err := bc.buildClient.GetDefinition(bc.ctx, getDefinitionArgs) if err != nil { - return errors.Wrapf(err, "error: get definition failed") + return fmt.Errorf("error: get definition failed: %w", err) } buildDefinitionVars := map[string]build.BuildDefinitionVariable{} @@ -68,7 +69,7 @@ func (bc *BuildClientImpl) UpdateVariables(variables []Variable) error { _, err = bc.buildClient.UpdateDefinition(bc.ctx, updateDefinitionArgs) if err != nil { - return errors.Wrapf(err, "error: update definition failed") + return fmt.Errorf("error: update definition failed: %w", err) } return nil diff --git a/pkg/ans/ans.go b/pkg/ans/ans.go index f57b3eebd..4448d740c 100644 --- a/pkg/ans/ans.go +++ b/pkg/ans/ans.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/SAP/jenkins-library/pkg/xsuaa" - "github.com/pkg/errors" ) // ANS holds the setup for the xsuaa service to retrieve a bearer token for authorization and @@ -37,7 +36,7 @@ type ServiceKey struct { // UnmarshallServiceKeyJSON unmarshalls the given json service key string. func UnmarshallServiceKeyJSON(serviceKeyJSON string) (ansServiceKey ServiceKey, err error) { if err = json.Unmarshal([]byte(serviceKeyJSON), &ansServiceKey); err != nil { - err = errors.Wrap(err, "error unmarshalling ANS serviceKey") + err = fmt.Errorf("error unmarshalling ANS serviceKey: %w", err) } return } @@ -115,7 +114,7 @@ func handleStatusCode(requestedUrl string, expectedStatus int, response *http.Re requestedUrl, expectedStatus, response.StatusCode) responseBody, err := readResponseBody(response) if err != nil { - err = errors.Wrapf(err, "%s; reading response body failed", statusCodeError.Error()) + err = fmt.Errorf("%s; reading response body failed: %w", statusCodeError.Error(), err) } else { err = fmt.Errorf("%s; response body: %s", statusCodeError.Error(), responseBody) } @@ -126,12 +125,12 @@ func handleStatusCode(requestedUrl string, expectedStatus int, response *http.Re func readResponseBody(response *http.Response) ([]byte, error) { if response == nil { - return nil, errors.Errorf("did not retrieve an HTTP response") + return nil, fmt.Errorf("did not retrieve an HTTP response") } defer response.Body.Close() bodyText, readErr := io.ReadAll(response.Body) if readErr != nil { - return nil, errors.Wrap(readErr, "HTTP response body could not be read") + return nil, fmt.Errorf("HTTP response body could not be read: %w", readErr) } return bodyText, nil } diff --git a/pkg/ans/ans_test.go b/pkg/ans/ans_test.go index 4067cd5e0..8b36ce0e9 100644 --- a/pkg/ans/ans_test.go +++ b/pkg/ans/ans_test.go @@ -5,14 +5,15 @@ package ans import ( "encoding/json" - "github.com/SAP/jenkins-library/pkg/xsuaa" - "github.com/jarcoal/httpmock" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "io" "net/http" "net/http/httptest" "testing" + + "github.com/SAP/jenkins-library/pkg/xsuaa" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type Examinee struct { diff --git a/pkg/ans/event.go b/pkg/ans/event.go index ddb8a3b66..f74085aca 100644 --- a/pkg/ans/event.go +++ b/pkg/ans/event.go @@ -4,11 +4,12 @@ import ( "bytes" "encoding/json" "fmt" + "github.com/go-playground/locales/en" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" en_translations "github.com/go-playground/validator/v10/translations/en" - "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) @@ -55,7 +56,7 @@ type Resource struct { // MergeWithJSON unmarshalls an ANS Event JSON string and merges it with the existing receiver Event func (event *Event) MergeWithJSON(eventJSON []byte) (err error) { if err = strictUnmarshal(eventJSON, &event); err != nil { - return errors.Wrapf(err, "error unmarshalling ANS event from JSON string %q", eventJSON) + return fmt.Errorf("error unmarshalling ANS event from JSON string %q: %w", eventJSON, err) } return } @@ -69,7 +70,7 @@ func (event *Event) Validate() (err error) { errs := err.(validator.ValidationErrors) err = fmt.Errorf("event JSON failed the validation") for _, fieldError := range errs.Translate(translator) { - err = errors.Wrap(err, fieldError) + err = fmt.Errorf("%s: %w", fieldError, err) } } return diff --git a/pkg/ans/event_test.go b/pkg/ans/event_test.go index 2411504e7..ada68c956 100644 --- a/pkg/ans/event_test.go +++ b/pkg/ans/event_test.go @@ -5,10 +5,11 @@ package ans import ( "fmt" + "testing" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) func TestEvent_MergeWithJSON(t *testing.T) { diff --git a/pkg/apim/APIMUtility.go b/pkg/apim/APIMUtility.go index 6c642b467..282f24d58 100644 --- a/pkg/apim/APIMUtility.go +++ b/pkg/apim/APIMUtility.go @@ -9,7 +9,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/xsuaa" "github.com/pasztorpisti/qs" - "github.com/pkg/errors" ) // Utils for apim @@ -53,7 +52,7 @@ func (apim *Bundle) InitAPIM() error { token, tokenErr := x.GetBearerToken() if tokenErr != nil { - return errors.Wrap(tokenErr, "failed to fetch Bearer Token") + return fmt.Errorf("failed to fetch Bearer Token: %w", tokenErr) } clientOptions.Token = fmt.Sprintf("Bearer %s", token.AccessToken) httpClient.SetOptions(clientOptions) diff --git a/pkg/apim/HttpMockAPIM.go b/pkg/apim/HttpMockAPIM.go index baa69e94d..b6452d2d1 100644 --- a/pkg/apim/HttpMockAPIM.go +++ b/pkg/apim/HttpMockAPIM.go @@ -8,8 +8,9 @@ import ( "io" "net/http" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/pkg/errors" ) type HttpMockAPIM struct { diff --git a/pkg/asc/asc.go b/pkg/asc/asc.go index db64cbf6d..4476150bd 100644 --- a/pkg/asc/asc.go +++ b/pkg/asc/asc.go @@ -11,9 +11,10 @@ import ( "strings" "time" + "errors" + piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -127,7 +128,7 @@ func (sys *SystemInstance) GetAppById(appId string) (App, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("api/v1/apps/%v", appId), nil, nil) if err != nil { - return app, errors.Wrapf(err, "fetching app %v failed", appId) + return app, fmt.Errorf("fetching app %v failed: %w", appId, err) } json.Unmarshal(data, &app) @@ -153,7 +154,7 @@ func (sys *SystemInstance) CreateRelease(ascAppId int, version string, descripti jsonValue, err := json.Marshal(jsonData) if err != nil { - return createReleaseResponse, errors.Wrap(err, "error marshalling release payload") + return createReleaseResponse, fmt.Errorf("error marshalling release payload: %w", err) } header := http.Header{} @@ -161,7 +162,7 @@ func (sys *SystemInstance) CreateRelease(ascAppId int, version string, descripti response, err := sendRequest(sys, http.MethodPost, fmt.Sprintf("api/v1/apps/%v/releases", ascAppId), bytes.NewBuffer(jsonValue), header) if err != nil { - return createReleaseResponse, errors.Wrap(err, "creating release") + return createReleaseResponse, fmt.Errorf("creating release: %w", err) } json.Unmarshal(response, &createReleaseResponse) @@ -176,7 +177,7 @@ func (sys *SystemInstance) GetJamfAppInfo(bundleId string, jamfTargetSystem stri data, err := sendRequest(sys, http.MethodPost, fmt.Sprintf("api/v1/jamf/%v/info?system=%v", bundleId, url2.QueryEscape(jamfTargetSystem)), nil, nil) if err != nil { - return jamfAppInformationResponse, errors.Wrapf(err, "fetching jamf %v app info for %v failed", jamfTargetSystem, bundleId) + return jamfAppInformationResponse, fmt.Errorf("fetching jamf %v app info for %v failed: %w", jamfTargetSystem, bundleId, err) } json.Unmarshal(data, &jamfAppInformationResponse) @@ -191,7 +192,7 @@ func (sys *SystemInstance) UploadIpa(path string, jamfAppId int, jamfTargetSyste _, err := sys.client.UploadFile(url, path, "file", nil, nil, "form") if err != nil { - return errors.Wrap(err, "failed to upload ipa to asc") + return fmt.Errorf("failed to upload ipa to asc: %w", err) } return nil diff --git a/pkg/blackduck/blackduck.go b/pkg/blackduck/blackduck.go index eddc898a8..dcd95209d 100644 --- a/pkg/blackduck/blackduck.go +++ b/pkg/blackduck/blackduck.go @@ -13,7 +13,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/reporting" "github.com/package-url/packageurl-go" - "github.com/pkg/errors" ) // ReportsDirectory defines the subfolder for the BlackDuck reports which are generated @@ -295,12 +294,12 @@ func (b *Client) getProjectByPagination(projectName string, offset int) (*Projec } respBody, err := b.sendRequest("GET", "/api/projects", queryParams, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "failed to get project '%v'", projectName) + return nil, fmt.Errorf("failed to get project '%v': %w", projectName, err) } projects := Projects{} err = json.Unmarshal(respBody, &projects) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve details for project '%v'", projectName) + return nil, fmt.Errorf("failed to retrieve details for project '%v': %w", projectName, err) } else if projects.TotalCount == 0 { return nil, fmt.Errorf("project '%v' not found", projectName) } @@ -333,13 +332,13 @@ func (b *Client) GetProjectVersion(projectName, projectVersion string) (*Project //More than 100 project versions is currently not supported/recommended by BlackDuck respBody, err := b.sendRequest("GET", versionPath, map[string]string{"offset": "0", "limit": "100"}, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "failed to get project version '%v:%v'", projectName, projectVersion) + return nil, fmt.Errorf("failed to get project version '%v:%v': %w", projectName, projectVersion, err) } projectVersions := ProjectVersions{} err = json.Unmarshal(respBody, &projectVersions) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve details for project version '%v:%v'", projectName, projectVersion) + return nil, fmt.Errorf("failed to retrieve details for project version '%v:%v': %w", projectName, projectVersion, err) } else if projectVersions.TotalCount == 0 { return nil, fmt.Errorf("project version '%v:%v' not found", projectName, projectVersion) } @@ -386,14 +385,14 @@ func (b *Client) GetComponents(projectName, versionName string) (*Components, er respBody, err := b.sendRequest("GET", componentsPath, map[string]string{"offset": "0", "limit": "999"}, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "Failed to get components list for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("Failed to get components list for project version '%v:%v': %w", projectName, versionName, err) } components := Components{} err = json.Unmarshal(respBody, &components) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve component details for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("failed to retrieve component details for project version '%v:%v': %w", projectName, versionName, err) } else if components.TotalCount == 0 { return nil, fmt.Errorf("No Components found for project version '%v:%v'", projectName, versionName) } @@ -420,14 +419,14 @@ func (b *Client) GetComponentsWithLicensePolicyRule(projectName, versionName str respBody, err := b.sendRequest("GET", componentsPath, map[string]string{"offset": "0", "limit": "999", "filter": "policyCategory:license"}, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "Failed to get components list for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("Failed to get components list for project version '%v:%v': %w", projectName, versionName, err) } components := Components{} err = json.Unmarshal(respBody, &components) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve component details for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("failed to retrieve component details for project version '%v:%v': %w", projectName, versionName, err) } //Just return the components, the details of the components are not necessary @@ -467,13 +466,13 @@ func (b *Client) GetVulnerabilities(projectName, versionName string) (*Vulnerabi respBody, err := b.sendRequest("GET", vulnerableComponentsPath, map[string]string{"offset": "0", "limit": "999"}, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "Failed to get Vulnerabilties for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("Failed to get Vulnerabilties for project version '%v:%v': %w", projectName, versionName, err) } vulnerabilities := Vulnerabilities{} err = json.Unmarshal(respBody, &vulnerabilities) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve Vulnerability details for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("failed to retrieve Vulnerability details for project version '%v:%v': %w", projectName, versionName, err) } return &vulnerabilities, nil @@ -498,13 +497,13 @@ func (b *Client) GetPolicyStatus(projectName, versionName string) (*PolicyStatus respBody, err := b.sendRequest("GET", policyStatusPath, map[string]string{}, nil, headers) if err != nil { - return nil, errors.Wrapf(err, "Failed to get Policy Violation status for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("Failed to get Policy Violation status for project version '%v:%v': %w", projectName, versionName, err) } policyStatus := PolicyStatus{} err = json.Unmarshal(respBody, &policyStatus) if err != nil { - return nil, errors.Wrapf(err, "failed to retrieve Policy violation details for project version '%v:%v'", projectName, versionName) + return nil, fmt.Errorf("failed to retrieve Policy violation details for project version '%v:%v': %w", projectName, versionName, err) } return &policyStatus, nil @@ -517,11 +516,11 @@ func (b *Client) authenticate() error { b.lastAuthentication = time.Now() respBody, err := b.sendRequest(http.MethodPost, "/api/tokens/authenticate", map[string]string{}, nil, headers) if err != nil { - return errors.Wrap(err, "authentication to BlackDuck API failed") + return fmt.Errorf("authentication to BlackDuck API failed: %w", err) } err = json.Unmarshal(respBody, b) if err != nil { - return errors.Wrap(err, "failed to parse BlackDuck response") + return fmt.Errorf("failed to parse BlackDuck response: %w", err) } return nil } @@ -531,7 +530,7 @@ func (b *Client) sendRequest(method, apiEndpoint string, params map[string]strin blackDuckAPIUrl, err := b.apiURL(apiEndpoint) if err != nil { - return responseBody, errors.Wrap(err, "failed to get api url") + return responseBody, fmt.Errorf("failed to get api url: %w", err) } q := url.Values{} @@ -546,12 +545,12 @@ func (b *Client) sendRequest(method, apiEndpoint string, params map[string]strin response, err := b.httpClient.SendRequest(method, blackDuckAPIUrl.String(), nil, header, nil) if err != nil { - return responseBody, errors.Wrap(err, "request to BlackDuck API failed") + return responseBody, fmt.Errorf("request to BlackDuck API failed: %w", err) } responseBody, err = io.ReadAll(response.Body) if err != nil { - return responseBody, errors.Wrap(err, "reading BlackDuck response failed") + return responseBody, fmt.Errorf("reading BlackDuck response failed: %w", err) } return responseBody, nil } diff --git a/pkg/blackduck/reporting.go b/pkg/blackduck/reporting.go index 0786a1c01..17287d8cd 100644 --- a/pkg/blackduck/reporting.go +++ b/pkg/blackduck/reporting.go @@ -13,7 +13,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" - "github.com/pkg/errors" ) var severityIndex = map[string]int{"LOW": 1, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4} @@ -214,7 +213,7 @@ func WriteVulnerabilityReports(scanReport reporting.ScanReport, utils piperutils htmlReportPath := "piper_detect_vulnerability_report.html" if err := utils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "BlackDuck Vulnerability Report", Target: htmlReportPath}) @@ -222,11 +221,11 @@ func WriteVulnerabilityReports(scanReport reporting.ScanReport, utils piperutils if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create reporting directory") + return reportPaths, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("detectExecuteScan_oss_%v.json", fmt.Sprintf("%v", utils.CurrentTime("")))), jsonReport, 0666); err != nil { - return reportPaths, errors.Wrapf(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } return reportPaths, nil @@ -239,16 +238,16 @@ func WriteSarifFile(sarif *format.SARIF, utils piperutils.FileUtils) ([]piperuti // ignore templating errors since template is in our hands and issues will be detected with the automated tests sarifReport, errorMarshall := json.Marshal(sarif) if errorMarshall != nil { - return reportPaths, errors.Wrapf(errorMarshall, "failed to marshall SARIF json file") + return reportPaths, fmt.Errorf("failed to marshall SARIF json file: %w", errorMarshall) } if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } sarifReportPath := filepath.Join(ReportsDirectory, "piper_detect_vulnerability.sarif") if err := utils.FileWrite(sarifReportPath, sarifReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write SARIF file") + return reportPaths, fmt.Errorf("failed to write SARIF file: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "BlackDuck Detect Vulnerability SARIF file", Target: sarifReportPath}) diff --git a/pkg/buildsettings/buildSettings.go b/pkg/buildsettings/buildSettings.go index 57ecb1bc0..7717bd21e 100644 --- a/pkg/buildsettings/buildSettings.go +++ b/pkg/buildsettings/buildSettings.go @@ -2,11 +2,11 @@ package buildsettings import ( "encoding/json" + "fmt" "os" "reflect" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) type BuildSettings struct { @@ -56,7 +56,7 @@ func CreateBuildSettingsInfo(config *BuildOptions, buildTool string) (string, er err := json.Unmarshal([]byte(config.BuildSettingsInfo), &jsonMap) if err != nil { - return "", errors.Wrapf(err, "failed to unmarshal existing build settings json '%v'", config.BuildSettingsInfo) + return "", fmt.Errorf("failed to unmarshal existing build settings json '%v': %w", config.BuildSettingsInfo, err) } if build, exist := jsonMap[buildTool]; exist { @@ -71,7 +71,7 @@ func CreateBuildSettingsInfo(config *BuildOptions, buildTool string) (string, er jsonResult, err = json.Marshal(&jsonMap) if err != nil { - return "", errors.Wrap(err, "Creating build settings failed with json marshalling") + return "", fmt.Errorf("Creating build settings failed with json marshalling: %w", err) } } else { var settings []BuildOptions @@ -119,7 +119,7 @@ func CreateBuildSettingsInfo(config *BuildOptions, buildTool string) (string, er return "", nil } if err != nil { - return "", errors.Wrap(err, "Creating build settings failed with json marshalling") + return "", fmt.Errorf("Creating build settings failed with json marshalling: %w", err) } } diff --git a/pkg/certutils/certutils.go b/pkg/certutils/certutils.go index 4e496dda4..61b5a5115 100644 --- a/pkg/certutils/certutils.go +++ b/pkg/certutils/certutils.go @@ -1,13 +1,13 @@ package certutils import ( + "fmt" "io" "net/http" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) // CertificateUpdate adds certificates to the given truststore @@ -20,7 +20,7 @@ func CertificateUpdate(certLinks []string, httpClient piperhttp.Sender, fileUtil caCerts, err := fileUtils.FileRead(caCertsFile) if err != nil { - return errors.Wrapf(err, "failed to load file '%v'", caCertsFile) + return fmt.Errorf("failed to load file '%v': %w", caCertsFile, err) } byteCerts, err := CertificateDownload(certLinks, httpClient) @@ -32,7 +32,7 @@ func CertificateUpdate(certLinks []string, httpClient piperhttp.Sender, fileUtil err = fileUtils.FileWrite(caCertsFile, caCerts, 0644) if err != nil { - return errors.Wrapf(err, "failed to update file '%v'", caCertsFile) + return fmt.Errorf("failed to update file '%v': %w", caCertsFile, err) } return nil } @@ -48,12 +48,12 @@ func CertificateDownload(certLinks []string, client piperhttp.Sender) ([]byte, e log.Entry().Debugf("Downloading CA certificate from URL: %s", certLink) response, err := client.SendRequest(http.MethodGet, certLink, nil, nil, nil) if err != nil { - return nil, errors.Wrap(err, "failed to load certificate from url") + return nil, fmt.Errorf("failed to load certificate from url: %w", err) } content, err := io.ReadAll(response.Body) if err != nil { - return nil, errors.Wrap(err, "failed to read response") + return nil, fmt.Errorf("failed to read response: %w", err) } _ = response.Body.Close() content = append(content, []byte("\n")...) diff --git a/pkg/checkmarx/checkmarx.go b/pkg/checkmarx/checkmarx.go index bccc87a46..251b34a8f 100644 --- a/pkg/checkmarx/checkmarx.go +++ b/pkg/checkmarx/checkmarx.go @@ -14,9 +14,10 @@ import ( "encoding/xml" + "errors" + piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -272,7 +273,7 @@ func NewSystemInstance(client piperHttp.Uploader, serverURL, username, password token, err := sys.getOAuth2Token() if err != nil { - return sys, errors.Wrap(err, "Error fetching oAuth token") + return sys, fmt.Errorf("Error fetching oAuth token: %w", err) } log.RegisterSecret(token) @@ -373,7 +374,7 @@ func (sys *SystemInstance) GetProjectByID(projectID int) (Project, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/%v", projectID), nil, nil) if err != nil { - return project, errors.Wrapf(err, "fetching project %v failed", projectID) + return project, fmt.Errorf("fetching project %v failed: %w", projectID, err) } json.Unmarshal(data, &project) @@ -398,7 +399,7 @@ func (sys *SystemInstance) GetProjectsByNameAndTeam(projectName, teamID string) data, err = sendRequestInternal(sys, http.MethodGet, "/projects", nil, header, []int{404}) } if err != nil { - return projects, errors.Wrapf(err, "fetching project %v failed", projectName) + return projects, fmt.Errorf("fetching project %v failed: %w", projectName, err) } json.Unmarshal(data, &projects) @@ -416,7 +417,7 @@ func (sys *SystemInstance) CreateProject(projectName, teamID string) (ProjectCre jsonValue, err := json.Marshal(jsonData) if err != nil { - return result, errors.Wrapf(err, "failed to marshal project data") + return result, fmt.Errorf("failed to marshal project data: %w", err) } header := http.Header{} @@ -424,7 +425,7 @@ func (sys *SystemInstance) CreateProject(projectName, teamID string) (ProjectCre data, err := sendRequest(sys, http.MethodPost, "/projects", bytes.NewBuffer(jsonValue), header) if err != nil { - return result, errors.Wrapf(err, "failed to create project %v", projectName) + return result, fmt.Errorf("failed to create project %v: %w", projectName, err) } json.Unmarshal(data, &result) @@ -495,13 +496,13 @@ func (sys *SystemInstance) UploadProjectSourceCode(projectID int, zipFile string header.Add("Accept", "text/plain") resp, err := sys.client.UploadFile(fmt.Sprintf("%v/cxrestapi/projects/%v/sourceCode/attachments", sys.serverURL, projectID), zipFile, "zippedSource", header, nil, "form") if err != nil { - return errors.Wrap(err, "failed to uploaded zipped sources") + return fmt.Errorf("failed to uploaded zipped sources: %w", err) } data, err := io.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { - return errors.Wrap(err, "error reading the response data") + return fmt.Errorf("error reading the response data: %w", err) } responseData := make(map[string]string) @@ -512,7 +513,7 @@ func (sys *SystemInstance) UploadProjectSourceCode(projectID int, zipFile string } sys.logger.Debugf("Body %s", data) - return errors.Wrapf(err, "error writing the request's body, status: %s", resp.Status) + return fmt.Errorf("error writing the request's body, status: %s: %w", resp.Status, err) } // UpdateProjectExcludeSettings updates the exclude configuration of the project @@ -524,14 +525,14 @@ func (sys *SystemInstance) UpdateProjectExcludeSettings(projectID int, excludeFo jsonValue, err := json.Marshal(jsonData) if err != nil { - return errors.Wrap(err, "error marhalling project exclude settings") + return fmt.Errorf("error marhalling project exclude settings: %w", err) } header := http.Header{} header.Set("Content-Type", "application/json") _, err = sendRequest(sys, http.MethodPut, fmt.Sprintf("/projects/%v/sourceCode/excludeSettings", projectID), bytes.NewBuffer(jsonValue), header) if err != nil { - return errors.Wrap(err, "request to checkmarx system failed") + return fmt.Errorf("request to checkmarx system failed: %w", err) } return nil @@ -585,12 +586,12 @@ func (sys *SystemInstance) UpdateProjectConfiguration(projectID int, presetID in jsonValue, err := json.Marshal(jsonData) if err != nil { - return errors.Wrapf(err, "error marshalling project data") + return fmt.Errorf("error marshalling project data: %w", err) } _, err = sendRequest(sys, http.MethodPost, "/sast/scanSettings", bytes.NewBuffer(jsonValue), header) if err != nil { - return errors.Wrapf(err, "request to checkmarx system failed") + return fmt.Errorf("request to checkmarx system failed: %w", err) } sys.logger.Debugf("Project configuration updated") @@ -616,7 +617,7 @@ func (sys *SystemInstance) ScanProject(projectID int, isIncremental, isPublic, f data, err := sendRequest(sys, http.MethodPost, "/sast/scans", bytes.NewBuffer(jsonValue), header) if err != nil { sys.logger.Errorf("Failed to trigger scan of project %v: %s", projectID, err) - return scan, errors.Wrapf(err, "Failed to trigger scan of project %v", projectID) + return scan, fmt.Errorf("Failed to trigger scan of project %v: %w", projectID, err) } json.Unmarshal(data, &scan) @@ -637,7 +638,7 @@ func (sys *SystemInstance) GetScans(projectID int) ([]ScanStatus, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/sast/scans?%v", body.Encode()), nil, header) if err != nil { sys.logger.Errorf("Failed to fetch scans of project %v: %s", projectID, err) - return scans, errors.Wrapf(err, "failed to fetch scans of project %v", projectID) + return scans, fmt.Errorf("failed to fetch scans of project %v: %w", projectID, err) } json.Unmarshal(data, &scans) @@ -688,7 +689,7 @@ func (sys *SystemInstance) RequestNewReport(scanID int, reportType string) (Repo header.Set("Content-Type", "application/json") data, err := sendRequest(sys, http.MethodPost, "/reports/sastScan", bytes.NewBuffer(jsonValue), header) if err != nil { - return report, errors.Wrapf(err, "Failed to trigger report generation for scan %v", scanID) + return report, fmt.Errorf("Failed to trigger report generation for scan %v: %w", scanID, err) } json.Unmarshal(data, &report) @@ -704,7 +705,7 @@ func (sys *SystemInstance) GetReportStatus(reportID int) (ReportStatusResponse, data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/reports/sastScan/%v/status", reportID), nil, header) if err != nil { sys.logger.Errorf("Failed to fetch report status for reportID %v: %s", reportID, err) - return response, errors.Wrapf(err, "failed to fetch report status for reportID %v", reportID) + return response, fmt.Errorf("failed to fetch report status for reportID %v: %w", reportID, err) } json.Unmarshal(data, &response) @@ -731,7 +732,7 @@ func (sys *SystemInstance) DownloadReport(reportID int) ([]byte, error) { header.Set("Accept", "application/json") data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/reports/sastScan/%v", reportID), nil, header) if err != nil { - return []byte{}, errors.Wrapf(err, "failed to download report with reportID %v", reportID) + return []byte{}, fmt.Errorf("failed to download report with reportID %v: %w", reportID, err) } return data, nil } diff --git a/pkg/checkmarx/cxxml_to_sarif.go b/pkg/checkmarx/cxxml_to_sarif.go index 98e74df62..141b7dfe9 100644 --- a/pkg/checkmarx/cxxml_to_sarif.go +++ b/pkg/checkmarx/cxxml_to_sarif.go @@ -9,10 +9,11 @@ import ( "strings" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/format" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) // CxXMLResults : This struct encapsulates everyting in the Cx XML document diff --git a/pkg/checkmarx/reporting.go b/pkg/checkmarx/reporting.go index 2b4d73bf9..f8d002e14 100644 --- a/pkg/checkmarx/reporting.go +++ b/pkg/checkmarx/reporting.go @@ -15,8 +15,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" - - "github.com/pkg/errors" ) type CheckmarxReportData struct { @@ -200,13 +198,13 @@ func WriteJSONReport(jsonReport CheckmarxReportData) ([]piperutils.Path, error) jsonComplianceReportPath := filepath.Join(ReportsDirectory, "piper_checkmarx_report.json") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } file, _ := json.Marshal(jsonReport) if err := utils.FileWrite(jsonComplianceReportPath, file, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write Checkmarx JSON compliance report") + return reportPaths, fmt.Errorf("failed to write Checkmarx JSON compliance report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Checkmarx JSON Compliance Report", Target: jsonComplianceReportPath}) @@ -221,7 +219,7 @@ func WriteSarif(sarif format.SARIF) ([]piperutils.Path, error) { sarifReportPath := filepath.Join(ReportsDirectory, "result.sarif") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } // HTML characters will most likely be present: we need to use encode: create a buffer to hold JSON data @@ -236,7 +234,7 @@ func WriteSarif(sarif format.SARIF) ([]piperutils.Path, error) { log.Entry().Info("Writing file to disk: ", sarifReportPath) if err := utils.FileWrite(sarifReportPath, buffer.Bytes(), 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write Checkmarx SARIF report") + return reportPaths, fmt.Errorf("failed to write Checkmarx SARIF report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Checkmarx SARIF Report", Target: sarifReportPath}) @@ -252,11 +250,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID htmlReportPath := filepath.Join(ReportsDirectory, "piper_checkmarx_report.html") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } if err := utils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Checkmarx Report", Target: htmlReportPath}) @@ -266,11 +264,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create reporting directory") + return reportPaths, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("checkmarxExecuteScan_sast_%v.json", reportShaCheckmarx([]string{projectName, projectID}))), jsonReport, 0666); err != nil { - return reportPaths, errors.Wrapf(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } // we do not add the json report to the overall list of reports for now, // since it is just an intermediary report used as input for later diff --git a/pkg/checkmarxone/checkmarxone.go b/pkg/checkmarxone/checkmarxone.go index 60fe4eca9..180530955 100644 --- a/pkg/checkmarxone/checkmarxone.go +++ b/pkg/checkmarxone/checkmarxone.go @@ -13,9 +13,10 @@ import ( "strings" "time" + "errors" + piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -364,12 +365,12 @@ func NewSystemInstance(client piperHttp.Uploader, serverURL, iamURL, tenant, API if APIKey != "" { token, err = sys.getAPIToken() if err != nil { - return sys, errors.Wrap(err, fmt.Sprintf("Error fetching oAuth token using API Key: %v", shortenGUID(APIKey))) + return sys, fmt.Errorf("Error fetching oAuth token using API Key %v: %w", shortenGUID(APIKey), err) } } else if client_id != "" && client_secret != "" { token, err = sys.getOAuth2Token() if err != nil { - return sys, errors.Wrap(err, fmt.Sprintf("Error fetching oAuth token using OIDC client: %v/%v", shortenGUID(client_id), shortenGUID(client_secret))) + return sys, fmt.Errorf(fmt.Sprintf("Error fetching oAuth token using OIDC client: %v/%v", shortenGUID(client_id), shortenGUID(client_secret)), err) } } else { return sys, errors.New("No APIKey or client_id/client_secret provided.") @@ -718,7 +719,7 @@ func (sys *SystemInstance) GetGroupByName(groupName string) (Group, error) { } } - return group, errors.New(fmt.Sprintf("No group matching %v", groupName)) + return group, fmt.Errorf("No group matching %v", groupName) } // New for Cx1 @@ -736,7 +737,7 @@ func (sys *SystemInstance) GetGroupByID(groupID string) (Group, error) { } } - return group, errors.New(fmt.Sprintf("No group with ID %v", groupID)) + return group, fmt.Errorf("No group with ID %v", groupID) } // GetProjects returns the projects defined in the Checkmarx backend which the user has access to @@ -752,7 +753,7 @@ func (sys *SystemInstance) GetProjectByID(projectID string) (Project, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/%v", projectID), nil, http.Header{}, []int{}) if err != nil { - return project, errors.Wrapf(err, "fetching project %v failed", projectID) + return project, fmt.Errorf("fetching project %v failed: %w", projectID, err) } err = json.Unmarshal(data, &project) @@ -781,7 +782,7 @@ func (sys *SystemInstance) GetProjectsByName(projectName string) ([]Project, err data, err = sendRequest(sys, http.MethodGet, fmt.Sprintf("/projects/?%v", body.Encode()), nil, header, []int{404}) if err != nil { - return []Project{}, errors.Wrapf(err, "fetching project %v failed", projectName) + return []Project{}, fmt.Errorf("fetching project %v failed: %w", projectName, err) } err = json.Unmarshal(data, &projectResponse) @@ -818,7 +819,7 @@ func (sys *SystemInstance) GetProjectsByNameAndGroup(projectName, groupID string data, err = sendRequest(sys, http.MethodGet, "/projects/", nil, header, []int{404}) } if err != nil { - return projectResponse.Projects, errors.Wrapf(err, "fetching project %v failed", projectName) + return projectResponse.Projects, fmt.Errorf("fetching project %v failed: %w", projectName, err) } err = json.Unmarshal(data, &projectResponse) @@ -839,7 +840,7 @@ func (sys *SystemInstance) CreateProject(projectName string, groupIDs []string) jsonValue, err := json.Marshal(jsonData) if err != nil { - return project, errors.Wrapf(err, "failed to marshal project data") + return project, fmt.Errorf("failed to marshal project data: %w", err) } header := http.Header{} @@ -847,7 +848,7 @@ func (sys *SystemInstance) CreateProject(projectName string, groupIDs []string) data, err := sendRequest(sys, http.MethodPost, "/projects", bytes.NewBuffer(jsonValue), header, []int{}) if err != nil { - return project, errors.Wrapf(err, "failed to create project %v", projectName) + return project, fmt.Errorf("failed to create project %v: %w", projectName, err) } err = json.Unmarshal(data, &project) @@ -867,7 +868,7 @@ func (sys *SystemInstance) CreateProjectInApplication(projectName, applicationID jsonValue, err := json.Marshal(jsonData) if err != nil { - return project, errors.Wrapf(err, "failed to marshal project data") + return project, fmt.Errorf("failed to marshal project data: %w", err) } header := http.Header{} @@ -875,12 +876,12 @@ func (sys *SystemInstance) CreateProjectInApplication(projectName, applicationID data, err := sendRequest(sys, http.MethodPost, "/projects", bytes.NewReader(jsonValue), header, []int{}) if err != nil { - return project, errors.Wrapf(err, "failed to create project %v under %v", projectName, applicationID) + return project, fmt.Errorf("failed to create project %v under %v: %w", projectName, applicationID, err) } err = json.Unmarshal(data, &project) if err != nil { - return project, errors.Wrapf(err, "failed to unmarshal project data") + return project, fmt.Errorf("failed to unmarshal project data: %w", err) } // since there is a delay to assign a project to an application, adding a check to ensure project is ready after creation @@ -910,7 +911,7 @@ func (sys *SystemInstance) GetUploadURI() (string, error) { resp, err := sendRequest(sys, http.MethodPost, "/uploads", nil, header, []int{}) if err != nil { - return "", errors.Wrap(err, "failed to get an upload uri") + return "", fmt.Errorf("failed to get an upload uri: %w", err) } responseData := make(map[string]string) @@ -982,7 +983,7 @@ func (sys *SystemInstance) ScanProjectZip(projectID, sourceUrl, branch string, s scan, err := sys.scanProject(jsonBody) if err != nil { - return scan, errors.Wrapf(err, "Failed to start a zip scan for project %v", projectID) + return scan, fmt.Errorf("Failed to start a zip scan for project %v: %w", projectID, err) } return scan, err } @@ -1001,7 +1002,7 @@ func (sys *SystemInstance) ScanProjectGit(projectID, repoUrl, branch string, set scan, err := sys.scanProject(jsonBody) if err != nil { - return scan, errors.Wrapf(err, "Failed to start a git scan for project %v", projectID) + return scan, fmt.Errorf("Failed to start a git scan for project %v: %w", projectID, err) } return scan, err } @@ -1117,7 +1118,7 @@ func (sys *SystemInstance) GetScan(scanID string) (Scan, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/scans/%v", scanID), nil, http.Header{}, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch scan with ID %v: %s", scanID, err) - return scan, errors.Wrapf(err, "failed to fetch scan with ID %v", scanID) + return scan, fmt.Errorf("failed to fetch scan with ID %v: %w", scanID, err) } json.Unmarshal(data, &scan) @@ -1134,7 +1135,7 @@ func (sys *SystemInstance) GetScanMetadatas(scanIDs []string) ([]ScanMetadata, e data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/sast-metadata?%v", params.Encode()), nil, http.Header{}, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch metadata for scans %s, error was: %s", fmt.Sprintf("%v", strings.Join(scanIDs, ",")), err) - return scans, errors.Wrapf(err, "failed to fetch metadata for scans") + return scans, fmt.Errorf("failed to fetch metadata for scans: %w", err) } json.Unmarshal(data, &scanmetadatalistresp) @@ -1149,7 +1150,7 @@ func (sys *SystemInstance) GetScanMetadata(scanID string) (ScanMetadata, error) data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/sast-metadata/%v", scanID), nil, http.Header{}, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch metadata for scan with ID %v: %s", scanID, err) - return scanmeta, errors.Wrapf(err, "failed to fetch metadata for scan with ID %v", scanID) + return scanmeta, fmt.Errorf("failed to fetch metadata for scan with ID %v: %w", scanID, err) } json.Unmarshal(data, &scanmeta) @@ -1162,7 +1163,7 @@ func (sys *SystemInstance) GetScanWorkflow(scanID string) ([]WorkflowLog, error) data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/scans/%v/workflow", scanID), nil, http.Header{}, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch scan with ID %v: %s", scanID, err) - return []WorkflowLog{}, errors.Wrapf(err, "failed to fetch scan with ID %v", scanID) + return []WorkflowLog{}, fmt.Errorf("failed to fetch scan with ID %v: %w", scanID, err) } json.Unmarshal(data, &workflow) @@ -1198,7 +1199,7 @@ func (sys *SystemInstance) GetLastScans(projectID, branch string, limit int) ([] data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/scans/?%v", body.Encode()), nil, header, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch scans of project %v: %s", projectID, err) - return []Scan{}, errors.Wrapf(err, "failed to fetch scans of project %v", projectID) + return []Scan{}, fmt.Errorf("failed to fetch scans of project %v: %w", projectID, err) } err = json.Unmarshal(data, &scanResponse) @@ -1233,7 +1234,7 @@ func (sys *SystemInstance) GetLastScansByStatus(projectID, branch string, limit data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/scans/?%v", body.Encode()), nil, nil, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch scans of project %v: %s", projectID, err) - return []Scan{}, errors.Wrapf(err, "failed to fetch scans of project %v", projectID) + return []Scan{}, fmt.Errorf("failed to fetch scans of project %v: %w", projectID, err) } err = json.Unmarshal(data, &scanResponse) @@ -1249,7 +1250,7 @@ func (s *Scan) IsIncremental() (bool, error) { } } } - return false, errors.New(fmt.Sprintf("Scan %v did not have a sast-engine incremental flag set", s.ScanID)) + return false, fmt.Errorf("Scan %v did not have a sast-engine incremental flag set", s.ScanID) } func (sys *SystemInstance) GetScanResults(scanID string, limit uint64) ([]ScanResult, error) { @@ -1316,7 +1317,7 @@ func (sys *SystemInstance) GetScanSummary(scanID string) (ScanSummary, error) { data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/scan-summary/?%v", params.Encode()), nil, nil, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch metadata for scan with ID %v: %s", scanID, err) - return ScanSummary{}, errors.Wrapf(err, "failed to fetch metadata for scan with ID %v", scanID) + return ScanSummary{}, fmt.Errorf("failed to fetch metadata for scan with ID %v: %w", scanID, err) } err = json.Unmarshal(data, &ScansSummaries) @@ -1325,7 +1326,7 @@ func (sys *SystemInstance) GetScanSummary(scanID string) (ScanSummary, error) { return ScanSummary{}, err } if ScansSummaries.TotalCount == 0 { - return ScanSummary{}, errors.New(fmt.Sprintf("Failed to retrieve scan summary for scan ID %v", scanID)) + return ScanSummary{}, fmt.Errorf("Failed to retrieve scan summary for scan ID %v", scanID) } if len(ScansSummaries.ScanSum) == 0 { @@ -1408,7 +1409,7 @@ func (sys *SystemInstance) RequestNewReportV2(scanID, reportType string) (string header.Set("Content-Type", "application/json") data, err := sendRequest(sys, http.MethodPost, "/reports/v2", bytes.NewBuffer(jsonValue), header, []int{}) if err != nil { - return "", errors.Wrapf(err, "Failed to trigger report generation for scan %v", scanID) + return "", fmt.Errorf("Failed to trigger report generation for scan %v: %w", scanID, err) } else { sys.logger.Infof("Generating report %v", string(data)) } @@ -1431,7 +1432,7 @@ func (sys *SystemInstance) GetReportStatus(reportID string) (ReportStatus, error data, err := sendRequest(sys, http.MethodGet, fmt.Sprintf("/reports/%v?returnUrl=true", reportID), nil, header, []int{}) if err != nil { sys.logger.Errorf("Failed to fetch report status for reportID %v: %s", reportID, err) - return response, errors.Wrapf(err, "failed to fetch report status for reportID %v", reportID) + return response, fmt.Errorf("failed to fetch report status for reportID %v: %w", reportID, err) } json.Unmarshal(data, &response) @@ -1464,7 +1465,7 @@ func (sys *SystemInstance) DownloadReport(reportUrl string) ([]byte, error) { header.Set("Accept", "application/json") data, err := sendRequestInternal(sys, http.MethodGet, reportUrl, nil, header, []int{}) if err != nil { - return []byte{}, errors.Wrapf(err, "failed to download report from url: %v", reportUrl) + return []byte{}, fmt.Errorf("failed to download report from url: %v: %w", reportUrl, err) } return data, nil } diff --git a/pkg/checkmarxone/reporting.go b/pkg/checkmarxone/reporting.go index 2ba42add1..1062523a5 100644 --- a/pkg/checkmarxone/reporting.go +++ b/pkg/checkmarxone/reporting.go @@ -13,8 +13,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" - - "github.com/pkg/errors" ) type CheckmarxOneReportData struct { @@ -224,13 +222,13 @@ func WriteJSONHeaderReport(jsonReport CheckmarxOneReportData) ([]piperutils.Path jsonComplianceReportPath := filepath.Join(ReportsDirectory, "piper_checkmarxone_report.json") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } file, _ := json.Marshal(jsonReport) if err := utils.FileWrite(jsonComplianceReportPath, file, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write CheckmarxOne JSON compliance report") + return reportPaths, fmt.Errorf("failed to write CheckmarxOne JSON compliance report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "CheckmarxOne JSON Compliance Report", Target: jsonComplianceReportPath}) @@ -245,7 +243,7 @@ func WriteSarif(sarif format.SARIF) ([]piperutils.Path, error) { sarifReportPath := filepath.Join(ReportsDirectory, "result.sarif") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } // HTML characters will most likely be present: we need to use encode: create a buffer to hold JSON data @@ -260,7 +258,7 @@ func WriteSarif(sarif format.SARIF) ([]piperutils.Path, error) { log.Entry().Info("Writing file to disk: ", sarifReportPath) if err := utils.FileWrite(sarifReportPath, buffer.Bytes(), 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write CheckmarxOne SARIF report") + return reportPaths, fmt.Errorf("failed to write CheckmarxOne SARIF report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "CheckmarxOne SARIF Report", Target: sarifReportPath}) @@ -276,11 +274,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID htmlReportPath := filepath.Join(ReportsDirectory, "piper_checkmarxone_report.html") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } if err := utils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "CheckmarxOne Report", Target: htmlReportPath}) @@ -290,11 +288,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create reporting directory") + return reportPaths, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("checkmarxOneExecuteScan_sast_%v.json", reportShaCheckmarxOne([]string{projectName, projectID}))), jsonReport, 0666); err != nil { - return reportPaths, errors.Wrapf(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } // we do not add the json report to the overall list of reports for now, // since it is just an intermediary report used as input for later diff --git a/pkg/cloudfoundry/ManifestUtils.go b/pkg/cloudfoundry/ManifestUtils.go index 7042bf337..f9d4ec3d6 100644 --- a/pkg/cloudfoundry/ManifestUtils.go +++ b/pkg/cloudfoundry/ManifestUtils.go @@ -6,7 +6,6 @@ import ( "reflect" "github.com/ghodss/yaml" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/log" ) @@ -46,12 +45,12 @@ func ReadManifest(name string) (Manifest, error) { content, err := _readFile(name) if err != nil { - return m, errors.Wrapf(err, "cannot read file '%v'", m.name) + return m, fmt.Errorf("cannot read file '%v': %w", m.name, err) } err = yaml.Unmarshal(content, &m.self) if err != nil { - return m, errors.Wrapf(err, "Cannot parse yaml file '%s': %s", m.name, string(content)) + return m, fmt.Errorf("Cannot parse yaml file '%s': %s: %w", m.name, string(content), err) } log.Entry().Infof("Manifest file '%s' has been parsed", m.name) diff --git a/pkg/cloudfoundry/ManifestUtils_test.go b/pkg/cloudfoundry/ManifestUtils_test.go index c7f27d62d..d8408f28d 100644 --- a/pkg/cloudfoundry/ManifestUtils_test.go +++ b/pkg/cloudfoundry/ManifestUtils_test.go @@ -7,8 +7,9 @@ import ( "testing" "fmt" - "github.com/stretchr/testify/assert" "os" + + "github.com/stretchr/testify/assert" ) func TestReadManifest(t *testing.T) { diff --git a/pkg/cloudfoundry/Vars.go b/pkg/cloudfoundry/Vars.go index d583984cf..ef338bb26 100644 --- a/pkg/cloudfoundry/Vars.go +++ b/pkg/cloudfoundry/Vars.go @@ -2,8 +2,9 @@ package cloudfoundry import ( "fmt" - "github.com/SAP/jenkins-library/pkg/piperutils" "regexp" + + "github.com/SAP/jenkins-library/pkg/piperutils" ) // VarsFilesNotFoundError ... diff --git a/pkg/cloudfoundry/Vars_test.go b/pkg/cloudfoundry/Vars_test.go index 66b74ee75..53ba361b2 100644 --- a/pkg/cloudfoundry/Vars_test.go +++ b/pkg/cloudfoundry/Vars_test.go @@ -4,10 +4,11 @@ package cloudfoundry import ( + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/stretchr/testify/assert" - "testing" ) func TestVarsFiles(t *testing.T) { diff --git a/pkg/cnbutils/bindings/bindings.go b/pkg/cnbutils/bindings/bindings.go index 84e7e5ea1..5f0889285 100644 --- a/pkg/cnbutils/bindings/bindings.go +++ b/pkg/cnbutils/bindings/bindings.go @@ -10,7 +10,8 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" + "errors" + k8sjson "sigs.k8s.io/json" "github.com/SAP/jenkins-library/pkg/cnbutils" @@ -90,7 +91,7 @@ func (b *bindingData) bindingContentType() bindingContentType { func ProcessBindings(utils cnbutils.BuildUtils, httpClient piperhttp.Sender, platformPath string, bindings map[string]interface{}) error { typedBindings, err := toTyped(bindings) if err != nil { - return errors.Wrap(err, "error while reading bindings") + return fmt.Errorf("error while reading bindings: %w", err) } for name, binding := range typedBindings { @@ -117,12 +118,12 @@ func processBinding(utils cnbutils.BuildUtils, httpClient piperhttp.Sender, plat bindingDir := filepath.Join(platformPath, "bindings", name) err = utils.MkdirAll(bindingDir, 0755) if err != nil { - return errors.Wrap(err, "failed to create binding directory") + return fmt.Errorf("failed to create binding directory: %w", err) } err = utils.FileWrite(filepath.Join(bindingDir, "type"), []byte(bindingType), 0644) if err != nil { - return errors.Wrap(err, "failed to write the 'type' binding file") + return fmt.Errorf("failed to write the 'type' binding file: %w", err) } var bindingContent []byte @@ -131,20 +132,20 @@ func processBinding(utils cnbutils.BuildUtils, httpClient piperhttp.Sender, plat case fileBinding: bindingContent, err = utils.FileRead(*data.File) if err != nil { - return errors.Wrap(err, "failed to copy binding file") + return fmt.Errorf("failed to copy binding file: %w", err) } case contentBinding: bindingContent = []byte(*data.Content) case fromURLBinding: response, err := httpClient.SendRequest(http.MethodGet, *data.FromURL, nil, nil, nil) if err != nil { - return errors.Wrap(err, "failed to load binding from url") + return fmt.Errorf("failed to load binding from url: %w", err) } bindingContent, err = io.ReadAll(response.Body) defer response.Body.Close() if err != nil { - return errors.Wrap(err, "error reading response") + return fmt.Errorf("error reading response: %w", err) } case vaultBinding: envVar := config.VaultCredentialEnvPrefixDefault + config.ConvertEnvVar(*data.VaultCredentialKey) @@ -157,7 +158,7 @@ func processBinding(utils cnbutils.BuildUtils, httpClient piperhttp.Sender, plat err = utils.FileWrite(filepath.Join(bindingDir, data.Key), bindingContent, 0644) if err != nil { - return errors.Wrap(err, "failed to write binding") + return fmt.Errorf("failed to write binding: %w", err) } return nil @@ -170,7 +171,7 @@ func validateBinding(name string, data bindingData) error { err := data.validate() if err != nil { - return errors.Wrapf(err, "failed to validate binding '%s'", name) + return fmt.Errorf("failed to validate binding '%s': %w", name, err) } return nil } @@ -183,7 +184,7 @@ func toTyped(rawMap map[string]interface{}) (bindings, error) { b, err := fromRaw(rawBinding) if err != nil { - return nil, errors.Wrapf(err, "could not process binding '%s'", name) + return nil, fmt.Errorf("could not process binding '%s': %w", name, err) } if b.Key != "" { @@ -220,10 +221,10 @@ func fromRaw(rawData interface{}) (binding, error) { if err == nil { err = e } else { - err = errors.Wrap(err, e.Error()) + err = fmt.Errorf("%s: %w", e.Error(), err) } } - err = errors.Wrap(err, "validation error") + err = fmt.Errorf("validation error: %w", err) return binding{}, err } diff --git a/pkg/cnbutils/buildpack.go b/pkg/cnbutils/buildpack.go index 8b744206d..3a41dc313 100644 --- a/pkg/cnbutils/buildpack.go +++ b/pkg/cnbutils/buildpack.go @@ -3,11 +3,11 @@ package cnbutils import ( "encoding/json" + "fmt" "os" "path/filepath" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const bpCacheDir = "/tmp/buildpacks_cache" @@ -34,23 +34,23 @@ func DownloadBuildpacks(path string, bpacks []string, dockerCreds string, utils err := utils.MkdirAll(bpCacheDir, os.ModePerm) if err != nil { - return errors.Wrap(err, "failed to create temp directory for buildpack cache") + return fmt.Errorf("failed to create temp directory for buildpack cache: %w", err) } for _, bpack := range bpacks { imageInfo, err := utils.GetRemoteImageInfo(bpack) if err != nil { - return errors.Wrap(err, "failed to get remote image info of buildpack") + return fmt.Errorf("failed to get remote image info of buildpack: %w", err) } hash, err := imageInfo.Digest() if err != nil { - return errors.Wrap(err, "failed to get image digest") + return fmt.Errorf("failed to get image digest: %w", err) } cacheDir := filepath.Join(bpCacheDir, hash.String()) cacheExists, err := utils.DirExists(cacheDir) if err != nil { - return errors.Wrapf(err, "failed to check if cache dir '%s' exists", cacheDir) + return fmt.Errorf("failed to check if cache dir '%s' exists: %w", cacheDir, err) } if cacheExists { @@ -58,13 +58,13 @@ func DownloadBuildpacks(path string, bpacks []string, dockerCreds string, utils } else { err := utils.MkdirAll(cacheDir, os.ModePerm) if err != nil { - return errors.Wrap(err, "failed to create temp directory for buildpack cache") + return fmt.Errorf("failed to create temp directory for buildpack cache: %w", err) } log.Entry().Infof("Downloading buildpack '%s' to %s", bpack, cacheDir) _, err = utils.DownloadImageContent(bpack, cacheDir) if err != nil { - return errors.Wrapf(err, "failed download buildpack image '%s'", bpack) + return fmt.Errorf("failed download buildpack image '%s': %w", bpack, err) } } @@ -96,7 +96,7 @@ func GetMetadata(bpacks []string, utils BuildUtils) ([]BuildPackMetadata, error) imgConf, err := imageInfo.ConfigFile() if err != nil { - return nil, errors.Wrapf(err, "failed to read '%s' image config", bpack) + return nil, fmt.Errorf("failed to read '%s' image config: %w", bpack, err) } err = json.Unmarshal([]byte(imgConf.Config.Labels["io.buildpacks.buildpackage.metadata"]), &bpackMeta) diff --git a/pkg/cnbutils/copy_project.go b/pkg/cnbutils/copy_project.go index d7f423820..a8eaa2b13 100644 --- a/pkg/cnbutils/copy_project.go +++ b/pkg/cnbutils/copy_project.go @@ -1,6 +1,7 @@ package cnbutils import ( + "fmt" "io/fs" "os" "path" @@ -8,7 +9,7 @@ import ( "strings" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" + ignore "github.com/sabhiram/go-gitignore" ) @@ -61,7 +62,7 @@ func CopyProject(source, target string, include, exclude *ignore.GitIgnore, util relPath, err := filepath.Rel(source, sourceFile) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Calculating relative path for '%s' failed", sourceFile) + return fmt.Errorf("Calculating relative path for '%s' failed: %w", sourceFile, err) } if !isIgnored(relPath, include, exclude) { @@ -91,14 +92,14 @@ func CopyProject(source, target string, include, exclude *ignore.GitIgnore, util err = utils.MkdirAll(target, os.ModePerm) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Creating directory '%s' failed", target) + return fmt.Errorf("Creating directory '%s' failed: %w", target, err) } } else { log.Entry().Debugf("Copying '%s' to '%s'", sourceFile, target) err = copyFile(sourceFile, target, utils) if err != nil { log.SetErrorCategory(log.ErrorBuild) - return errors.Wrapf(err, "Copying '%s' to '%s' failed", sourceFile, target) + return fmt.Errorf("Copying '%s' to '%s' failed: %w", sourceFile, target, err) } } } diff --git a/pkg/cnbutils/project/descriptor.go b/pkg/cnbutils/project/descriptor.go index 620b27c79..2c3f4d123 100644 --- a/pkg/cnbutils/project/descriptor.go +++ b/pkg/cnbutils/project/descriptor.go @@ -2,7 +2,8 @@ package project import ( - "github.com/pkg/errors" + "errors" + "fmt" "github.com/BurntSushi/toml" "github.com/SAP/jenkins-library/pkg/cnbutils" @@ -49,7 +50,7 @@ func ParseDescriptor(descriptorPath string, utils cnbutils.BuildUtils, httpClien var versionDescriptor versionDescriptor _, err = toml.Decode(string(descriptorContent), &versionDescriptor) if err != nil { - return &Descriptor{}, errors.Wrapf(err, "parsing schema version") + return &Descriptor{}, fmt.Errorf("parsing schema version: %w", err) } version := versionDescriptor.Project.Version diff --git a/pkg/cnbutils/target_image.go b/pkg/cnbutils/target_image.go index 31f6b5bc8..41ae86142 100644 --- a/pkg/cnbutils/target_image.go +++ b/pkg/cnbutils/target_image.go @@ -7,8 +7,9 @@ import ( "regexp" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/piperenv" - "github.com/pkg/errors" ) type TargetImage struct { @@ -32,7 +33,7 @@ func GetTargetImage(imageRegistry, imageName, imageTag, projectID, envRootPath s url, err := url.ParseRequestURI(imageRegistry) if err != nil { - return nil, errors.Wrap(err, "invalid registry url") + return nil, fmt.Errorf("invalid registry url: %w", err) } targetImage.ContainerRegistry = url diff --git a/pkg/cnbutils/user.go b/pkg/cnbutils/user.go index 189f8a15f..e92a70588 100644 --- a/pkg/cnbutils/user.go +++ b/pkg/cnbutils/user.go @@ -4,7 +4,7 @@ import ( "os" "strconv" - "github.com/pkg/errors" + "errors" ) func CnbUserInfo() (int, int, error) { diff --git a/pkg/codeql/reporting.go b/pkg/codeql/reporting.go index 7e65c4fa2..245418e00 100644 --- a/pkg/codeql/reporting.go +++ b/pkg/codeql/reporting.go @@ -5,10 +5,11 @@ import ( "fmt" "path/filepath" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/toolrecord" - "github.com/pkg/errors" ) type CodeqlAudit struct { @@ -33,13 +34,13 @@ func WriteJSONReport(jsonReport CodeqlAudit, modulePath string) ([]piperutils.Pa reportsDirectory := filepath.Join(modulePath, "codeql") jsonComplianceReportPath := filepath.Join(reportsDirectory, "piper_codeql_report.json") if err := utils.MkdirAll(reportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } file, _ := json.Marshal(jsonReport) if err := utils.FileWrite(jsonComplianceReportPath, file, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write codeql json compliance report") + return reportPaths, fmt.Errorf("failed to write codeql json compliance report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Codeql JSON Compliance Report", Target: jsonComplianceReportPath}) diff --git a/pkg/codeql/sarif_upload_test.go b/pkg/codeql/sarif_upload_test.go index 5b67c9997..15099e5e3 100644 --- a/pkg/codeql/sarif_upload_test.go +++ b/pkg/codeql/sarif_upload_test.go @@ -4,7 +4,8 @@ import ( "testing" "time" - "github.com/pkg/errors" + "errors" + "github.com/stretchr/testify/assert" ) diff --git a/pkg/command/command.go b/pkg/command/command.go index 521d47ac2..7325a6bcc 100644 --- a/pkg/command/command.go +++ b/pkg/command/command.go @@ -12,7 +12,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) // Command defines the information required for executing a call to any executable @@ -118,7 +117,7 @@ func (c *Command) RunShell(shell, script string) error { log.Entry().Infof("running shell script: %v %v", shell, script) if err := c.runCmd(cmd); err != nil { - return errors.Wrapf(err, "running shell script failed with %v", shell) + return fmt.Errorf("running shell script failed with %v: %w", shell, err) } return nil } @@ -154,7 +153,7 @@ func (c *Command) RunExecutableWithAttrs(executable string, sysProcAttr *syscall } if err := c.runCmd(cmd); err != nil { - return errors.Wrapf(err, "running command '%v' failed", executable) + return fmt.Errorf("running command '%v' failed: %w", executable, err) } return nil } @@ -182,7 +181,7 @@ func (c *Command) RunExecutableInBackground(executable string, params ...string) execution, err := c.startCmd(cmd) if err != nil { - return nil, errors.Wrapf(err, "starting command '%v' failed", executable) + return nil, fmt.Errorf("starting command '%v' failed: %w", executable, err) } return execution, nil @@ -222,12 +221,12 @@ func appendEnvironment(cmd *exec.Cmd, env []string) { func (c *Command) startCmd(cmd *exec.Cmd) (*execution, error) { stdout, stderr, err := cmdPipes(cmd) if err != nil { - return nil, errors.Wrap(err, "getting command pipes failed") + return nil, fmt.Errorf("getting command pipes failed: %w", err) } err = cmd.Start() if err != nil { - return nil, errors.Wrap(err, "starting command failed") + return nil, fmt.Errorf("starting command failed: %w", err) } execution := execution{cmd: cmd, ul: log.NewURLLogger(c.StepName)} @@ -371,7 +370,7 @@ func (c *Command) runCmd(cmd *exec.Cmd) error { c.exitCode = status.ExitStatus() } } - return errors.Wrap(err, "cmd.Run() failed") + return fmt.Errorf("cmd.Run() failed: %w", err) } c.exitCode = 0 return nil @@ -393,12 +392,12 @@ func (c *Command) prepareOut() { func cmdPipes(cmd *exec.Cmd) (io.ReadCloser, io.ReadCloser, error) { stdout, err := cmd.StdoutPipe() if err != nil { - return nil, nil, errors.Wrap(err, "getting Stdout pipe failed") + return nil, nil, fmt.Errorf("getting Stdout pipe failed: %w", err) } stderr, err := cmd.StderrPipe() if err != nil { - return nil, nil, errors.Wrap(err, "getting Stderr pipe failed") + return nil, nil, fmt.Errorf("getting Stderr pipe failed: %w", err) } return stdout, stderr, nil diff --git a/pkg/command/execution.go b/pkg/command/execution.go index 85636e1c4..407024007 100644 --- a/pkg/command/execution.go +++ b/pkg/command/execution.go @@ -1,9 +1,10 @@ package command import ( - "github.com/SAP/jenkins-library/pkg/log" "os/exec" "sync" + + "github.com/SAP/jenkins-library/pkg/log" ) // errCopyStdout and errCopyStderr are filled after the command execution after Wait() terminates diff --git a/pkg/config/config.go b/pkg/config/config.go index 99e7dda7b..0b604a996 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -18,7 +18,6 @@ import ( "github.com/ghodss/yaml" "github.com/google/go-cmp/cmp" - "github.com/pkg/errors" ) // Config defines the structure of the config files @@ -48,7 +47,7 @@ func (c *Config) ReadConfig(configuration io.ReadCloser) error { content, err := io.ReadAll(configuration) if err != nil { - return errors.Wrapf(err, "error reading %v", configuration) + return fmt.Errorf("error reading %v: %w", configuration, err) } err = yaml.Unmarshal(content, &c) @@ -149,7 +148,7 @@ func (c *Config) copyStepAliasConfig(stepName string, stepAliases []Alias) { func (c *Config) InitializeConfig(configuration io.ReadCloser, defaults []io.ReadCloser, ignoreCustomDefaults bool) error { if configuration != nil { if err := c.ReadConfig(configuration); err != nil { - return errors.Wrap(err, "failed to parse custom pipeline configuration") + return fmt.Errorf("failed to parse custom pipeline configuration: %w", err) } } @@ -163,14 +162,14 @@ func (c *Config) InitializeConfig(configuration io.ReadCloser, defaults []io.Rea for _, f := range c.CustomDefaults { fc, err := c.openFile(f, c.accessTokens) if err != nil { - return errors.Wrapf(err, "getting default '%v' failed", f) + return fmt.Errorf("getting default '%v' failed: %w", f, err) } defaults = append(defaults, fc) } } if err := c.defaults.ReadPipelineDefaults(defaults); err != nil { - return errors.Wrap(err, "failed to read default configuration") + return fmt.Errorf("failed to read default configuration: %w", err) } c.initialized = true return nil @@ -373,7 +372,7 @@ func (c *Config) GetStageConfig(paramJSON string, configuration io.ReadCloser, d func GetJSON(data interface{}) (string, error) { result, err := json.Marshal(data) if err != nil { - return "", errors.Wrapf(err, "error marshalling json: %v", err) + return "", fmt.Errorf("error marshalling json: %v: %w", err, err) } return string(result), nil } @@ -382,7 +381,7 @@ func GetJSON(data interface{}) (string, error) { func GetYAML(data interface{}) (string, error) { result, err := yaml.Marshal(data) if err != nil { - return "", errors.Wrapf(err, "error marshalling yaml: %v", err) + return "", fmt.Errorf("error marshalling yaml: %v: %w", err, err) } return string(result), nil } @@ -390,7 +389,7 @@ func GetYAML(data interface{}) (string, error) { // OpenPiperFile provides functionality to retrieve configuration via file or http func OpenPiperFile(name string, accessTokens map[string]string) (io.ReadCloser, error) { if len(name) == 0 { - return nil, errors.Wrap(os.ErrNotExist, "no filename provided") + return nil, fmt.Errorf("no filename provided: %w", os.ErrNotExist) } if !strings.HasPrefix(name, "http://") && !strings.HasPrefix(name, "https://") { diff --git a/pkg/config/defaults.go b/pkg/config/defaults.go index fa357793b..df9e1ef4d 100644 --- a/pkg/config/defaults.go +++ b/pkg/config/defaults.go @@ -5,7 +5,6 @@ import ( "io" "github.com/ghodss/yaml" - "github.com/pkg/errors" ) // PipelineDefaults defines the structure of the pipeline defaults @@ -28,7 +27,7 @@ func (d *PipelineDefaults) ReadPipelineDefaults(defaultSources []io.ReadCloser) content, err := io.ReadAll(def) if err != nil { - return errors.Wrapf(err, "error reading %v", def) + return fmt.Errorf("error reading %v: %w", def, err) } err = yaml.Unmarshal(content, &c) diff --git a/pkg/config/evaluation.go b/pkg/config/evaluation.go index af90ac905..1f8bf2909 100644 --- a/pkg/config/evaluation.go +++ b/pkg/config/evaluation.go @@ -7,8 +7,6 @@ import ( "slices" "strings" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/orchestrator" "github.com/SAP/jenkins-library/pkg/piperutils" @@ -135,7 +133,7 @@ func (s *StepCondition) evaluateV1( if s.Config != nil { if len(s.Config) > 1 { - return false, errors.Errorf("only one config key allowed per condition but %v provided", len(s.Config)) + return false, fmt.Errorf("only one config key allowed per condition but %v provided", len(s.Config)) } // for loop will only cover first entry since we throw an error in case there is more than one config key defined already above @@ -157,7 +155,7 @@ func (s *StepCondition) evaluateV1( if len(s.FilePattern) > 0 { files, err := utils.Glob(s.FilePattern) if err != nil { - return false, errors.Wrap(err, "failed to check filePattern condition") + return false, fmt.Errorf("failed to check filePattern condition: %w", err) } if len(files) > 0 { return true, nil @@ -173,7 +171,7 @@ func (s *StepCondition) evaluateV1( } files, err := utils.Glob(configValue) if err != nil { - return false, errors.Wrap(err, "failed to check filePatternFromConfig condition") + return false, fmt.Errorf("failed to check filePatternFromConfig condition: %w", err) } if len(files) > 0 { return true, nil @@ -261,7 +259,7 @@ func checkConfigKeyV1(config map[string]interface{}, configKey []string) (bool, func checkForNpmScriptsInPackagesV1(npmScript string, config StepConfig, utils piperutils.FileUtils) (bool, error) { packages, err := utils.Glob("**/package.json") if err != nil { - return false, errors.Wrap(err, "failed to check if file-exists") + return false, fmt.Errorf("failed to check if file-exists: %w", err) } for _, pack := range packages { packDirs := strings.Split(path.Dir(pack), "/") @@ -278,11 +276,11 @@ func checkForNpmScriptsInPackagesV1(npmScript string, config StepConfig, utils p jsonFile, err := utils.FileRead(pack) if err != nil { - return false, errors.Errorf("failed to open file %s: %v", pack, err) + return false, fmt.Errorf("failed to open file %s: %v", pack, err) } packageJSON := map[string]interface{}{} if err := json.Unmarshal(jsonFile, &packageJSON); err != nil { - return false, errors.Errorf("failed to unmarshal json file %s: %v", pack, err) + return false, fmt.Errorf("failed to unmarshal json file %s: %v", pack, err) } npmScripts, ok := packageJSON["scripts"] if !ok { @@ -290,7 +288,7 @@ func checkForNpmScriptsInPackagesV1(npmScript string, config StepConfig, utils p } scriptsMap, ok := npmScripts.(map[string]interface{}) if !ok { - return false, errors.Errorf("failed to read scripts from package.json: %T", npmScripts) + return false, fmt.Errorf("failed to read scripts from package.json: %T", npmScripts) } if _, ok := scriptsMap[npmScript]; ok { return true, nil diff --git a/pkg/config/run.go b/pkg/config/run.go index f65c4e23c..99f1e6ecc 100644 --- a/pkg/config/run.go +++ b/pkg/config/run.go @@ -6,7 +6,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/ghodss/yaml" - "github.com/pkg/errors" ) // RunConfig ... @@ -123,12 +122,12 @@ func (r *RunConfigV1) LoadConditionsV1() error { defer r.StageConfigFile.Close() content, err := io.ReadAll(r.StageConfigFile) if err != nil { - return errors.Wrapf(err, "error: failed to read the stageConfig file") + return fmt.Errorf("error: failed to read the stageConfig file: %w", err) } err = yaml.Unmarshal(content, &r.PipelineConfig) if err != nil { - return errors.Errorf("format of configuration is invalid %q: %v", content, err) + return fmt.Errorf("format of configuration is invalid %q: %v", content, err) } return nil } diff --git a/pkg/config/stepmeta.go b/pkg/config/stepmeta.go index 739d20dd7..dc9f19255 100644 --- a/pkg/config/stepmeta.go +++ b/pkg/config/stepmeta.go @@ -9,8 +9,9 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperenv" + "errors" + "github.com/ghodss/yaml" - "github.com/pkg/errors" ) const SupportedVolumeName = "volume" @@ -174,12 +175,12 @@ func (m *StepData) ReadPipelineStepData(metadata io.ReadCloser) error { defer metadata.Close() content, err := io.ReadAll(metadata) if err != nil { - return errors.Wrapf(err, "error reading %v", metadata) + return fmt.Errorf("error reading %v: %w", metadata, err) } err = yaml.Unmarshal(content, &m) if err != nil { - return errors.Wrapf(err, "error unmarshalling: %v", err) + return fmt.Errorf("error unmarshalling: %v: %w", err, err) } return nil } @@ -400,7 +401,7 @@ func (m *StepData) GetContextDefaults(stepName string) (io.ReadCloser, error) { JSON, err := yaml.Marshal(c) if err != nil { - return nil, errors.Wrap(err, "failed to create context defaults") + return nil, fmt.Errorf("failed to create context defaults: %w", err) } r := io.NopCloser(bytes.NewReader(JSON)) @@ -542,12 +543,12 @@ func ResolveMetadata(gitHubTokens map[string]string, metaDataResolver func() map if stepMetadata != "" { metadataFile, err := OpenPiperFile(stepMetadata, gitHubTokens) if err != nil { - return metadata, errors.Wrap(err, "open failed") + return metadata, fmt.Errorf("open failed: %w", err) } err = metadata.ReadPipelineStepData(metadataFile) if err != nil { - return metadata, errors.Wrap(err, "read failed") + return metadata, fmt.Errorf("read failed: %w", err) } } else { if stepName != "" { @@ -558,10 +559,10 @@ func ResolveMetadata(gitHubTokens map[string]string, metaDataResolver func() map var ok bool metadata, ok = metadataMap[stepName] if !ok { - return metadata, errors.Errorf("could not retrieve by stepName %v", stepName) + return metadata, fmt.Errorf("could not retrieve by stepName %v", stepName) } } else { - return metadata, errors.Errorf("either one of stepMetadata or stepName parameter has to be passed") + return metadata, fmt.Errorf("either one of stepMetadata or stepName parameter has to be passed") } } return metadata, nil diff --git a/pkg/config/validation/validation_test.go b/pkg/config/validation/validation_test.go index f30fb37f1..04c666aea 100644 --- a/pkg/config/validation/validation_test.go +++ b/pkg/config/validation/validation_test.go @@ -4,8 +4,9 @@ package validation import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) type Connection struct { diff --git a/pkg/contrast/reporting.go b/pkg/contrast/reporting.go index d53470155..9845a06e2 100644 --- a/pkg/contrast/reporting.go +++ b/pkg/contrast/reporting.go @@ -1,12 +1,12 @@ package contrast import ( + "fmt" "path/filepath" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/toolrecord" - "github.com/pkg/errors" ) type ContrastAudit struct { @@ -73,11 +73,11 @@ func SaveReportFile(utils piperutils.FileUtils, fileName, displayName string, da reportPath := filepath.Join(reportsDirectory, fileName) if err := utils.MkdirAll(reportsDirectory, 0777); err != nil { - return nil, errors.Wrap(err, "failed to create contrast directory") + return nil, fmt.Errorf("failed to create contrast directory: %w", err) } if err := utils.FileWrite(reportPath, data, 0644); err != nil { - return nil, errors.Wrapf(err, "failed to write %s file", fileName) + return nil, fmt.Errorf("failed to write %s file: %w", fileName, err) } log.Entry().Infof("Report saved to %s", reportPath) diff --git a/pkg/contrast/request.go b/pkg/contrast/request.go index 35d03a49c..3aeed4c6d 100644 --- a/pkg/contrast/request.go +++ b/pkg/contrast/request.go @@ -2,12 +2,12 @@ package contrast import ( "encoding/json" + "fmt" "io" "net/http" "time" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) type ContrastHttpClient interface { @@ -29,22 +29,22 @@ func NewContrastHttpClient(apiKey, auth string) *ContrastHttpClientInstance { func (c *ContrastHttpClientInstance) ExecuteRequest(url string, params map[string]string, dest interface{}) error { req, err := newHttpRequest(url, c.apiKey, c.auth, params) if err != nil { - return errors.Wrap(err, "failed to create request") + return fmt.Errorf("failed to create request: %w", err) } log.Entry().Debugf("GET call request to: %s", url) response, err := performRequest(req) if response != nil && response.StatusCode != http.StatusOK { - return errors.Errorf("failed to perform request, status code: %v and status %v", response.StatusCode, response.Status) + return fmt.Errorf("failed to perform request, status code: %v and status %v", response.StatusCode, response.Status) } if err != nil { - return errors.Wrap(err, "failed to perform request") + return fmt.Errorf("failed to perform request: %w", err) } defer response.Body.Close() err = parseJsonResponse(response, dest) if err != nil { - return errors.Wrap(err, "failed to parse JSON response") + return fmt.Errorf("failed to parse JSON response: %w", err) } return nil } diff --git a/pkg/cpi/commonUtils.go b/pkg/cpi/commonUtils.go index 0c6dde42a..723c4a8f8 100644 --- a/pkg/cpi/commonUtils.go +++ b/pkg/cpi/commonUtils.go @@ -13,7 +13,6 @@ import ( "github.com/Jeffail/gabs/v2" piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/pkg/errors" ) // CommonUtils for CPI @@ -69,7 +68,7 @@ func ReadCpiServiceKey(serviceKeyJSON string) (cpiServiceKey ServiceKey, err err // parse err = json.Unmarshal([]byte(serviceKeyJSON), &cpiServiceKey) if err != nil { - err = errors.Wrap(err, "error unmarshalling serviceKey") + err = fmt.Errorf("error unmarshalling serviceKey: %w", err) return } @@ -94,27 +93,27 @@ func (tokenParameters TokenParameters) GetBearerToken() (string, error) { method := "POST" resp, httpErr := httpClient.SendRequest(method, tokenFinalURL, nil, header, nil) if httpErr != nil { - return "", errors.Wrapf(httpErr, "HTTP %v request to %v failed with error", method, tokenFinalURL) + return "", fmt.Errorf("HTTP %v request to %v failed with error: %w", method, tokenFinalURL, httpErr) } if resp != nil && resp.Body != nil { defer resp.Body.Close() } if resp == nil { - return "", errors.Errorf("did not retrieve a HTTP response") + return "", fmt.Errorf("did not retrieve a HTTP response") } if resp.StatusCode != 200 { - return "", errors.Errorf("did not retrieve a valid HTTP response code: %v", httpErr) + return "", fmt.Errorf("did not retrieve a valid HTTP response code: %v", httpErr) } bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return "", errors.Wrap(readErr, "HTTP response body could not be read") + return "", fmt.Errorf("HTTP response body could not be read: %w", readErr) } jsonResponse, parsingErr := gabs.ParseJSON([]byte(bodyText)) if parsingErr != nil { - return "", errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return "", fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), parsingErr) } token := jsonResponse.Path("access_token").Data().(string) return token, nil @@ -126,7 +125,7 @@ func (httpFileDownloadRequestParameters HttpFileDownloadRequestParameters) Handl contentDisposition := response.Header.Get("Content-Disposition") disposition, params, err := mime.ParseMediaType(contentDisposition) if err != nil { - return errors.Wrapf(err, "failed to read filename from http response headers, Content-Disposition %s", disposition) + return fmt.Errorf("failed to read filename from http response headers, Content-Disposition %s: %w", disposition, err) } filename := params["filename"] @@ -139,13 +138,13 @@ func (httpFileDownloadRequestParameters HttpFileDownloadRequestParameters) Handl err = os.MkdirAll(workspaceRelativePath, 0755) // handling error while creating a workspce directoy for file download, if one not exist already! if err != nil { - return errors.Wrapf(err, "Failed to create workspace directory") + return fmt.Errorf("Failed to create workspace directory: %w", err) } zipFileName := filepath.Join(workspaceRelativePath, filename) file, err := os.Create(zipFileName) // handling error while creating a file in the filesystem if err != nil { - return errors.Wrap(err, "failed to create zip archive of api proxy") + return fmt.Errorf("failed to create zip archive of api proxy: %w", err) } _, err = io.Copy(file, response.Body) if err != nil { @@ -155,10 +154,10 @@ func (httpFileDownloadRequestParameters HttpFileDownloadRequestParameters) Handl } responseBody, readErr := io.ReadAll(response.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", response.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", response.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code : %v", responseBody, response.StatusCode) - return errors.Errorf("%s, Response Status code: %v", httpFileDownloadRequestParameters.ErrMessage, response.StatusCode) + return fmt.Errorf("%s, Response Status code: %v", httpFileDownloadRequestParameters.ErrMessage, response.StatusCode) } // HandleHTTPFileUploadResponse - Handle the file upload response @@ -170,7 +169,7 @@ func (httpFileUploadRequestParameters HttpFileUploadRequestParameters) HandleHTT } if response == nil { - return errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } responseCode := response.StatusCode @@ -183,12 +182,12 @@ func (httpFileUploadRequestParameters HttpFileUploadRequestParameters) HandleHTT if httpErr != nil { responseBody, readErr := io.ReadAll(response.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", response.StatusCode) + return fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", response.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), response.StatusCode) - return errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpFileUploadRequestParameters.HTTPMethod, httpFileUploadRequestParameters.HTTPURL, string(responseBody)) + return fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpFileUploadRequestParameters.HTTPMethod, httpFileUploadRequestParameters.HTTPURL, string(responseBody), httpErr) } - return errors.Errorf("%s, Response Status code: %v", httpFileUploadRequestParameters.ErrMessage, response.StatusCode) + return fmt.Errorf("%s, Response Status code: %v", httpFileUploadRequestParameters.ErrMessage, response.StatusCode) } // HandleHTTPGetRequestResponse - Handle the GET Request response data @@ -200,22 +199,22 @@ func (httpGetRequestParameters HttpFileUploadRequestParameters) HandleHTTPGetReq } if response == nil { - return "", errors.Errorf("did not retrieve a HTTP response: %v", httpErr) + return "", fmt.Errorf("did not retrieve a HTTP response: %v", httpErr) } if response.StatusCode == http.StatusOK { responseBody, readErr := io.ReadAll(response.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, response status code: %v", response.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, response status code: %v: %w", response.StatusCode, readErr) } return string(responseBody), nil } if httpErr != nil { responseBody, readErr := io.ReadAll(response.Body) if readErr != nil { - return "", errors.Wrapf(readErr, "HTTP response body could not be read, Response status code: %v", response.StatusCode) + return "", fmt.Errorf("HTTP response body could not be read, Response status code: %v: %w", response.StatusCode, readErr) } log.Entry().Errorf("a HTTP error occurred! Response body: %v, Response status code: %v", string(responseBody), response.StatusCode) - return "", errors.Wrapf(httpErr, "HTTP %v request to %v failed with error: %v", httpGetRequestParameters.HTTPMethod, httpGetRequestParameters.HTTPURL, string(responseBody)) + return "", fmt.Errorf("HTTP %v request to %v failed with error: %v: %w", httpGetRequestParameters.HTTPMethod, httpGetRequestParameters.HTTPURL, string(responseBody), httpErr) } - return "", errors.Errorf("%s, Response Status code: %v", httpGetRequestParameters.ErrMessage, response.StatusCode) + return "", fmt.Errorf("%s, Response Status code: %v", httpGetRequestParameters.ErrMessage, response.StatusCode) } diff --git a/pkg/cpi/commonUtils_test.go b/pkg/cpi/commonUtils_test.go index 0e8795288..2146bc800 100644 --- a/pkg/cpi/commonUtils_test.go +++ b/pkg/cpi/commonUtils_test.go @@ -4,8 +4,9 @@ package cpi import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestReadCpiServiceKeyFile(t *testing.T) { diff --git a/pkg/cpi/mockingUtils.go b/pkg/cpi/mockingUtils.go index 50f4217ed..8025a4206 100644 --- a/pkg/cpi/mockingUtils.go +++ b/pkg/cpi/mockingUtils.go @@ -9,7 +9,7 @@ import ( "net/http" "strings" - "github.com/pkg/errors" + "errors" ) // GetCPIFunctionMockResponse -Generate mock response payload for different CPI functions diff --git a/pkg/docker/container.go b/pkg/docker/container.go index 5dd903e95..a183b6280 100644 --- a/pkg/docker/container.go +++ b/pkg/docker/container.go @@ -7,14 +7,13 @@ import ( "strings" containerName "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" ) // ContainerRegistryFromURL provides the registry part of a complete registry url including the port func ContainerRegistryFromURL(registryURL string) (string, error) { u, err := url.ParseRequestURI(registryURL) if err != nil { - return "", errors.Wrap(err, "invalid registry url") + return "", fmt.Errorf("invalid registry url: %w", err) } if len(u.Host) == 0 { return "", fmt.Errorf("invalid registry url") @@ -26,7 +25,7 @@ func ContainerRegistryFromURL(registryURL string) (string, error) { func ContainerRegistryFromImage(fullImage string) (string, error) { ref, err := containerName.ParseReference(strings.ToLower(fullImage)) if err != nil { - return "", errors.Wrap(err, "failed to parse image name") + return "", fmt.Errorf("failed to parse image name: %w", err) } return ref.Context().RegistryStr(), nil } @@ -35,7 +34,7 @@ func ContainerRegistryFromImage(fullImage string) (string, error) { func ContainerImageNameTagFromImage(fullImage string) (string, error) { ref, err := containerName.ParseReference(strings.ToLower(fullImage)) if err != nil { - return "", errors.Wrap(err, "failed to parse image name") + return "", fmt.Errorf("failed to parse image name: %w", err) } registryOnly := fmt.Sprintf("%v/", ref.Context().RegistryStr()) return strings.ReplaceAll(fullImage, registryOnly, ""), nil diff --git a/pkg/docker/docker.go b/pkg/docker/docker.go index ac8f25728..e20b9889e 100644 --- a/pkg/docker/docker.go +++ b/pkg/docker/docker.go @@ -20,7 +20,6 @@ import ( "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" @@ -39,13 +38,13 @@ func MergeDockerConfigJSON(sourcePath, targetPath string, utils piperutils.FileU sourceReader, err := utils.Open(sourcePath) if err != nil { - return errors.Wrapf(err, "failed to open file %q", sourcePath) + return fmt.Errorf("failed to open file %q: %w", sourcePath, err) } defer sourceReader.Close() sourceConfig, err := config.LoadFromReader(sourceReader) if err != nil { - return errors.Wrapf(err, "failed to read file %q", sourcePath) + return fmt.Errorf("failed to read file %q: %w", sourcePath, err) } var targetConfig *configfile.ConfigFile @@ -55,12 +54,12 @@ func MergeDockerConfigJSON(sourcePath, targetPath string, utils piperutils.FileU } else { targetReader, err := utils.Open(targetPath) if err != nil { - return errors.Wrapf(err, "failed to open file %q", targetReader) + return fmt.Errorf("failed to open file %q: %w", targetReader, err) } defer targetReader.Close() targetConfig, err = config.LoadFromReader(targetReader) if err != nil { - return errors.Wrapf(err, "failed to read file %q", targetPath) + return fmt.Errorf("failed to read file %q: %w", targetPath, err) } } @@ -71,7 +70,7 @@ func MergeDockerConfigJSON(sourcePath, targetPath string, utils piperutils.FileU buf := bytes.NewBuffer(nil) err = targetConfig.SaveToWriter(buf) if err != nil { - return errors.Wrapf(err, "failed to save file %q", targetPath) + return fmt.Errorf("failed to save file %q: %w", targetPath, err) } err = utils.MkdirAll(filepath.Dir(targetPath), 0777) @@ -265,7 +264,7 @@ func (c *Client) DownloadImage(imageSource, targetFile string) (v1.Image, error) func (c *Client) GetRemoteImageInfo(imageSource string) (v1.Image, error) { ref, err := c.getImageRef(imageSource) if err != nil { - return nil, errors.Wrap(err, "parsing image reference") + return nil, fmt.Errorf("parsing image reference: %w", err) } return remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain)) diff --git a/pkg/events/events.go b/pkg/events/events.go index 71fcc5068..0ee3a074b 100644 --- a/pkg/events/events.go +++ b/pkg/events/events.go @@ -3,11 +3,11 @@ package events import ( "bytes" "encoding/json" + "fmt" "time" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/google/uuid" - "github.com/pkg/errors" ) // type EventType string @@ -40,7 +40,7 @@ func (e Event) CreateWithJSONData(data string, opts ...Option) (Event, error) { if data != "" { err := json.Unmarshal([]byte(data), &dataMap) if err != nil { - return e, errors.Wrap(err, "eventData is an invalid JSON") + return e, fmt.Errorf("eventData is an invalid JSON: %w", err) } } return e.Create(dataMap, opts...), nil @@ -74,7 +74,7 @@ func GetUUID(pipelineIdentifier string) string { func (e Event) ToBytes() ([]byte, error) { data, err := json.Marshal(e.cloudEvent) if err != nil { - return nil, errors.Wrap(err, "failed to marshal event data") + return nil, fmt.Errorf("failed to marshal event data: %w", err) } return data, nil } @@ -97,13 +97,13 @@ func (e *Event) AddToCloudEventData(additionalDataString string) error { var additionalData map[string]interface{} err := json.Unmarshal([]byte(additionalDataString), &additionalData) if err != nil { - errors.Wrap(err, "couldn't add additional data to cloud event") + return fmt.Errorf("couldn't add additional data to cloud event: %w", err) } var newEventData map[string]interface{} err = json.Unmarshal(e.cloudEvent.DataEncoded, &newEventData) if err != nil { - errors.Wrap(err, "couldn't add additional data to cloud event") + return fmt.Errorf("couldn't add additional data to cloud event: %w", err) } for k, v := range additionalData { diff --git a/pkg/format/assessment.go b/pkg/format/assessment.go index 82ccd32f1..94fee323c 100644 --- a/pkg/format/assessment.go +++ b/pkg/format/assessment.go @@ -7,7 +7,6 @@ import ( cdx "github.com/CycloneDX/cyclonedx-go" "github.com/ghodss/yaml" "github.com/package-url/packageurl-go" - "github.com/pkg/errors" ) type Assessment struct { @@ -114,7 +113,7 @@ func ReadAssessments(assessmentFile io.ReadCloser) (*[]Assessment, error) { content, err := io.ReadAll(assessmentFile) if err != nil { - return nil, errors.Wrapf(err, "error reading %v", assessmentFile) + return nil, fmt.Errorf("error reading %v: %w", assessmentFile, err) } err = yaml.Unmarshal(content, &ignore) diff --git a/pkg/fortify/fortify.go b/pkg/fortify/fortify.go index 58952311d..656675108 100644 --- a/pkg/fortify/fortify.go +++ b/pkg/fortify/fortify.go @@ -34,7 +34,6 @@ import ( "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -220,13 +219,13 @@ func (sys *SystemInstance) GetProjectVersionDetailsByProjectIDAndVersionName(id // projectVersion not found for specified project id and name, check if autoCreate is enabled if !autoCreate { log.SetErrorCategory(log.ErrorConfiguration) - return nil, errors.New(fmt.Sprintf("Project version with name %v not found in project with ID %v and automatic creation not enabled", versionName, id)) + return nil, fmt.Errorf("Project version with name %v not found in project with ID %v and automatic creation not enabled", versionName, id) } log.Entry().Debugf("Could not find project version with name %v under project %v auto-creating one now...", versionName, projectName) version, err := sys.CreateProjectVersionIfNotExist(projectName, versionName, "Created by Go script") if err != nil { - return nil, errors.Wrapf(err, "failed to auto-create project version: %v for project %v", versionName, projectName) + return nil, fmt.Errorf("failed to auto-create project version: %v for project %v: %w", versionName, projectName, err) } log.Entry().Debugf("Successfully created project version %v for project %v", versionName, projectName) return version, nil @@ -265,11 +264,11 @@ func (sys *SystemInstance) CreateProjectVersionIfNotExist(projectName, projectVe } projectVersion, err := sys.CreateProjectVersion(projectVersionDto) if err != nil { - return nil, errors.Wrapf(err, "Failed to create new project version %v for projectName %v", projectVersionName, projectName) + return nil, fmt.Errorf("Failed to create new project version %v for projectName %v: %w", projectVersionName, projectName, err) } _, err = sys.CommitProjectVersion(projectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to commit project version %v: %v", projectVersion.ID, err) + return nil, fmt.Errorf("Failed to commit project version %v: %v: %w", projectVersion.ID, err, err) } return projectVersion, nil } @@ -294,34 +293,34 @@ func (sys *SystemInstance) LookupOrCreateProjectVersionDetailsForPullRequest(pro projectVersion, err := sys.CreateProjectVersion(newVersion) if err != nil { - return nil, errors.Wrapf(err, "Failed to create new project version for pull request %v", pullRequestName) + return nil, fmt.Errorf("Failed to create new project version for pull request %v: %w", pullRequestName, err) } attributes, err := sys.GetProjectVersionAttributesByProjectVersionID(masterProjectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to load project version attributes for master project version %v", masterProjectVersion.ID) + return nil, fmt.Errorf("Failed to load project version attributes for master project version %v: %w", masterProjectVersion.ID, err) } for _, attribute := range attributes { attribute.ID = 0 } _, err = sys.SetProjectVersionAttributesByProjectVersionID(projectVersion.ID, attributes) if err != nil { - return nil, errors.Wrapf(err, "Failed to update project version attributes for pull request project version %v", projectVersion.ID) + return nil, fmt.Errorf("Failed to update project version attributes for pull request project version %v: %w", projectVersion.ID, err) } err = sys.ProjectVersionCopyFromPartial(masterProjectVersion.ID, projectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy from partial of project version %v to %v", masterProjectVersion.ID, projectVersion.ID) + return nil, fmt.Errorf("Failed to copy from partial of project version %v to %v: %w", masterProjectVersion.ID, projectVersion.ID, err) } _, err = sys.CommitProjectVersion(projectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to commit project version %v: %v", projectVersion.ID, err) + return nil, fmt.Errorf("Failed to commit project version %v: %v: %w", projectVersion.ID, err, err) } err = sys.ProjectVersionCopyCurrentState(masterProjectVersion.ID, projectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy current state of project version %v to %v", masterProjectVersion.ID, projectVersion.ID) + return nil, fmt.Errorf("Failed to copy current state of project version %v to %v: %w", masterProjectVersion.ID, projectVersion.ID, err) } err = sys.ProjectVersionCopyPermissions(masterProjectVersion.ID, projectVersion.ID) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy permissions of project version %v to %v", masterProjectVersion.ID, projectVersion.ID) + return nil, fmt.Errorf("Failed to copy permissions of project version %v to %v: %w", masterProjectVersion.ID, projectVersion.ID, err) } return projectVersion, nil } @@ -471,11 +470,11 @@ func (sys *SystemInstance) MergeProjectVersionStateOfPRIntoMaster(downloadEndpoi log.Entry().Debugf("Found project version with ID '%v', starting transfer", prProjectVersion.ID) data, err := sys.DownloadResultFile(downloadEndpoint, prProjectVersion.ID) if err != nil { - return errors.Wrapf(err, "Failed to download current state FPR of PR project version %v", prProjectVersion.ID) + return fmt.Errorf("Failed to download current state FPR of PR project version %v: %w", prProjectVersion.ID, err) } err = sys.uploadResultFileContent(uploadEndpoint, "prMergeTransfer.fpr", bytes.NewReader(data), masterProjectVersionID) if err != nil { - return errors.Wrapf(err, "Failed to upload PR project version state to master project version %v", masterProjectVersionID) + return fmt.Errorf("Failed to upload PR project version state to master project version %v: %w", masterProjectVersionID, err) } _, err = sys.inactivateProjectVersion(prProjectVersion.ID) if err != nil { @@ -707,7 +706,7 @@ func (sys *SystemInstance) getFileToken(tokenType string) (*models.FileToken, er func (sys *SystemInstance) UploadResultFile(endpoint, file string, projectVersionID int64) error { fileHandle, err := os.Open(file) if err != nil { - return errors.Wrapf(err, "Unable to locate file %v", file) + return fmt.Errorf("Unable to locate file %v: %w", file, err) } defer fileHandle.Close() @@ -744,7 +743,7 @@ func (sys *SystemInstance) uploadResultFileContent(endpoint, file string, fileCo func (sys *SystemInstance) downloadFile(endpoint, method, acceptType, tokenType string, fileID int64) ([]byte, error) { token, err := sys.getFileToken(tokenType) if err != nil { - return nil, errors.Wrap(err, "Error fetching file token") + return nil, fmt.Errorf("Error fetching file token: %w", err) } defer sys.invalidateFileTokens() @@ -769,7 +768,7 @@ func (sys *SystemInstance) downloadFile(endpoint, method, acceptType, tokenType data, err := io.ReadAll(response.Body) defer response.Body.Close() if err != nil { - return nil, errors.Wrap(err, "Error reading the response data") + return nil, fmt.Errorf("Error reading the response data: %w", err) } return data, nil } @@ -778,7 +777,7 @@ func (sys *SystemInstance) downloadFile(endpoint, method, acceptType, tokenType func (sys *SystemInstance) DownloadReportFile(endpoint string, reportID int64) ([]byte, error) { data, err := sys.downloadFile(endpoint, http.MethodGet, "application/octet-stream", "REPORT_FILE", reportID) if err != nil { - return nil, errors.Wrap(err, "Error downloading report file") + return nil, fmt.Errorf("Error downloading report file: %w", err) } return data, nil } @@ -787,7 +786,7 @@ func (sys *SystemInstance) DownloadReportFile(endpoint string, reportID int64) ( func (sys *SystemInstance) DownloadResultFile(endpoint string, projectVersionID int64) ([]byte, error) { data, err := sys.downloadFile(endpoint, http.MethodGet, "application/zip", "DOWNLOAD", projectVersionID) if err != nil { - return nil, errors.Wrap(err, "Error downloading result file") + return nil, fmt.Errorf("Error downloading result file: %w", err) } return data, nil } diff --git a/pkg/fortify/fpr_to_sarif_test.go b/pkg/fortify/fpr_to_sarif_test.go index 74b2473ed..65f995272 100644 --- a/pkg/fortify/fpr_to_sarif_test.go +++ b/pkg/fortify/fpr_to_sarif_test.go @@ -4,12 +4,13 @@ package fortify import ( - "github.com/SAP/jenkins-library/pkg/format" - "github.com/piper-validation/fortify-client-go/models" - "github.com/stretchr/testify/assert" "net/http" "strings" "testing" + + "github.com/SAP/jenkins-library/pkg/format" + "github.com/piper-validation/fortify-client-go/models" + "github.com/stretchr/testify/assert" ) func TestParse(t *testing.T) { diff --git a/pkg/fortify/reporting.go b/pkg/fortify/reporting.go index 866d34391..0312b10ce 100644 --- a/pkg/fortify/reporting.go +++ b/pkg/fortify/reporting.go @@ -17,8 +17,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" "github.com/piper-validation/fortify-client-go/models" - - "github.com/pkg/errors" ) type FortifyReportData struct { @@ -132,13 +130,13 @@ func WriteJSONReport(jsonReport FortifyReportData) ([]piperutils.Path, error) { jsonComplianceReportPath := filepath.Join(ReportsDirectory, "piper_fortify_report.json") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } file, _ := json.Marshal(jsonReport) if err := utils.FileWrite(jsonComplianceReportPath, file, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write fortify json compliance report") + return reportPaths, fmt.Errorf("failed to write fortify json compliance report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Fortify JSON Compliance Report", Target: jsonComplianceReportPath}) @@ -152,7 +150,7 @@ func WriteSarif(sarif format.SARIF, fileName string) ([]piperutils.Path, error) sarifReportPath := filepath.Join(ReportsDirectory, fileName) // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } // This solution did not allow for special HTML characters. If this causes any issue, revert l148-l157 with these two @@ -171,7 +169,7 @@ func WriteSarif(sarif format.SARIF, fileName string) ([]piperutils.Path, error) log.Entry().Info("Writing file to disk: ", sarifReportPath) if err := utils.FileWrite(sarifReportPath, buffer.Bytes(), 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write fortify SARIF report") + return reportPaths, fmt.Errorf("failed to write fortify SARIF report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Fortify SARIF Report", Target: sarifReportPath}) @@ -185,7 +183,7 @@ func WriteGzipSarif(sarif format.SARIF, fileName string) ([]piperutils.Path, err sarifReportPath := filepath.Join(ReportsDirectory, fileName) // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } // HTML characters will most likely be present: we need to use encode: create a buffer to hold JSON data @@ -208,7 +206,7 @@ func WriteGzipSarif(sarif format.SARIF, fileName string) ([]piperutils.Path, err log.Entry().Info("Writing file to disk: ", sarifReportPath) if err := utils.FileWrite(sarifReportPath, gzBuffer.Bytes(), 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write Fortify SARIF gzip report") + return reportPaths, fmt.Errorf("failed to write Fortify SARIF gzip report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Fortify SARIF gzip Report", Target: sarifReportPath}) @@ -224,11 +222,11 @@ func WriteCustomReports(scanReport reporting.ScanReport) ([]piperutils.Path, err htmlReportPath := filepath.Join(ReportsDirectory, "piper_fortify_report.html") // Ensure reporting directory exists if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } if err := utils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Fortify Report", Target: htmlReportPath}) diff --git a/pkg/gcp/pubsub.go b/pkg/gcp/pubsub.go index b2f09d6be..6f27c032f 100644 --- a/pkg/gcp/pubsub.go +++ b/pkg/gcp/pubsub.go @@ -1,11 +1,13 @@ package gcp import ( - "cloud.google.com/go/pubsub" "context" + "errors" + "fmt" + + "cloud.google.com/go/pubsub" piperConfig "github.com/SAP/jenkins-library/pkg/config" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "golang.org/x/oauth2" "google.golang.org/api/option" ) @@ -38,7 +40,7 @@ func (cl *pubsubClient) Publish(topic string, data []byte) error { ctx := context.Background() psClient, err := cl.getAuthorizedGCPClient(ctx) if err != nil { - return errors.Wrap(err, "could not get authorized pubsub client token") + return fmt.Errorf("could not get authorized pubsub client token: %w", err) } return cl.publish(ctx, psClient, topic, cl.orderingKey, data) @@ -51,12 +53,12 @@ func (cl *pubsubClient) getAuthorizedGCPClient(ctx context.Context) (*pubsub.Cli oidcToken, err := cl.vaultClient.GetOIDCTokenByValidation(cl.oidcRoleId) if err != nil { - return nil, errors.Wrap(err, "could not get oidc token") + return nil, fmt.Errorf("could not get oidc token: %w", err) } accessToken, err := getFederatedToken(cl.projectNumber, cl.pool, cl.provider, oidcToken) if err != nil { - return nil, errors.Wrap(err, "could not get federated token") + return nil, fmt.Errorf("could not get federated token: %w", err) } staticTokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}) @@ -72,7 +74,7 @@ func (cl *pubsubClient) publish(ctx context.Context, psClient *pubsub.Client, to // By removing .Get() method call we can make publishing asynchronous, but without ability to catch errors msgID, err := publishResult.Get(context.Background()) if err != nil { - return errors.Wrap(err, "event publish failed") + return fmt.Errorf("event publish failed: %w", err) } log.Entry().Debugf("Event published with ID: %s", msgID) diff --git a/pkg/gcp/token.go b/pkg/gcp/token.go index fc00b1909..828a74115 100644 --- a/pkg/gcp/token.go +++ b/pkg/gcp/token.go @@ -3,13 +3,15 @@ package gcp import ( "context" "fmt" - "github.com/SAP/jenkins-library/pkg/log" - "google.golang.org/api/option" "os" "strconv" "time" - "github.com/pkg/errors" + "github.com/SAP/jenkins-library/pkg/log" + "google.golang.org/api/option" + + "errors" + "google.golang.org/api/sts/v1" ) @@ -31,7 +33,7 @@ func getFederatedToken(projectNumber, pool, provider, oidcToken string) (string, ctx := context.Background() token, expiresAt, err := exchangeOIDCToken(ctx, projectNumber, pool, provider, oidcToken) if err != nil { - return "", errors.Wrap(err, "token exchange") + return "", fmt.Errorf("token exchange: %w", err) } os.Setenv(gcpPubsubTokenKey, token) @@ -47,13 +49,13 @@ func exchangeOIDCToken(ctx context.Context, projectNumber, pool, provider, oidcT stsService, err := sts.NewService(ctx, option.WithoutAuthentication()) if err != nil { - return "", 0, errors.Wrap(err, "service not created") + return "", 0, fmt.Errorf("service not created: %w", err) } request := getExchangeTokenRequestData(projectNumber, pool, provider, oidcToken) response, err := sts.NewV1Service(stsService).Token(request).Context(ctx).Do() if err != nil { - return "", 0, errors.Wrap(err, "exchange failed") + return "", 0, fmt.Errorf("exchange failed: %w", err) } expiresAt := time.Now().Unix() + response.ExpiresIn diff --git a/pkg/gcs/gcs_client.go b/pkg/gcs/gcs_client.go index 44e84ce17..d41880578 100644 --- a/pkg/gcs/gcs_client.go +++ b/pkg/gcs/gcs_client.go @@ -2,6 +2,7 @@ package gcs import ( "context" + "errors" "fmt" "io" "os" @@ -9,7 +10,7 @@ import ( "cloud.google.com/go/storage" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" + "google.golang.org/api/iterator" "google.golang.org/api/option" ) @@ -82,7 +83,7 @@ func (cl *gcsClient) DownloadFile(ctx context.Context, bucketID, sourcePath, tar target, err := cl.createFile(targetPath) if err != nil { - return errors.Wrapf(err, "could not create target file: %v", err) + return fmt.Errorf("could not create target file: %v: %w", err, err) } defer target.Close() @@ -113,7 +114,7 @@ func (cl *gcsClient) ListFiles(ctx context.Context, bucketID string) ([]string, break } if err != nil { - return nil, errors.Wrap(err, "could not list files") + return nil, fmt.Errorf("could not list files: %w", err) } fileNames = append(fileNames, attrs.Name) } diff --git a/pkg/gcs/mocks/client.go b/pkg/gcs/mocks/client.go index d97f654ee..1f27c92db 100644 --- a/pkg/gcs/mocks/client.go +++ b/pkg/gcs/mocks/client.go @@ -4,6 +4,7 @@ package mocks import ( "context" + mock "github.com/stretchr/testify/mock" ) diff --git a/pkg/gcts/gctsUtils.go b/pkg/gcts/gctsUtils.go index fc32eaf8a..1fb160fa8 100644 --- a/pkg/gcts/gctsUtils.go +++ b/pkg/gcts/gctsUtils.go @@ -1,20 +1,20 @@ package gcts import ( + "fmt" "net/http/cookiejar" "net/url" "github.com/SAP/jenkins-library/pkg/http" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) func NewHttpClientOptions(username, password, proxy string, skipSSLVerification bool) (http.ClientOptions, error) { cookieJar, err := cookiejar.New(nil) if err != nil { - return piperhttp.ClientOptions{}, errors.Wrap(err, "creating a cookie jar failed") + return piperhttp.ClientOptions{}, fmt.Errorf("creating a cookie jar failed: %w", err) } options := piperhttp.ClientOptions{ @@ -29,7 +29,7 @@ func NewHttpClientOptions(username, password, proxy string, skipSSLVerification if proxy != "" { proxyURL, err := url.Parse(proxy) if err != nil { - return piperhttp.ClientOptions{}, errors.Wrap(err, "parsing proxy-url failed") + return piperhttp.ClientOptions{}, fmt.Errorf("parsing proxy-url failed: %w", err) } options.TransportProxy = proxyURL log.Entry().Infof("Using proxy: %v", proxy) diff --git a/pkg/git/git.go b/pkg/git/git.go index bcee2e6e6..c6a54541a 100644 --- a/pkg/git/git.go +++ b/pkg/git/git.go @@ -1,14 +1,16 @@ package git import ( + "fmt" "time" + "errors" + "github.com/SAP/jenkins-library/pkg/log" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/transport/http" - "github.com/pkg/errors" ) // utilsWorkTree interface abstraction of git.Worktree to enable tests @@ -39,7 +41,7 @@ func CommitSingleFile(filePath, commitMessage, author string, worktree *git.Work func commitSingleFile(filePath, commitMessage, author string, worktree utilsWorkTree) (plumbing.Hash, error) { _, err := worktree.Add(filePath) if err != nil { - return [20]byte{}, errors.Wrap(err, "failed to add file to git") + return [20]byte{}, fmt.Errorf("failed to add file to git: %w", err) } commit, err := worktree.Commit(commitMessage, &git.CommitOptions{ @@ -47,7 +49,7 @@ func commitSingleFile(filePath, commitMessage, author string, worktree utilsWork Author: &object.Signature{Name: author, When: time.Now()}, }) if err != nil { - return [20]byte{}, errors.Wrap(err, "failed to commit file") + return [20]byte{}, fmt.Errorf("failed to commit file: %w", err) } return commit, nil @@ -71,7 +73,7 @@ func pushChangesToRepository(username, password string, force *bool, repository } err := repository.Push(pushOptions) if err != nil { - return errors.Wrap(err, "failed to push commit") + return fmt.Errorf("failed to push commit: %w", err) } return nil } @@ -96,7 +98,7 @@ func plainClone(username, password, serverURL, branchName, directory string, abs repository, err := abstractionGit.plainClone(directory, false, &gitCloneOptions) if err != nil { - return nil, errors.Wrap(err, "failed to clone git") + return nil, fmt.Errorf("failed to clone git: %w", err) } return repository, nil } @@ -111,7 +113,7 @@ func plainOpen(path string, abstractionGit utilsGit) (*git.Repository, error) { log.Entry().Infof("Opening git repo at '%s'", path) r, err := abstractionGit.plainOpen(path) if err != nil { - return nil, errors.Wrapf(err, "Unable to open git repository at '%s'", path) + return nil, fmt.Errorf("Unable to open git repository at '%s': %w", path, err) } return r, nil } @@ -137,7 +139,7 @@ func changeBranch(branchName string, worktree utilsWorkTree) error { checkoutOptions.Create = true err = worktree.Checkout(checkoutOptions) if err != nil { - return errors.Wrap(err, "failed to checkout branch") + return fmt.Errorf("failed to checkout branch: %w", err) } } @@ -150,11 +152,11 @@ func LogRange(repo *git.Repository, from, to string) (object.CommitIter, error) cTo, err := getCommitObject(to, repo) if err != nil { - return nil, errors.Wrapf(err, "Cannot provide log range (to: '%s' not found)", to) + return nil, fmt.Errorf("Cannot provide log range (to: '%s' not found): %w", to, err) } cFrom, err := getCommitObject(from, repo) if err != nil { - return nil, errors.Wrapf(err, "Cannot provide log range (from: '%s' not found)", from) + return nil, fmt.Errorf("Cannot provide log range (from: '%s' not found): %w", from, err) } ignore := []plumbing.Hash{} err = object.NewCommitPreorderIter( @@ -166,7 +168,7 @@ func LogRange(repo *git.Repository, from, to string) (object.CommitIter, error) return nil }) if err != nil { - return nil, errors.Wrap(err, "Cannot provide log range") + return nil, fmt.Errorf("Cannot provide log range: %w", err) } return object.NewCommitPreorderIter(cTo, map[plumbing.Hash]bool{}, ignore), nil @@ -179,11 +181,11 @@ func getCommitObject(ref string, repo *git.Repository) (*object.Commit, error) { } r, err := repo.ResolveRevision(plumbing.Revision(ref)) if err != nil { - return nil, errors.Wrapf(err, "Trouble resolving '%s'", ref) + return nil, fmt.Errorf("Trouble resolving '%s': %w", ref, err) } c, err := repo.CommitObject(*r) if err != nil { - return nil, errors.Wrapf(err, "Trouble resolving '%s'", ref) + return nil, fmt.Errorf("Trouble resolving '%s': %w", ref, err) } return c, nil } diff --git a/pkg/git/git_test.go b/pkg/git/git_test.go index bafa7ddec..28bc048a3 100644 --- a/pkg/git/git_test.go +++ b/pkg/git/git_test.go @@ -6,6 +6,8 @@ package git import ( "errors" "fmt" + "testing" + "github.com/go-git/go-billy/v5" "github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-git/v5" @@ -13,7 +15,6 @@ import ( "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/storage/memory" "github.com/stretchr/testify/assert" - "testing" ) func TestCommit(t *testing.T) { diff --git a/pkg/github/commit.go b/pkg/github/commit.go index 0d5353ccd..d4331c3e8 100644 --- a/pkg/github/commit.go +++ b/pkg/github/commit.go @@ -1,8 +1,9 @@ package github import ( + "fmt" + "github.com/google/go-github/v68/github" - "github.com/pkg/errors" ) // FetchCommitOptions to configure the lookup @@ -29,12 +30,12 @@ func FetchCommitStatistics(options *FetchCommitOptions) (FetchCommitResult, erro // create GitHub client ctx, client, err := NewClientBuilder(options.Token, options.APIURL).WithTrustedCerts(options.TrustedCerts).Build() if err != nil { - return FetchCommitResult{}, errors.Wrap(err, "failed to get GitHub client") + return FetchCommitResult{}, fmt.Errorf("failed to get GitHub client: %w", err) } // fetch commit by SAH result, _, err := client.Repositories.GetCommit(ctx, options.Owner, options.Repository, options.SHA, &github.ListOptions{}) if err != nil { - return FetchCommitResult{}, errors.Wrap(err, "failed to get GitHub commit") + return FetchCommitResult{}, fmt.Errorf("failed to get GitHub commit: %w", err) } return FetchCommitResult{ Files: len(result.Files), diff --git a/pkg/github/create_issue.go b/pkg/github/create_issue.go index 7a6bcc483..8ee681e8e 100644 --- a/pkg/github/create_issue.go +++ b/pkg/github/create_issue.go @@ -6,7 +6,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" ) // CreateIssueOptions to configure the creation @@ -26,7 +25,7 @@ type CreateIssueOptions struct { func CreateIssue(options *CreateIssueOptions) (*github.Issue, error) { ctx, client, err := NewClientBuilder(options.Token, options.APIURL).WithTrustedCerts(options.TrustedCerts).Build() if err != nil { - return nil, errors.Wrap(err, "failed to get GitHub client") + return nil, fmt.Errorf("failed to get GitHub client: %w", err) } return createIssueLocal(ctx, options, client.Issues, client.Search, client.Issues) } @@ -65,7 +64,7 @@ func createIssueLocal( if resp != nil { log.Entry().Errorf("GitHub search issue returned response code %v", resp.Status) } - return nil, errors.Wrap(err, "error occurred when looking for existing issue") + return nil, fmt.Errorf("error occurred when looking for existing issue: %w", err) } else { for _, value := range searchResult.Issues { if value != nil && *value.Title == options.Title { @@ -82,7 +81,7 @@ func createIssueLocal( if resp != nil { log.Entry().Errorf("GitHub create comment returned response code %v", resp.Status) } - return nil, errors.Wrap(err, "error occurred when adding comment to existing issue") + return nil, fmt.Errorf("error occurred when adding comment to existing issue: %w", err) } } } @@ -93,7 +92,7 @@ func createIssueLocal( if resp != nil { log.Entry().Errorf("GitHub create issue returned response code %v", resp.Status) } - return nil, errors.Wrap(err, "error occurred when creating issue") + return nil, fmt.Errorf("error occurred when creating issue: %w", err) } log.Entry().Debugf("New issue created: %v", newIssue) existingIssue = newIssue diff --git a/pkg/github/github.go b/pkg/github/github.go index 256266d50..6084fffe7 100644 --- a/pkg/github/github.go +++ b/pkg/github/github.go @@ -2,13 +2,14 @@ package github import ( "context" + "fmt" "net/url" "strings" "time" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" + "golang.org/x/oauth2" ) @@ -75,12 +76,12 @@ func (b *ClientBuilder) WithMaxRetries(maxRetries int) *ClientBuilder { func (b *ClientBuilder) Build() (context.Context, *github.Client, error) { baseURL, err := url.Parse(b.baseURL) if err != nil { - return nil, nil, errors.Wrap(err, "failed to parse baseURL") + return nil, nil, fmt.Errorf("failed to parse baseURL: %w", err) } uploadURL, err := url.Parse(b.uploadURL) if err != nil { - return nil, nil, errors.Wrap(err, "failed to parse uploadURL") + return nil, nil, fmt.Errorf("failed to parse uploadURL: %w", err) } if b.timeout == 0 { diff --git a/pkg/goget/goget.go b/pkg/goget/goget.go index d7b325192..17c5b54e6 100644 --- a/pkg/goget/goget.go +++ b/pkg/goget/goget.go @@ -2,10 +2,11 @@ package goget import ( "fmt" - piperhttp "github.com/SAP/jenkins-library/pkg/http" "net/http" "strings" + piperhttp "github.com/SAP/jenkins-library/pkg/http" + "github.com/antchfx/htmlquery" ) diff --git a/pkg/goget/goget_test.go b/pkg/goget/goget_test.go index 371f60c7a..e3df3994a 100644 --- a/pkg/goget/goget_test.go +++ b/pkg/goget/goget_test.go @@ -5,11 +5,12 @@ package goget import ( "fmt" - piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/stretchr/testify/assert" "io" "net/http" "testing" + + piperhttp "github.com/SAP/jenkins-library/pkg/http" + "github.com/stretchr/testify/assert" ) func TestGoGetClient(t *testing.T) { diff --git a/pkg/http/downloader.go b/pkg/http/downloader.go index 687d6f2d7..9c9ee0982 100644 --- a/pkg/http/downloader.go +++ b/pkg/http/downloader.go @@ -1,13 +1,12 @@ package http import ( + "fmt" "net/http" "os" "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/piperutils" ) @@ -26,7 +25,7 @@ func (c *Client) DownloadFile(url, filename string, header http.Header, cookies func (c *Client) DownloadRequest(method, url, filename string, header http.Header, cookies []*http.Cookie) error { response, err := c.SendRequest(method, url, nil, header, cookies) if err != nil { - return errors.Wrapf(err, "HTTP %v request to %v failed with error", method, url) + return fmt.Errorf("HTTP %v request to %v failed with error: %w", method, url, err) } defer response.Body.Close() parent := filepath.Dir(filename) @@ -37,13 +36,13 @@ func (c *Client) DownloadRequest(method, url, filename string, header http.Heade } fileHandler, err := os.Create(filename) if err != nil { - return errors.Wrapf(err, "unable to create file %v", filename) + return fmt.Errorf("unable to create file %v: %w", filename, err) } defer fileHandler.Close() _, err = piperutils.CopyData(fileHandler, response.Body) if err != nil { - return errors.Wrapf(err, "unable to copy content from url to file %v", filename) + return fmt.Errorf("unable to copy content from url to file %v: %w", filename, err) } return err } @@ -52,7 +51,7 @@ func (c *Client) DownloadRequest(method, url, filename string, header http.Heade func (c *Client) GetRequest(url string, header http.Header, cookies []*http.Cookie) (*http.Response, error) { response, err := c.SendRequest("GET", url, nil, header, cookies) if err != nil { - return &http.Response{}, errors.Wrapf(err, "HTTP request to %v failed with error", url) + return &http.Response{}, fmt.Errorf("HTTP request to %v failed with error: %w", url, err) } return response, nil } @@ -70,11 +69,11 @@ func DownloadExecutable(githubToken string, fileUtils piperutils.FileUtils, down fullFileName := filepath.Join(".pipeline", fileName) err := downloader.DownloadFile(url, fullFileName, header, []*http.Cookie{}) if err != nil { - return "", errors.Wrapf(err, "unable to download script from %v", url) + return "", fmt.Errorf("unable to download script from %v: %w", url, err) } err = fileUtils.Chmod(fullFileName, 0555) if err != nil { - return "", errors.Wrapf(err, "unable to change script permission for %v", fullFileName) + return "", fmt.Errorf("unable to change script permission for %v: %w", fullFileName, err) } return fullFileName, nil } diff --git a/pkg/http/http.go b/pkg/http/http.go index 4f128b1e1..4c8bde3be 100644 --- a/pkg/http/http.go +++ b/pkg/http/http.go @@ -23,7 +23,6 @@ import ( "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/hashicorp/go-retryablehttp" "github.com/motemen/go-nuts/roundtime" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -135,7 +134,7 @@ func (c *Client) UploadRequest(method, url, file, fileFieldName string, header h fileHandle, err := c.getFileUtils().Open(file) if err != nil { - return &http.Response{}, errors.Wrapf(err, "unable to locate file %v", file) + return &http.Response{}, fmt.Errorf("unable to locate file %v: %w", file, err) } defer fileHandle.Close() @@ -154,7 +153,7 @@ func (c *Client) UploadRequest(method, url, file, fileFieldName string, header h // Upload uploads a file's content as multipart-form or pure binary with given http method request to the specified URL func (c *Client) Upload(data UploadRequestData) (*http.Response, error) { if data.Method != http.MethodPost && data.Method != http.MethodPut { - return nil, errors.New(fmt.Sprintf("Http method %v is not allowed. Possible values are %v or %v", data.Method, http.MethodPost, http.MethodPut)) + return nil, fmt.Errorf("Http method %v is not allowed. Possible values are %v or %v", data.Method, http.MethodPost, http.MethodPut) } // Binary upload :: other options ("binary" or "form"). @@ -162,7 +161,7 @@ func (c *Client) Upload(data UploadRequestData) (*http.Response, error) { request, err := c.createRequest(data.Method, data.URL, data.FileContent, &data.Header, data.Cookies) if err != nil { c.logger.Debugf("New %v request to %v (binary upload)", data.Method, data.URL) - return &http.Response{}, errors.Wrapf(err, "error creating %v request to %v (binary upload)", data.Method, data.URL) + return &http.Response{}, fmt.Errorf("error creating %v request to %v (binary upload): %w", data.Method, data.URL, err) } request.Header.Add("Content-Type", "application/octet-stream") request.Header.Add("Connection", "Keep-Alive") @@ -178,19 +177,19 @@ func (c *Client) Upload(data UploadRequestData) (*http.Response, error) { for fieldName, fieldValue := range data.FormFields { err := bodyWriter.WriteField(fieldName, fieldValue) if err != nil { - return &http.Response{}, errors.Wrapf(err, "error writing form field %v with value %v", fieldName, fieldValue) + return &http.Response{}, fmt.Errorf("error writing form field %v with value %v: %w", fieldName, fieldValue, err) } } } fileWriter, err := bodyWriter.CreateFormFile(data.FileFieldName, data.File) if err != nil { - return &http.Response{}, errors.Wrapf(err, "error creating form file %v for field %v", data.File, data.FileFieldName) + return &http.Response{}, fmt.Errorf("error creating form file %v for field %v: %w", data.File, data.FileFieldName, err) } _, err = piperutils.CopyData(fileWriter, data.FileContent) if err != nil { - return &http.Response{}, errors.Wrapf(err, "unable to copy file content of %v into request body", data.File) + return &http.Response{}, fmt.Errorf("unable to copy file content of %v into request body: %w", data.File, err) } err = bodyWriter.Close() if err != nil { @@ -200,7 +199,7 @@ func (c *Client) Upload(data UploadRequestData) (*http.Response, error) { request, err := c.createRequest(data.Method, data.URL, bodyBuffer, &data.Header, data.Cookies) if err != nil { c.logger.Debugf("new %v request to %v", data.Method, data.URL) - return &http.Response{}, errors.Wrapf(err, "error creating %v request to %v", data.Method, data.URL) + return &http.Response{}, fmt.Errorf("error creating %v request to %v: %w", data.Method, data.URL, err) } startBoundary := strings.Index(bodyWriter.FormDataContentType(), "=") + 1 @@ -219,7 +218,7 @@ func (c *Client) Upload(data UploadRequestData) (*http.Response, error) { func (c *Client) SendRequest(method, url string, body io.Reader, header http.Header, cookies []*http.Cookie) (*http.Response, error) { request, err := c.createRequest(method, url, body, &header, cookies) if err != nil { - return &http.Response{}, errors.Wrapf(err, "error creating %v request to %v", method, url) + return &http.Response{}, fmt.Errorf("error creating %v request to %v: %w", method, url, err) } return c.Send(request) @@ -230,7 +229,7 @@ func (c *Client) Send(request *http.Request) (*http.Response, error) { httpClient := c.initializeHttpClient() response, err := httpClient.Do(request) if err != nil { - return response, errors.Wrapf(err, "HTTP %v request to %v failed", request.Method, request.URL) + return response, fmt.Errorf("HTTP %v request to %v failed: %w", request.Method, request.URL, err) } return c.handleResponse(response, request.URL.String()) } @@ -534,7 +533,7 @@ func (c *Client) configureTLSToTrustCertificates(transport *TransportWrapper) er trustStoreDir, err := getWorkingDirForTrustStore() if err != nil { - return errors.Wrap(err, "failed to create trust store directory") + return fmt.Errorf("failed to create trust store directory: %w", err) } /* insecure := flag.Bool("insecure-ssl", false, "Accept/Ignore all server SSL certificates") */ // Get the SystemCertPool, continue with an empty pool on error @@ -587,7 +586,7 @@ func (c *Client) configureTLSToTrustCertificates(transport *TransportWrapper) er } response, err := httpClient.Do(request) if err != nil { - return errors.Wrapf(err, "HTTP %v request to %v failed", request.Method, request.URL) + return fmt.Errorf("HTTP %v request to %v failed: %w", request.Method, request.URL, err) } if response.StatusCode >= 200 && response.StatusCode < 300 { @@ -600,39 +599,39 @@ func (c *Client) configureTLSToTrustCertificates(transport *TransportWrapper) er } fileHandler, err := c.getFileUtils().Create(target) if err != nil { - return errors.Wrapf(err, "unable to create file %v", filename) + return fmt.Errorf("unable to create file %v: %w", filename, err) } defer fileHandler.Close() numWritten, err := io.Copy(fileHandler, response.Body) if err != nil { - return errors.Wrapf(err, "unable to copy content from url to file %v", filename) + return fmt.Errorf("unable to copy content from url to file %v: %w", filename, err) } log.Entry().Debugf("wrote %v bytes from response body to file", numWritten) certs, err := os.ReadFile(target) if err != nil { - return errors.Wrapf(err, "failed to read cert file %v", certificate) + return fmt.Errorf("failed to read cert file %v: %w", certificate, err) } // Append our cert to the system pool ok := rootCAs.AppendCertsFromPEM(certs) if !ok { - return errors.Errorf("failed to append %v to root CA store", certificate) + return fmt.Errorf("failed to append %v to root CA store", certificate) } log.Entry().Infof("%v appended to root CA successfully", certificate) } else { - return errors.Wrapf(err, "Download of TLS certificate %v failed with status code %v", certificate, response.StatusCode) + return fmt.Errorf("Download of TLS certificate %v failed with status code %v: %w", certificate, response.StatusCode, err) } } else { log.Entry().Debugf("existing certificate file %v found, appending it to rootCA", target) certs, err := os.ReadFile(target) if err != nil { - return errors.Wrapf(err, "failed to read cert file %v", certificate) + return fmt.Errorf("failed to read cert file %v: %w", certificate, err) } // Append our cert to the system pool ok := rootCAs.AppendCertsFromPEM(certs) if !ok { - return errors.Errorf("failed to append %v to root CA store", certificate) + return fmt.Errorf("failed to append %v to root CA store", certificate) } log.Entry().Debugf("%v appended to root CA successfully", certificate) } @@ -649,7 +648,7 @@ func getWorkingDirForTrustStore() (string, error) { if exists, _ := fileUtils.DirExists(TrustStoreDirectory); !exists { err := fileUtils.MkdirAll(TrustStoreDirectory, 0777) if err != nil { - return "", errors.Wrap(err, "failed to create trust store directory") + return "", fmt.Errorf("failed to create trust store directory: %w", err) } } return TrustStoreDirectory, nil @@ -658,17 +657,17 @@ func getWorkingDirForTrustStore() (string, error) { // ParseHTTPResponseBodyXML parses an XML http response into a given interface func ParseHTTPResponseBodyXML(resp *http.Response, response interface{}) error { if resp == nil { - return errors.Errorf("cannot parse HTTP response with value ") + return fmt.Errorf("cannot parse HTTP response with value ") } bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrap(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } marshalErr := xml.Unmarshal(bodyText, &response) if marshalErr != nil { - return errors.Wrapf(marshalErr, "HTTP response body could not be parsed as XML: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as XML: %v: %w", string(bodyText), marshalErr) } return nil @@ -677,17 +676,17 @@ func ParseHTTPResponseBodyXML(resp *http.Response, response interface{}) error { // ParseHTTPResponseBodyJSON parses a JSON http response into a given interface func ParseHTTPResponseBodyJSON(resp *http.Response, response interface{}) error { if resp == nil { - return errors.Errorf("cannot parse HTTP response with value ") + return fmt.Errorf("cannot parse HTTP response with value ") } bodyText, readErr := io.ReadAll(resp.Body) if readErr != nil { - return errors.Wrapf(readErr, "HTTP response body could not be read") + return fmt.Errorf("HTTP response body could not be read: %w", readErr) } marshalErr := json.Unmarshal(bodyText, &response) if marshalErr != nil { - return errors.Wrapf(marshalErr, "HTTP response body could not be parsed as JSON: %v", string(bodyText)) + return fmt.Errorf("HTTP response body could not be parsed as JSON: %v: %w", string(bodyText), marshalErr) } return nil diff --git a/pkg/jenkins/jenkins.go b/pkg/jenkins/jenkins.go index a654fef91..013a7fa80 100644 --- a/pkg/jenkins/jenkins.go +++ b/pkg/jenkins/jenkins.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/bndr/gojenkins" - "github.com/pkg/errors" ) // Jenkins is an interface to abstract gojenkins.Jenkins. @@ -36,7 +35,7 @@ func TriggerJob(ctx context.Context, jenkins Jenkins, job Job, parameters map[st // update job _, pollJobErr := job.Poll(ctx) if pollJobErr != nil { - return nil, errors.Wrapf(pollJobErr, "failed to load job") + return nil, fmt.Errorf("failed to load job: %w", pollJobErr) } // start job queueID, startBuildErr := job.InvokeSimple(ctx, parameters) diff --git a/pkg/log/ansHook.go b/pkg/log/ansHook.go index 7506fc498..71be75ff2 100644 --- a/pkg/log/ansHook.go +++ b/pkg/log/ansHook.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/SAP/jenkins-library/pkg/ans" - "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) @@ -91,13 +91,13 @@ func registerANSHookIfConfigured(correlationID string, util registrationUtil) er ansServiceKey, err := ans.UnmarshallServiceKeyJSON(ansServiceKeyJSON) if err != nil { - return errors.Wrap(err, "cannot initialize SAP Alert Notification Service due to faulty serviceKey json") + return fmt.Errorf("cannot initialize SAP Alert Notification Service due to faulty serviceKey json: %w", err) } RegisterSecret(ansServiceKey.ClientSecret) util.SetServiceKey(ansServiceKey) if err = util.CheckCorrectSetup(); err != nil { - return errors.Wrap(err, "check http request to SAP Alert Notification Service failed; not setting up the ANS hook") + return fmt.Errorf("check http request to SAP Alert Notification Service failed; not setting up the ANS hook: %w", err) } eventTemplate, err := setupEventTemplate(os.Getenv("PIPER_ansEventTemplate"), correlationID) @@ -123,7 +123,7 @@ func setupEventTemplate(customerEventTemplate, correlationID string) (ans.Event, if len(customerEventTemplate) > 0 { if err := event.MergeWithJSON([]byte(customerEventTemplate)); err != nil { - return ans.Event{}, errors.Wrapf(err, "provided SAP Alert Notification Service event template '%s' could not be unmarshalled", customerEventTemplate) + return ans.Event{}, fmt.Errorf("provided SAP Alert Notification Service event template '%s' could not be unmarshalled: %w", customerEventTemplate, err) } } if len(event.Severity) > 0 { @@ -135,7 +135,7 @@ func setupEventTemplate(customerEventTemplate, correlationID string) (ans.Event, event.Category = "" } if err := event.Validate(); err != nil { - return ans.Event{}, errors.Wrap(err, "did not initialize SAP Alert Notification Service due to faulty event template json") + return ans.Event{}, fmt.Errorf("did not initialize SAP Alert Notification Service due to faulty event template json: %w", err) } return event, nil } diff --git a/pkg/log/ansHook_test.go b/pkg/log/ansHook_test.go index 02b3c43d8..b97b2cdba 100644 --- a/pkg/log/ansHook_test.go +++ b/pkg/log/ansHook_test.go @@ -7,15 +7,16 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/SAP/jenkins-library/pkg/ans" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "os" "reflect" "strconv" "testing" "time" + + "github.com/SAP/jenkins-library/pkg/ans" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestANSHook_Levels(t *testing.T) { diff --git a/pkg/log/errors_test.go b/pkg/log/errors_test.go index 92ced26cb..c81c0a7e5 100644 --- a/pkg/log/errors_test.go +++ b/pkg/log/errors_test.go @@ -6,9 +6,10 @@ package log import ( "encoding/json" "fmt" + "testing" + "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" - "testing" ) func TestSetErrorCategory(t *testing.T) { diff --git a/pkg/log/writer_test.go b/pkg/log/writer_test.go index 53ac7deff..ede46f3d2 100644 --- a/pkg/log/writer_test.go +++ b/pkg/log/writer_test.go @@ -5,8 +5,9 @@ package log import ( "fmt" - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) type mockLogger struct { diff --git a/pkg/malwarescan/malwarescan.go b/pkg/malwarescan/malwarescan.go index 2e8672282..ebd65da6e 100644 --- a/pkg/malwarescan/malwarescan.go +++ b/pkg/malwarescan/malwarescan.go @@ -7,7 +7,6 @@ import ( "net/http" piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/pkg/errors" ) // ScanResult : Returned by the scan endpoint of the malwarescan api of SAP CP @@ -82,7 +81,7 @@ func (c *ClientImpl) sendAPIRequest(method, endpoint string, body io.Reader, hea // a response body could even be already closed. response, err := c.HTTPClient.SendRequest(method, c.Host+endpoint, body, header, nil) if err != nil { - return errors.Wrap(err, fmt.Sprintf("Failed to send request to MalwareService.")) + return fmt.Errorf(fmt.Sprintf("Failed to send request to MalwareService."), err) } if response.StatusCode != 200 { @@ -119,7 +118,7 @@ func (c *ClientImpl) unmarshalResponse(response *http.Response, obj interface{}) err = json.Unmarshal(body, obj) if err != nil { - return errors.Wrap(err, fmt.Sprintf("Unmarshalling of response body failed. Body: '%s'", body)) + return fmt.Errorf(fmt.Sprintf("Unmarshalling of response body failed. Body: '%s'", body), err) } return err diff --git a/pkg/malwarescan/malwarescan_test.go b/pkg/malwarescan/malwarescan_test.go index 6ba9ec65d..46f66d8ef 100644 --- a/pkg/malwarescan/malwarescan_test.go +++ b/pkg/malwarescan/malwarescan_test.go @@ -5,11 +5,12 @@ package malwarescan import ( "fmt" - piperhttp "github.com/SAP/jenkins-library/pkg/http" - "github.com/stretchr/testify/assert" "io" "net/http" "testing" + + piperhttp "github.com/SAP/jenkins-library/pkg/http" + "github.com/stretchr/testify/assert" ) func TestMalwareServiceScan(t *testing.T) { diff --git a/pkg/maven/model_test.go b/pkg/maven/model_test.go index 06695efc1..aa911460a 100644 --- a/pkg/maven/model_test.go +++ b/pkg/maven/model_test.go @@ -4,9 +4,10 @@ package maven import ( + "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) const aggregatorPomXML = ` diff --git a/pkg/mock/dockerRunner_test.go b/pkg/mock/dockerRunner_test.go index 110179b4d..3cec72139 100644 --- a/pkg/mock/dockerRunner_test.go +++ b/pkg/mock/dockerRunner_test.go @@ -6,9 +6,10 @@ package mock import ( "errors" "fmt" - "github.com/stretchr/testify/assert" "os" "testing" + + "github.com/stretchr/testify/assert" ) func TestDockerExecRunnerAddExecConfig(t *testing.T) { diff --git a/pkg/mock/example_dockerRunner_test.go b/pkg/mock/example_dockerRunner_test.go index 5e1030d76..de5dd3786 100644 --- a/pkg/mock/example_dockerRunner_test.go +++ b/pkg/mock/example_dockerRunner_test.go @@ -6,10 +6,11 @@ package mock_test import ( "bytes" "fmt" - "github.com/SAP/jenkins-library/pkg/command" - "github.com/SAP/jenkins-library/pkg/mock" "io" "strings" + + "github.com/SAP/jenkins-library/pkg/command" + "github.com/SAP/jenkins-library/pkg/mock" ) type ExecRunner interface { diff --git a/pkg/nexus/nexus.go b/pkg/nexus/nexus.go index e01da9609..43ccaf2d0 100644 --- a/pkg/nexus/nexus.go +++ b/pkg/nexus/nexus.go @@ -3,8 +3,9 @@ package nexus import ( "errors" "fmt" - "github.com/SAP/jenkins-library/pkg/log" "strings" + + "github.com/SAP/jenkins-library/pkg/log" ) // ArtifactDescription describes a single artifact that can be uploaded to a Nexus repository manager. diff --git a/pkg/npm/config.go b/pkg/npm/config.go index cf01c12d9..ac67003cc 100644 --- a/pkg/npm/config.go +++ b/pkg/npm/config.go @@ -6,8 +6,6 @@ import ( "path/filepath" "regexp" "strings" - - "github.com/pkg/errors" ) const ( @@ -34,7 +32,7 @@ type NPMRC struct { func (rc *NPMRC) Write() error { if err := propertiesWriteFile(rc.filepath, []byte(rc.content), 0644); err != nil { - return errors.Wrapf(err, "failed to write %s", rc.filepath) + return fmt.Errorf("failed to write %s: %w", rc.filepath, err) } return nil } diff --git a/pkg/npm/ignore.go b/pkg/npm/ignore.go index b159956f1..05af66257 100644 --- a/pkg/npm/ignore.go +++ b/pkg/npm/ignore.go @@ -2,11 +2,10 @@ package npm import ( "bufio" + "fmt" "os" "path/filepath" "strings" - - "github.com/pkg/errors" ) const ( @@ -33,7 +32,7 @@ func (ignorefile *NPMIgnore) Write() error { content := strings.Join(ignorefile.values, "\n") if err := writeIgnoreFile(ignorefile.filepath, []byte(content+"\n"), 0644); err != nil { - return errors.Wrapf(err, "failed to write %s", ignorefile.filepath) + return fmt.Errorf("failed to write %s: %w", ignorefile.filepath, err) } return nil } diff --git a/pkg/npm/mock.go b/pkg/npm/mock.go index 4c5d20414..d5c4a4232 100644 --- a/pkg/npm/mock.go +++ b/pkg/npm/mock.go @@ -5,6 +5,7 @@ package npm import ( "fmt" + "github.com/SAP/jenkins-library/pkg/versioning" "github.com/SAP/jenkins-library/pkg/mock" diff --git a/pkg/npm/publish.go b/pkg/npm/publish.go index 412c79d3d..77e50d785 100644 --- a/pkg/npm/publish.go +++ b/pkg/npm/publish.go @@ -7,8 +7,6 @@ import ( "regexp" "strings" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/versioning" @@ -60,17 +58,17 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT scope, err := exec.readPackageScope(packageJSON) if err != nil { - return errors.Wrapf(err, "error reading package scope from %s", packageJSON) + return fmt.Errorf("error reading package scope from %s: %w", packageJSON, err) } npmignore := NewNPMIgnore(filepath.Dir(packageJSON)) if exists, err := exec.Utils.FileExists(npmignore.filepath); exists { if err != nil { - return errors.Wrapf(err, "failed to check for existing %s file", npmignore.filepath) + return fmt.Errorf("failed to check for existing %s file: %w", npmignore.filepath, err) } log.Entry().Debugf("loading existing %s file", npmignore.filepath) if err = npmignore.Load(); err != nil { - return errors.Wrapf(err, "failed to read existing %s file", npmignore.filepath) + return fmt.Errorf("failed to read existing %s file: %w", npmignore.filepath, err) } } else { log.Entry().Debug("creating .npmignore file") @@ -91,7 +89,7 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT npmignore.Add(npmrc.filepath) if err := npmignore.Write(); err != nil { - return errors.Wrapf(err, "failed to update %s file", npmignore.filepath) + return fmt.Errorf("failed to update %s file: %w", npmignore.filepath, err) } // update .piperNpmrc @@ -99,11 +97,11 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT // check existing .npmrc file if exists, err := exec.Utils.FileExists(npmrc.filepath); exists { if err != nil { - return errors.Wrapf(err, "failed to check for existing %s file", npmrc.filepath) + return fmt.Errorf("failed to check for existing %s file: %w", npmrc.filepath, err) } log.Entry().Debugf("loading existing %s file", npmrc.filepath) if err = npmrc.Load(); err != nil { - return errors.Wrapf(err, "failed to read existing %s file", npmrc.filepath) + return fmt.Errorf("failed to read existing %s file: %w", npmrc.filepath, err) } } else { log.Entry().Debugf("creating new npmrc file at %s", npmrc.filepath) @@ -127,7 +125,7 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT } // update .npmrc if err := npmrc.Write(); err != nil { - return errors.Wrapf(err, "failed to update %s file", npmrc.filepath) + return fmt.Errorf("failed to update %s file: %w", npmrc.filepath, err) } } else { log.Entry().Debug("no registry provided") @@ -136,7 +134,7 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT // Read version to check if it's a prerelease version, err := exec.readPackageVersion(packageJSON) if err != nil { - return errors.Wrapf(err, "failed to read package version from %s", packageJSON) + return fmt.Errorf("failed to read package version from %s: %w", packageJSON, err) } tag := publishTag @@ -199,7 +197,7 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT } if err = execRunner.RunExecutable("npm", publishArgs...); err != nil { - return errors.Wrap(err, "failed publishing artifact") + return fmt.Errorf("failed publishing artifact: %w", err) } if projectNpmrcExists { @@ -220,7 +218,7 @@ func (exec *Execute) publish(packageJSON, registry, username, password, publishT } if err = execRunner.RunExecutable("npm", publishArgs...); err != nil { - return errors.Wrap(err, "failed publishing artifact") + return fmt.Errorf("failed publishing artifact: %w", err) } } diff --git a/pkg/orchestrator/azure_test.go b/pkg/orchestrator/azure_test.go index cfe820192..72b707005 100644 --- a/pkg/orchestrator/azure_test.go +++ b/pkg/orchestrator/azure_test.go @@ -10,9 +10,10 @@ import ( "testing" "time" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/jarcoal/httpmock" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/pkg/orchestrator/github_actions.go b/pkg/orchestrator/github_actions.go index 3381b7cc8..1b80e400d 100644 --- a/pkg/orchestrator/github_actions.go +++ b/pkg/orchestrator/github_actions.go @@ -16,7 +16,7 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/google/go-github/v68/github" - "github.com/pkg/errors" + "golang.org/x/sync/errgroup" ) @@ -61,7 +61,7 @@ func (g *githubActionsConfigProvider) Configure(opts *Options) error { var err error g.ctx, g.client, err = piperGithub.NewClientBuilder(opts.GitHubToken, getEnv("GITHUB_API_URL", "")).Build() if err != nil { - return errors.Wrap(err, "failed to create github client") + return fmt.Errorf("failed to create github client: %w", err) } log.Entry().Debug("Successfully initialized GitHubActions config provider") @@ -125,14 +125,14 @@ func (g *githubActionsConfigProvider) FullLogs() ([]byte, error) { // GitHub API returns redirect URL instead of plain text logs. See: // https://docs.github.com/en/enterprise-server@3.9/rest/actions/workflow-jobs?apiVersion=2022-11-28#download-job-logs-for-a-workflow-run if err.Error() != "unexpected status code: 200 OK" { - return errors.Wrap(err, "fetching job logs failed") + return fmt.Errorf("fetching job logs failed: %w", err) } } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { - return errors.Wrap(err, "failed to read response body") + return fmt.Errorf("failed to read response body: %w", err) } fullLogs.Lock() @@ -143,7 +143,7 @@ func (g *githubActionsConfigProvider) FullLogs() ([]byte, error) { }) } if err := wg.Wait(); err != nil { - return nil, errors.Wrap(err, "failed to fetch all logs") + return nil, fmt.Errorf("failed to fetch all logs: %w", err) } return bytes.Join(fullLogs.b, []byte("")), nil @@ -294,7 +294,7 @@ func (g *githubActionsConfigProvider) fetchJobs() error { jobs, resp, err := g.client.Actions.ListWorkflowJobs(g.ctx, g.owner, g.repo, g.runIdInt64(), nil) if err != nil || resp.StatusCode != 200 { - return errors.Wrap(err, "failed to get API data") + return fmt.Errorf("failed to get API data: %w", err) } if len(jobs.Jobs) == 0 { return fmt.Errorf("no jobs found in response") diff --git a/pkg/orchestrator/helpers_test.go b/pkg/orchestrator/helpers_test.go index 86200733e..3237e9569 100644 --- a/pkg/orchestrator/helpers_test.go +++ b/pkg/orchestrator/helpers_test.go @@ -4,9 +4,10 @@ package orchestrator import ( - "github.com/stretchr/testify/assert" "os" "testing" + + "github.com/stretchr/testify/assert" ) func Test_envVarsAreSet(t *testing.T) { diff --git a/pkg/orchestrator/jenkins.go b/pkg/orchestrator/jenkins.go index cbf2bf299..39d292ccc 100644 --- a/pkg/orchestrator/jenkins.go +++ b/pkg/orchestrator/jenkins.go @@ -2,6 +2,7 @@ package orchestrator import ( "encoding/json" + "fmt" "io" "strings" "time" @@ -9,7 +10,6 @@ import ( "github.com/Jeffail/gabs/v2" piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) type jenkinsConfigProvider struct { @@ -128,14 +128,14 @@ func (j *jenkinsConfigProvider) FullLogs() ([]byte, error) { response, err := j.client.GetRequest(URL, nil, nil) if err != nil { - return []byte{}, errors.Wrapf(err, "could not GET Jenkins log file %v", err) + return []byte{}, fmt.Errorf("could not GET Jenkins log file %v: %w", err, err) } else if response.StatusCode != 200 { log.Entry().Error("response code !=200 could not get log information from Jenkins, returning with empty log.") return []byte{}, nil } logFile, err := io.ReadAll(response.Body) if err != nil { - return []byte{}, errors.Wrapf(err, "could not read Jenkins log file from request %v", err) + return []byte{}, fmt.Errorf("could not read Jenkins log file from request %v: %w", err, err) } defer response.Body.Close() return logFile, nil diff --git a/pkg/orchestrator/jenkins_test.go b/pkg/orchestrator/jenkins_test.go index d9bd7d2ca..c8d2ca0c7 100644 --- a/pkg/orchestrator/jenkins_test.go +++ b/pkg/orchestrator/jenkins_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + "errors" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/jarcoal/httpmock" diff --git a/pkg/orchestrator/orchestrator.go b/pkg/orchestrator/orchestrator.go index 56a715eff..c6ac69b83 100644 --- a/pkg/orchestrator/orchestrator.go +++ b/pkg/orchestrator/orchestrator.go @@ -1,10 +1,11 @@ package orchestrator import ( + "fmt" "sync" "time" - "github.com/pkg/errors" + "errors" "github.com/SAP/jenkins-library/pkg/log" ) @@ -107,7 +108,7 @@ func GetOrchestratorConfigProvider(opts *Options) (ConfigProvider, error) { // This allows configuration of the provider during initialization and/or after it (reconfiguration) if cfgErr := provider.Configure(opts); cfgErr != nil { - return provider, errors.Wrap(cfgErr, "provider configuration failed") + return provider, fmt.Errorf("provider configuration failed: %w", cfgErr) } return provider, nil diff --git a/pkg/piperenv/environment.go b/pkg/piperenv/environment.go index 0a2e8e925..467e213e1 100644 --- a/pkg/piperenv/environment.go +++ b/pkg/piperenv/environment.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) // This file contains functions used to read/write pipeline environment data from/to disk. @@ -26,7 +25,7 @@ func SetResourceParameter(path, resourceName, paramName string, value interface{ paramPath += ".json" content, err = json.Marshal(typedValue) if err != nil { - return errors.Wrapf(err, "failed to marshal resource parameter value %v", typedValue) + return fmt.Errorf("failed to marshal resource parameter value %v: %w", typedValue, err) } } return writeToDisk(paramPath, content) diff --git a/pkg/piperutils/ioUtils.go b/pkg/piperutils/ioUtils.go index de9c2c0db..989506741 100644 --- a/pkg/piperutils/ioUtils.go +++ b/pkg/piperutils/ioUtils.go @@ -3,8 +3,6 @@ package piperutils import ( "fmt" "io" - - "github.com/pkg/errors" ) // CopyData transfers the bytes from src to dst without doing close handling implicitly. @@ -19,18 +17,18 @@ func CopyData(dst io.Writer, src io.Reader) (int64, error) { bytesRead += int64(nr) if err != nil { if err != io.EOF { - return bytesRead, errors.Wrap(err, "read error") + return bytesRead, fmt.Errorf("read error: %w", err) } done = true } nw, err := dst.Write(tmp[:nr]) bytesWritten += int64(nw) if err != nil { - return bytesWritten, errors.Wrap(err, "write error") + return bytesWritten, fmt.Errorf("write error: %w", err) } } if bytesRead != bytesWritten { - return bytesRead, errors.New(fmt.Sprintf("transfer error: read %v bytes but wrote %v bytes", bytesRead, bytesWritten)) + return bytesRead, fmt.Errorf("transfer error: read %v bytes but wrote %v bytes", bytesRead, bytesWritten) } return bytesWritten, nil } diff --git a/pkg/piperutils/strings.go b/pkg/piperutils/strings.go index 8ec7e1509..cd96ef75e 100644 --- a/pkg/piperutils/strings.go +++ b/pkg/piperutils/strings.go @@ -1,9 +1,10 @@ package piperutils import ( + "strings" + "golang.org/x/text/cases" "golang.org/x/text/language" - "strings" ) func Title(in string) string { diff --git a/pkg/piperutils/templateUtils_test.go b/pkg/piperutils/templateUtils_test.go index 421f13766..e0023df24 100644 --- a/pkg/piperutils/templateUtils_test.go +++ b/pkg/piperutils/templateUtils_test.go @@ -4,9 +4,10 @@ package piperutils import ( - "github.com/stretchr/testify/assert" "testing" "text/template" + + "github.com/stretchr/testify/assert" ) type SomeDescriptor struct { diff --git a/pkg/protecode/report.go b/pkg/protecode/report.go index 2fdd796c7..bcfe33014 100644 --- a/pkg/protecode/report.go +++ b/pkg/protecode/report.go @@ -8,8 +8,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" @@ -106,11 +104,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID htmlReportPath := filepath.Join(ReportsDirectory, "piper_protecode_report.html") // Ensure reporting directory exists if err := fileUtils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } if err := fileUtils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "Protecode Vulnerability Report", Target: htmlReportPath}) @@ -120,11 +118,11 @@ func WriteCustomReports(scanReport reporting.ScanReport, projectName, projectID if exists, _ := fileUtils.DirExists(reporting.StepReportDirectory); !exists { err := fileUtils.MkdirAll(reporting.StepReportDirectory, 0777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create reporting directory") + return reportPaths, fmt.Errorf("failed to create reporting directory: %w", err) } } if err := fileUtils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("protecodeExecuteScan_osvm_%v.json", reportShaProtecode([]string{projectName, projectID}))), jsonReport, 0666); err != nil { - return reportPaths, errors.Wrapf(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } // we do not add the json report to the overall list of reports for now, // since it is just an intermediary report used as input for later diff --git a/pkg/reporting/reporting.go b/pkg/reporting/reporting.go index b7fed1e60..b1ef2cd14 100644 --- a/pkg/reporting/reporting.go +++ b/pkg/reporting/reporting.go @@ -6,8 +6,6 @@ import ( "fmt" "text/template" "time" - - "github.com/pkg/errors" ) // IssueDetail represents any content that can be transformed into the body of a GitHub issue @@ -225,12 +223,12 @@ func (s *ScanReport) ToHTML() ([]byte, error) { report := []byte{} tmpl, err := template.New("report").Funcs(funcMap).Parse(reportHTMLTemplate) if err != nil { - return report, errors.Wrap(err, "failed to create HTML report template") + return report, fmt.Errorf("failed to create HTML report template: %w", err) } buf := new(bytes.Buffer) err = tmpl.Execute(buf, s) if err != nil { - return report, errors.Wrap(err, "failed to execute HTML report template") + return report, fmt.Errorf("failed to execute HTML report template: %w", err) } return buf.Bytes(), nil } @@ -301,12 +299,12 @@ func (s ScanReport) ToMarkdown() ([]byte, error) { report := []byte{} tmpl, err := template.New("report").Funcs(funcMap).Parse(reportMdTemplate) if err != nil { - return report, errors.Wrap(err, "failed to create Markdown report template") + return report, fmt.Errorf("failed to create Markdown report template: %w", err) } buf := new(bytes.Buffer) err = tmpl.Execute(buf, s) if err != nil { - return report, errors.Wrap(err, "failed to execute Markdown report template") + return report, fmt.Errorf("failed to execute Markdown report template: %w", err) } return buf.Bytes(), nil } diff --git a/pkg/sonar/componentService.go b/pkg/sonar/componentService.go index 46103d54a..a672181ad 100644 --- a/pkg/sonar/componentService.go +++ b/pkg/sonar/componentService.go @@ -1,13 +1,15 @@ package sonar import ( + "fmt" "net/http" "strconv" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/log" sonargo "github.com/magicsong/sonargo/sonar" - "github.com/pkg/errors" ) // EndpointIssuesSearch API endpoint for https://sonarcloud.io/web_api/api/measures/component @@ -80,13 +82,13 @@ func (service *ComponentService) GetLinesOfCode() (*SonarLinesOfCode, error) { component, response, err := service.Component(&options) if err != nil { - return nil, errors.Wrap(err, "Failed to get coverage from Sonar measures/component API") + return nil, fmt.Errorf("Failed to get coverage from Sonar measures/component API: %w", err) } // reuse response verification from sonargo err = sonargo.CheckResponse(response) if err != nil { - return nil, errors.Wrap(err, "Failed to get lines of code from Sonar measures/component API") + return nil, fmt.Errorf("Failed to get lines of code from Sonar measures/component API: %w", err) } measures := component.Component.Measures @@ -119,13 +121,13 @@ func (service *ComponentService) GetCoverage() (*SonarCoverage, error) { } component, response, err := service.Component(&options) if err != nil { - return nil, errors.Wrap(err, "Failed to get coverage from Sonar measures/component API") + return nil, fmt.Errorf("Failed to get coverage from Sonar measures/component API: %w", err) } // reuse response verification from sonargo err = sonargo.CheckResponse(response) if err != nil { - return nil, errors.Wrap(err, "Failed to get coverage from Sonar measures/component API") + return nil, fmt.Errorf("Failed to get coverage from Sonar measures/component API: %w", err) } measures := component.Component.Measures @@ -176,7 +178,7 @@ func parseMeasureValuef32(measure sonargo.SonarMeasure) (float32, error) { str := measure.Value f64, err := strconv.ParseFloat(str, 32) if err != nil { - return 0.0, errors.Wrap(err, "Invalid value found in measure "+measure.Metric+": "+measure.Value) + return 0.0, fmt.Errorf("Invalid value found in measure "+measure.Metric+": "+measure.Value, err) } return float32(f64), nil } @@ -185,7 +187,7 @@ func parseMeasureValueInt(measure sonargo.SonarMeasure) (int, error) { str := measure.Value val, err := strconv.Atoi(str) if err != nil { - return 0, errors.Wrap(err, "Invalid value found in measure "+measure.Metric+": "+measure.Value) + return 0, fmt.Errorf("Invalid value found in measure "+measure.Metric+": "+measure.Value, err) } return int(val), nil } @@ -205,7 +207,7 @@ func parseMeasureLanguageDistribution(measure sonargo.SonarMeasure) ([]SonarLang loc, err := strconv.Atoi(dist[1]) if err != nil { - return nil, errors.Wrap(err, "Not able to parse value "+dist[1]+" found in measure "+measure.Metric+": "+measure.Value) + return nil, fmt.Errorf("Not able to parse value "+dist[1]+" found in measure "+measure.Metric+": "+measure.Value, err) } ld = append(ld, SonarLanguageDistribution{LanguageKey: dist[0], LinesOfCode: loc}) diff --git a/pkg/sonar/issueService.go b/pkg/sonar/issueService.go index 2f08c0163..7095c4e0f 100644 --- a/pkg/sonar/issueService.go +++ b/pkg/sonar/issueService.go @@ -1,12 +1,12 @@ package sonar import ( + "fmt" "net/http" "net/http/httputil" "github.com/SAP/jenkins-library/pkg/log" sonargo "github.com/magicsong/sonargo/sonar" - "github.com/pkg/errors" ) // EndpointIssuesSearch API endpoint for https://sonarcloud.io/web_api/api/issues/search @@ -67,7 +67,7 @@ func (service *IssueService) getIssueCount(severity issueSeverity, categories *[ } result, _, err := service.SearchIssues(options) if err != nil { - return -1, errors.Wrapf(err, "failed to fetch the numer of '%s' issues", severity) + return -1, fmt.Errorf("failed to fetch the numer of '%s' issues: %w", severity, err) } table := map[string]int{} diff --git a/pkg/sonar/sonar.go b/pkg/sonar/sonar.go index 50ec843f5..93d8552ec 100644 --- a/pkg/sonar/sonar.go +++ b/pkg/sonar/sonar.go @@ -1,10 +1,10 @@ package sonar import ( + "fmt" "path/filepath" "github.com/magiconair/properties" - "github.com/pkg/errors" ) // TaskReportData encapsulates information about an executed Sonar scan task. @@ -30,7 +30,7 @@ func ReadTaskReport(workspace string) (result TaskReportData, err error) { // read content into struct err = reportContent.Decode(&result) if err != nil { - err = errors.Wrapf(err, "decode %s", reportFile) + err = fmt.Errorf("decode %s: %w", reportFile, err) } return } diff --git a/pkg/splunk/splunk.go b/pkg/splunk/splunk.go index d245796c4..a6d5ab535 100644 --- a/pkg/splunk/splunk.go +++ b/pkg/splunk/splunk.go @@ -13,7 +13,6 @@ import ( piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/telemetry" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -80,7 +79,7 @@ func (s *Splunk) Send(telemetryData telemetry.Data, logCollector *log.CollectorH // OR Failure run, and we do not want to send the logs err := s.tryPostMessages(preparedTelemetryData, []log.Message{}) if err != nil { - return errors.Wrap(err, "error while sending logs") + return fmt.Errorf("error while sending logs: %w", err) } return nil } else { @@ -92,7 +91,7 @@ func (s *Splunk) Send(telemetryData telemetry.Data, logCollector *log.CollectorH } err := s.tryPostMessages(preparedTelemetryData, logCollector.Messages[i:upperBound]) if err != nil { - return errors.Wrap(err, "error while sending logs") + return fmt.Errorf("error while sending logs: %w", err) } } } @@ -188,7 +187,7 @@ func (s *Splunk) SendPipelineStatus(pipelineTelemetryData map[string]interface{} } err := s.postLogFile(pipelineTelemetryData, splitted[i:upperBound]) if err != nil { - return errors.Wrap(err, "error while sending logs") + return fmt.Errorf("error while sending logs: %w", err) } } } @@ -208,7 +207,7 @@ func (s *Splunk) postTelemetry(telemetryData map[string]interface{}) error { payload, err := json.Marshal(details) if err != nil { - return errors.Wrap(err, "error while marshalling Splunk message details") + return fmt.Errorf("error while marshalling Splunk message details: %w", err) } prettyPayload, err := json.MarshalIndent(details, "", " ") if err != nil { @@ -218,7 +217,7 @@ func (s *Splunk) postTelemetry(telemetryData map[string]interface{}) error { log.Entry().Debugf("Sending the follwing payload to Splunk HEC: %s", string(prettyPayload)) if err != nil { - return errors.Wrap(err, "error while marshalling Splunk message details") + return fmt.Errorf("error while marshalling Splunk message details: %w", err) } resp, err := s.splunkClient.SendRequest(http.MethodPost, s.splunkDsn, bytes.NewBuffer(payload), nil, nil) @@ -230,20 +229,20 @@ func (s *Splunk) postTelemetry(telemetryData map[string]interface{}) error { body, errRead := io.ReadAll(rdr) log.Entry().Infof("%v: Splunk logging failed - %v", resp.Status, string(body)) if errRead != nil { - return errors.Wrap(errRead, "Error reading response body from Splunk.") + return fmt.Errorf("Error reading response body from Splunk.: %w", errRead) } - return errors.Wrapf(err, "%v: Splunk logging failed - %v", resp.Status, string(body)) + return fmt.Errorf("%v: Splunk logging failed - %v: %w", resp.Status, string(body), err) } } if err != nil { - return errors.Wrap(err, "error sending the requests to Splunk") + return fmt.Errorf("error sending the requests to Splunk: %w", err) } defer func() { err := resp.Body.Close() if err != nil { - errors.Wrap(err, "closing response body failed") + log.Entry().WithError(err).Debug("closing response body failed") } }() @@ -263,7 +262,7 @@ func (s *Splunk) postLogFile(telemetryData map[string]interface{}, messages []st } marshalledLogMessage, err := json.Marshal(logMessage) if err != nil { - return errors.Wrap(err, "error while marshalling Splunk messages") + return fmt.Errorf("error while marshalling Splunk messages: %w", err) } logfileEvents = append(logfileEvents, string(marshalledLogMessage)) } @@ -280,20 +279,20 @@ func (s *Splunk) postLogFile(telemetryData map[string]interface{}, messages []st body, errRead := io.ReadAll(rdr) log.Entry().Infof("%v: Splunk logging failed - %v", resp.Status, string(body)) if errRead != nil { - return errors.Wrap(errRead, "Error reading response body from Splunk.") + return fmt.Errorf("Error reading response body from Splunk.: %w", errRead) } - return errors.Wrapf(err, "%v: Splunk logging failed - %v", resp.Status, string(body)) + return fmt.Errorf("%v: Splunk logging failed - %v: %w", resp.Status, string(body), err) } } if err != nil { - return errors.Wrap(err, "error sending the requests to Splunk") + return fmt.Errorf("error sending the requests to Splunk: %w", err) } defer func() { err := resp.Body.Close() if err != nil { - errors.Wrap(err, "closing response body failed") + log.Entry().WithError(err).Debug("closing response body failed") } }() @@ -315,7 +314,7 @@ func (s *Splunk) tryPostMessages(telemetryData MonitoringData, messages []log.Me payload, err := json.Marshal(details) if err != nil { - return errors.Wrap(err, "error while marshalling Splunk message details") + return fmt.Errorf("error while marshalling Splunk message details: %w", err) } resp, err := s.splunkClient.SendRequest(http.MethodPost, s.splunkDsn, bytes.NewBuffer(payload), nil, nil) @@ -327,20 +326,20 @@ func (s *Splunk) tryPostMessages(telemetryData MonitoringData, messages []log.Me body, errRead := io.ReadAll(rdr) log.Entry().Infof("%v: Splunk logging failed - %v", resp.Status, string(body)) if errRead != nil { - return errors.Wrap(errRead, "Error reading response body from Splunk.") + return fmt.Errorf("Error reading response body from Splunk.: %w", errRead) } - return errors.Wrapf(err, "%v: Splunk logging failed - %v", resp.Status, string(body)) + return fmt.Errorf("%v: Splunk logging failed - %v: %w", resp.Status, string(body), err) } } if err != nil { - return errors.Wrap(err, "error sending the requests to Splunk") + return fmt.Errorf("error sending the requests to Splunk: %w", err) } defer func() { err := resp.Body.Close() if err != nil { - errors.Wrap(err, "closing response body failed") + log.Entry().WithError(err).Debug("closing response body failed") } }() diff --git a/pkg/syft/syft.go b/pkg/syft/syft.go index fb37f0de4..df8a107cc 100644 --- a/pkg/syft/syft.go +++ b/pkg/syft/syft.go @@ -9,10 +9,11 @@ import ( "path/filepath" "strings" + "errors" + "github.com/SAP/jenkins-library/pkg/command" piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) type SyftScanner struct { @@ -40,7 +41,7 @@ func CreateSyftScanner(syftDownloadURL string, fileUtils piperutils.FileUtils, h err = install(syftDownloadURL, syftFile, fileUtils, httpClient) if err != nil { - return nil, errors.Wrap(err, "failed to install syft") + return nil, fmt.Errorf("failed to install syft: %w", err) } return &SyftScanner{syftFile: syftFile}, nil @@ -86,7 +87,7 @@ func install(syftDownloadURL, dest string, fileUtils piperutils.FileUtils, httpC err = extractSyft(response.Body, dest, fileUtils) if err != nil { - return errors.Wrap(err, "failed to extract syft binary") + return fmt.Errorf("failed to extract syft binary: %w", err) } err = fileUtils.Chmod(dest, 0755) @@ -114,7 +115,7 @@ func extractSyft(archive io.Reader, dest string, fileUtils piperutils.FileUtils) } if err != nil { - return errors.Wrap(err, "failed to read archive") + return fmt.Errorf("failed to read archive: %w", err) } if filepath.Base(f.Name) == "syft" { @@ -122,7 +123,7 @@ func extractSyft(archive io.Reader, dest string, fileUtils piperutils.FileUtils) df, err := fileUtils.Create(dest) if err != nil { - return errors.Wrapf(err, "failed to create file %q", dest) + return fmt.Errorf("failed to create file %q: %w", dest, err) } size, err := io.Copy(df, tr) diff --git a/pkg/syft/syft_test.go b/pkg/syft/syft_test.go index f801d6255..6cf97ff51 100644 --- a/pkg/syft/syft_test.go +++ b/pkg/syft/syft_test.go @@ -7,11 +7,12 @@ import ( "net/http" "testing" + "errors" + piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/syft" "github.com/jarcoal/httpmock" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) diff --git a/pkg/systemtrust/systemtrust.go b/pkg/systemtrust/systemtrust.go index 637fa598f..49e58bcb5 100644 --- a/pkg/systemtrust/systemtrust.go +++ b/pkg/systemtrust/systemtrust.go @@ -8,7 +8,8 @@ import ( "net/url" "strings" - "github.com/pkg/errors" + "errors" + "github.com/sirupsen/logrus" piperhttp "github.com/SAP/jenkins-library/pkg/http" @@ -35,7 +36,7 @@ type Configuration struct { func GetToken(refName string, client *piperhttp.Client, systemTrustConfiguration Configuration) (string, error) { secrets, err := getSecrets([]string{refName}, client, systemTrustConfiguration) if err != nil { - return "", errors.Wrap(err, "couldn't get token from System Trust") + return "", fmt.Errorf("couldn't get token from System Trust: %w", err) } for _, s := range secrets { if s.System == refName { @@ -55,7 +56,7 @@ func getSecrets(refNames []string, client *piperhttp.Client, systemTrustConfigur } response, err := getResponse(systemTrustConfiguration.ServerURL, systemTrustConfiguration.TokenEndPoint, query, client) if err != nil { - return secrets, errors.Wrap(err, "getting secrets from System Trust failed") + return secrets, fmt.Errorf("getting secrets from System Trust failed: %w", err) } for k, v := range response { secrets = append(secrets, Secret{ @@ -72,7 +73,7 @@ func getResponse(serverURL, endpoint string, query url.Values, client *piperhttp rawURL, err := parseURL(serverURL, endpoint, query) if err != nil { - return secrets, errors.Wrap(err, "parsing System Trust url failed") + return secrets, fmt.Errorf("parsing System Trust url failed: %w", err) } header := make(http.Header) header.Add("Accept", "application/json") @@ -85,16 +86,16 @@ func getResponse(serverURL, endpoint string, query url.Values, client *piperhttp defer response.Body.Close() bodyBytes, bodyErr := io.ReadAll(response.Body) if bodyErr == nil { - err = errors.Wrap(err, string(bodyBytes)) + err = fmt.Errorf(string(bodyBytes), err) } } - return secrets, errors.Wrap(err, "getting response from System Trust failed") + return secrets, fmt.Errorf("getting response from System Trust failed: %w", err) } defer response.Body.Close() err = json.NewDecoder(response.Body).Decode(&secrets) if err != nil { - return secrets, errors.Wrap(err, "getting response from System Trust failed") + return secrets, fmt.Errorf("getting response from System Trust failed: %w", err) } return secrets, nil diff --git a/pkg/systemtrust/systemtrust_test.go b/pkg/systemtrust/systemtrust_test.go index e01534b8d..3eb36e3be 100644 --- a/pkg/systemtrust/systemtrust_test.go +++ b/pkg/systemtrust/systemtrust_test.go @@ -5,10 +5,11 @@ package systemtrust import ( "fmt" - "github.com/jarcoal/httpmock" "net/http" "testing" + "github.com/jarcoal/httpmock" + piperhttp "github.com/SAP/jenkins-library/pkg/http" "github.com/stretchr/testify/assert" ) diff --git a/pkg/terraform/terraform_test.go b/pkg/terraform/terraform_test.go index 49141c1fa..11c5b903e 100644 --- a/pkg/terraform/terraform_test.go +++ b/pkg/terraform/terraform_test.go @@ -4,8 +4,9 @@ package terraform import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestReadOutputs(t *testing.T) { diff --git a/pkg/tms/tmsClient.go b/pkg/tms/tmsClient.go index 88a5f6394..c6c72fa53 100644 --- a/pkg/tms/tmsClient.go +++ b/pkg/tms/tmsClient.go @@ -15,7 +15,6 @@ import ( piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/xsuaa" - "github.com/pkg/errors" ) // NewCommunicationInstance returns CommunicationInstance structure with http client prepared for communication with TMS backend @@ -34,7 +33,7 @@ func NewCommunicationInstance(httpClient piperHttp.Uploader, tmsUrl, uaaUrl, cli token, err := communicationInstance.getOAuthToken() if err != nil { - return communicationInstance, errors.Wrap(err, "Error fetching OAuth token") + return communicationInstance, fmt.Errorf("Error fetching OAuth token: %w", err) } clientOptions.Token = token @@ -194,7 +193,7 @@ func (communicationInstance *CommunicationInstance) UploadFileToNode(fileInfo Fi body := NodeUploadRequestEntity{ContentType: "MTA", StorageType: "FILE", NodeName: nodeName, Description: description, NamedUser: namedUser, Entries: []Entry{entry}} bodyBytes, errMarshaling := json.Marshal(body) if errMarshaling != nil { - return nodeUploadResponseEntity, errors.Wrapf(errMarshaling, "unable to marshal request body %v", body) + return nodeUploadResponseEntity, fmt.Errorf("unable to marshal request body %v: %w", body, errMarshaling) } data, errSendRequest := sendRequest(communicationInstance, http.MethodPost, "/v2/nodes/upload", bytes.NewReader(bodyBytes), header, http.StatusOK, false) @@ -226,7 +225,7 @@ func (communicationInstance *CommunicationInstance) ExportFileToNode(fileInfo Fi body := NodeUploadRequestEntity{ContentType: "MTA", StorageType: "FILE", NodeName: nodeName, Description: description, NamedUser: namedUser, Entries: []Entry{entry}} bodyBytes, errMarshaling := json.Marshal(body) if errMarshaling != nil { - return nodeUploadResponseEntity, errors.Wrapf(errMarshaling, "unable to marshal request body %v", body) + return nodeUploadResponseEntity, fmt.Errorf("unable to marshal request body %v: %w", body, errMarshaling) } data, errSendRequest := sendRequest(communicationInstance, http.MethodPost, "/v2/nodes/export", bytes.NewReader(bodyBytes), header, http.StatusOK, false) @@ -257,7 +256,7 @@ func (communicationInstance *CommunicationInstance) UpdateMtaExtDescriptor(nodeI var mtaExtDescriptor MtaExtDescriptor fileHandle, errOpenFile := os.Open(file) if errOpenFile != nil { - return mtaExtDescriptor, errors.Wrapf(errOpenFile, "unable to locate file %v", file) + return mtaExtDescriptor, fmt.Errorf("unable to locate file %v: %w", file, errOpenFile) } defer fileHandle.Close() @@ -293,7 +292,7 @@ func (communicationInstance *CommunicationInstance) UploadMtaExtDescriptorToNode var mtaExtDescriptor MtaExtDescriptor fileHandle, errOpenFile := os.Open(file) if errOpenFile != nil { - return mtaExtDescriptor, errors.Wrapf(errOpenFile, "unable to locate file %v", file) + return mtaExtDescriptor, fmt.Errorf("unable to locate file %v: %w", file, errOpenFile) } defer fileHandle.Close() @@ -326,7 +325,7 @@ func (communicationInstance *CommunicationInstance) UploadFile(file, namedUser s var fileInfo FileInfo fileHandle, errOpenFile := os.Open(file) if errOpenFile != nil { - return fileInfo, errors.Wrapf(errOpenFile, "unable to locate file %v", file) + return fileInfo, fmt.Errorf("unable to locate file %v: %w", file, errOpenFile) } defer fileHandle.Close() diff --git a/pkg/tms/tmsUtils.go b/pkg/tms/tmsUtils.go index 416d8619b..6060c3bf4 100644 --- a/pkg/tms/tmsUtils.go +++ b/pkg/tms/tmsUtils.go @@ -6,12 +6,13 @@ import ( "net/url" "sort" + "errors" + "github.com/SAP/jenkins-library/pkg/command" piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/ghodss/yaml" - "github.com/pkg/errors" "github.com/sirupsen/logrus" ) @@ -174,7 +175,7 @@ func FormNodeIdExtDescriptorMappingWithValidation(utils TmsUtils, nodeNameExtDes wrongMtaIdExtDescriptors = append(wrongMtaIdExtDescriptors, mappedValueString) } } else { - wrappedErr := errors.Wrapf(errGetYamlAsMap, "tried to parse %v as yaml, but got an error", mappedValueString) + wrappedErr := fmt.Errorf("tried to parse %v as yaml, but got an error: %w", mappedValueString, errGetYamlAsMap) errorMessage += fmt.Sprintf("%v\n", wrappedErr) } } else { diff --git a/pkg/tms/tmsUtils_test.go b/pkg/tms/tmsUtils_test.go index 2b166d1f7..9b8220c12 100644 --- a/pkg/tms/tmsUtils_test.go +++ b/pkg/tms/tmsUtils_test.go @@ -1,8 +1,9 @@ package tms import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func Test_unmarshalServiceKey(t *testing.T) { diff --git a/pkg/transportrequest/gitutils.go b/pkg/transportrequest/gitutils.go index 977ea2e3b..243027733 100644 --- a/pkg/transportrequest/gitutils.go +++ b/pkg/transportrequest/gitutils.go @@ -2,12 +2,13 @@ package transportrequest import ( "fmt" + gitUtils "github.com/SAP/jenkins-library/pkg/git" "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing/object" - "github.com/pkg/errors" + "os" "regexp" "sort" @@ -26,7 +27,7 @@ type transportRequestGitUtils struct { func (g *transportRequestGitUtils) PlainOpen(directory string) (*git.Repository, error) { r, err := gitUtils.PlainOpen(directory) if err != nil { - return nil, errors.Wrapf(err, "Unable to open git repository at '%s'", directory) + return nil, fmt.Errorf("Unable to open git repository at '%s': %w", directory, err) } return r, nil } @@ -42,23 +43,23 @@ func findIDInRange(label, from, to string, trGitUtils iTransportRequestGitUtils) workdir, err := os.Getwd() if err != nil { - return "", errors.Wrapf(err, "Cannot open git repo in current working directory '%s'", workdir) + return "", fmt.Errorf("Cannot open git repo in current working directory '%s': %w", workdir, err) } log.Entry().Infof("Opening git repo at '%s'", workdir) r, err := trGitUtils.PlainOpen(workdir) if err != nil { - return "", errors.Wrapf(err, "Unable to open git repository at '%s'", workdir) + return "", fmt.Errorf("Unable to open git repository at '%s': %w", workdir, err) } cIter, err := logRange(r, from, to) if err != nil { - return "", errors.Wrapf(err, "Cannot retrieve '%s'. Unable to resolve commits in range '%s..%s'", label, from, to) + return "", fmt.Errorf("Cannot retrieve '%s'. Unable to resolve commits in range '%s..%s': %w", label, from, to, err) } ids, err := findLabelsInCommits(cIter, label) if err != nil { - return "", errors.Wrapf(err, "Cannot retrieve '%s'. Unable to traverse commits in range '%s..%s'", label, from, to) + return "", fmt.Errorf("Cannot retrieve '%s'. Unable to traverse commits in range '%s..%s': %w", label, from, to, err) } if len(ids) > 1 { diff --git a/pkg/transportrequest/gitutils_test.go b/pkg/transportrequest/gitutils_test.go index 5359bfb69..6fcd42437 100644 --- a/pkg/transportrequest/gitutils_test.go +++ b/pkg/transportrequest/gitutils_test.go @@ -4,6 +4,9 @@ package transportrequest import ( + "io" + "testing" + pipergit "github.com/SAP/jenkins-library/pkg/git" "github.com/go-git/go-billy/v5/memfs" "github.com/go-git/go-git/v5" @@ -12,8 +15,6 @@ import ( "github.com/go-git/go-git/v5/plumbing/storer" "github.com/go-git/go-git/v5/storage/memory" "github.com/stretchr/testify/assert" - "io" - "testing" ) type commitIteratorMock struct { diff --git a/pkg/transportrequest/rfc/upload.go b/pkg/transportrequest/rfc/upload.go index a1c0786df..a3c97bfd4 100644 --- a/pkg/transportrequest/rfc/upload.go +++ b/pkg/transportrequest/rfc/upload.go @@ -1,12 +1,13 @@ package rfc import ( + "errors" "fmt" + "strconv" + "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/config/validation" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" - "strconv" ) const ( @@ -131,7 +132,7 @@ func (action *UploadAction) Perform(command Exec) error { // error chaining (the other error is not necessaryly a "predecessor" of this one). // But it is a pragmatic approach for not loosing information for trouble shooting. There // is no possibility to have something like suppressed errors. - err = errors.Wrap(err, message) + err = fmt.Errorf("%s: %w", message, err) } else { err = errors.New(message) } @@ -141,12 +142,12 @@ func (action *UploadAction) Perform(command Exec) error { log.Entry().Infof("Deploying artifact '%s' to '%s', client: '%s', instance: '%s' succeeded.", action.ApplicationURL, action.Connection.Endpoint, action.Connection.Client, action.Connection.Instance, ) - } else { - log.Entry().Warnf("Deploying artifact '%s' to '%s', client: '%s', instance: '%s' failed.", - action.ApplicationURL, action.Connection.Endpoint, action.Connection.Client, action.Connection.Instance, - ) + return nil } - return errors.Wrap(err, "cannot upload artifact") + log.Entry().Warnf("Deploying artifact '%s' to '%s', client: '%s', instance: '%s' failed.", + action.ApplicationURL, action.Connection.Endpoint, action.Connection.Client, action.Connection.Instance, + ) + return fmt.Errorf("cannot upload artifact: %w", err) } func toAbapBool(b bool) string { diff --git a/pkg/transportrequest/rfc/upload_test.go b/pkg/transportrequest/rfc/upload_test.go index 43e16e842..82fd934bf 100644 --- a/pkg/transportrequest/rfc/upload_test.go +++ b/pkg/transportrequest/rfc/upload_test.go @@ -5,9 +5,10 @@ package rfc import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/stretchr/testify/assert" - "testing" ) func TestUploadRFC(t *testing.T) { diff --git a/pkg/transportrequest/solman/create.go b/pkg/transportrequest/solman/create.go index 2e91d9c87..b241669f6 100644 --- a/pkg/transportrequest/solman/create.go +++ b/pkg/transportrequest/solman/create.go @@ -2,12 +2,13 @@ package solman import ( "bytes" + "errors" "fmt" - "github.com/SAP/jenkins-library/pkg/config/validation" - "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" "io" "strings" + + "github.com/SAP/jenkins-library/pkg/config/validation" + "github.com/SAP/jenkins-library/pkg/log" ) // CreateAction Collects all the properties we need for creating a transport request @@ -96,7 +97,7 @@ func (a *CreateAction) Perform(command Exec) (string, error) { // error chaining (the other error is not necessaryly a "predecessor" of this one). // But it is a pragmatic approach for not loosing information for trouble shooting. There // is no possibility to have something like suppressed errors. - err = errors.Wrap(err, message) + err = fmt.Errorf("%s: %w", message, err) } else { err = errors.New(message) } @@ -114,14 +115,14 @@ func (a *CreateAction) Perform(command Exec) (string, error) { a.ChangeDocumentID, a.DevelopmentSystemID, ) - } else { - log.Entry().WithError(err).Warnf("Creating transport request '%s' at '%s' failed. ChangeDocumentId: '%s', DevelopmentSystemId: '%s'", - transportRequestID, - a.Connection.Endpoint, - a.ChangeDocumentID, - a.DevelopmentSystemID, - ) + return transportRequestID, nil } + log.Entry().WithError(err).Warnf("Creating transport request '%s' at '%s' failed. ChangeDocumentId: '%s', DevelopmentSystemId: '%s'", + transportRequestID, + a.Connection.Endpoint, + a.ChangeDocumentID, + a.DevelopmentSystemID, + ) - return transportRequestID, errors.Wrap(err, "cannot create transport request") + return transportRequestID, fmt.Errorf("cannot create transport request: %w", err) } diff --git a/pkg/transportrequest/solman/create_test.go b/pkg/transportrequest/solman/create_test.go index 0723bd94d..d1a408f99 100644 --- a/pkg/transportrequest/solman/create_test.go +++ b/pkg/transportrequest/solman/create_test.go @@ -6,9 +6,10 @@ package solman import ( "bytes" "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/stretchr/testify/assert" - "testing" ) func TestSolmanCreateTransportRequest(t *testing.T) { diff --git a/pkg/transportrequest/solman/upload.go b/pkg/transportrequest/solman/upload.go index 67c80f444..ef5aa33c5 100644 --- a/pkg/transportrequest/solman/upload.go +++ b/pkg/transportrequest/solman/upload.go @@ -1,11 +1,12 @@ package solman import ( + "errors" "fmt" + "strings" + "github.com/SAP/jenkins-library/pkg/config/validation" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" - "strings" ) // FileSystem interface collecting everything which is file system @@ -117,7 +118,7 @@ func (a *UploadAction) Perform(fs FileSystem, command Exec) error { // error chaining (the other error is not necessaryly a "predecessor" of this one). // But it is a pragmatic approach for not loosing information for trouble shooting. There // is no possibility to have something like suppressed errors. - err = errors.Wrap(err, message) + err = fmt.Errorf("%s: %w", message, err) } else { err = errors.New(message) } @@ -127,10 +128,10 @@ func (a *UploadAction) Perform(fs FileSystem, command Exec) error { if err == nil { log.Entry().Infof("Deployment succeeded, artifact: '%s', endpoint: '%s'", a.File, a.Connection.Endpoint) - } else { - log.Entry().WithError(err).Warnf("Deployment failed, artifact: '%s', endpoint: '%s'", - a.File, a.Connection.Endpoint) + return nil } + log.Entry().WithError(err).Warnf("Deployment failed, artifact: '%s', endpoint: '%s'", + a.File, a.Connection.Endpoint) - return errors.Wrapf(err, "cannot upload artifact '%s'", a.File) + return fmt.Errorf("cannot upload artifact '%s': %w", a.File, err) } diff --git a/pkg/transportrequest/solman/upload_test.go b/pkg/transportrequest/solman/upload_test.go index 7c68842df..f30cab354 100644 --- a/pkg/transportrequest/solman/upload_test.go +++ b/pkg/transportrequest/solman/upload_test.go @@ -5,9 +5,10 @@ package solman import ( "fmt" + "testing" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/stretchr/testify/assert" - "testing" ) func TestSolmanUpload(t *testing.T) { diff --git a/pkg/vault/oidc.go b/pkg/vault/oidc.go index 972084b59..ea9154755 100644 --- a/pkg/vault/oidc.go +++ b/pkg/vault/oidc.go @@ -10,7 +10,6 @@ import ( "time" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) type jwtPayload struct { @@ -45,12 +44,12 @@ func getJWTPayload(token string) (*jwtPayload, error) { decodedBytes, err := base64.RawStdEncoding.DecodeString(parts[1]) if err != nil { - return nil, errors.Wrap(err, "JWT payload couldn't be decoded: %s") + return nil, fmt.Errorf("JWT payload couldn't be decoded: %w", err) } var payload jwtPayload if err = json.Unmarshal(decodedBytes, &payload); err != nil { - return nil, errors.Wrap(err, "JWT unmarshal failed") + return nil, fmt.Errorf("JWT unmarshal failed: %w", err) } return &payload, nil diff --git a/pkg/versioning/docker.go b/pkg/versioning/docker.go index eb7169f65..3553a96d1 100644 --- a/pkg/versioning/docker.go +++ b/pkg/versioning/docker.go @@ -5,8 +5,6 @@ import ( "os" "path/filepath" "strings" - - "github.com/pkg/errors" ) // Docker defines an artifact based on a Dockerfile @@ -57,7 +55,7 @@ func (d *Docker) GetVersion() (string, error) { d.initDockerfile() d.content, err = d.readFile(d.path) if err != nil { - return "", errors.Wrapf(err, "failed to read file '%v'", d.path) + return "", fmt.Errorf("failed to read file '%v': %w", d.path, err) } version := d.versionFromBaseImageTag() if len(version) == 0 { @@ -83,7 +81,7 @@ func (d *Docker) GetVersion() (string, error) { d.initDockerfile() d.content, err = d.readFile(d.path) if err != nil { - return "", errors.Wrapf(err, "failed to read file '%v'", d.path) + return "", fmt.Errorf("failed to read file '%v': %w", d.path, err) } version := d.versionFromEnv(d.versionSource) if len(version) == 0 { @@ -109,7 +107,7 @@ func (d *Docker) SetVersion(version string) error { err := d.writeFile(filepath.Join(dir, "VERSION"), []byte(version), 0700) if err != nil { - return errors.Wrap(err, "failed to write file 'VERSION'") + return fmt.Errorf("failed to write file 'VERSION': %w", err) } return nil diff --git a/pkg/versioning/gomodfile.go b/pkg/versioning/gomodfile.go index 9f1668d21..63ce226cc 100644 --- a/pkg/versioning/gomodfile.go +++ b/pkg/versioning/gomodfile.go @@ -1,13 +1,14 @@ package versioning import ( + "fmt" "os" "strings" "golang.org/x/mod/modfile" "golang.org/x/mod/module" - "github.com/pkg/errors" + "errors" ) // GoMod utility to interact with Go Modules specific versioning @@ -29,7 +30,7 @@ func (m *GoMod) init() error { if len(m.buildDescriptorContent) == 0 { content, err := m.readFile(m.path) if err != nil { - return errors.Wrapf(err, "failed to read file '%v'", m.path) + return fmt.Errorf("failed to read file '%v': %w", m.path, err) } m.buildDescriptorContent = string(content) } @@ -45,18 +46,18 @@ func (m *GoMod) GetVersion() (string, error) { if err != nil { err = m.init() if err != nil { - return "", errors.Wrapf(err, "failed to read file '%v'", m.path) + return "", fmt.Errorf("failed to read file '%v': %w", m.path, err) } parsed, err := modfile.Parse(m.path, []byte(m.buildDescriptorContent), nil) if err != nil { - return "", errors.Wrap(err, "failed to parse go.mod file") + return "", fmt.Errorf("failed to parse go.mod file: %w", err) } if parsed.Module.Mod.Version != "" { return parsed.Module.Mod.Version, nil } - return "", errors.Wrap(err, "failed to retrieve version") + return "", fmt.Errorf("failed to retrieve version: %w", err) } } artifact := &Versionfile{ @@ -86,7 +87,7 @@ func (m *GoMod) GetCoordinates() (Coordinates, error) { parsed, err := modfile.Parse(m.path, []byte(m.buildDescriptorContent), nil) if err != nil { - return result, errors.Wrap(err, "failed to parse go.mod file") + return result, fmt.Errorf("failed to parse go.mod file: %w", err) } if parsed.Module == nil { @@ -95,7 +96,7 @@ func (m *GoMod) GetCoordinates() (Coordinates, error) { // validate module path as defined by golang if err = module.CheckPath(parsed.Module.Mod.Path); err != nil { - return result, errors.Wrap(err, "failed to parse go.mod file") + return result, fmt.Errorf("failed to parse go.mod file: %w", err) } if parsed.Module.Mod.Path != "" { diff --git a/pkg/versioning/inifile.go b/pkg/versioning/inifile.go index d7b1c08e4..372bd9bb9 100644 --- a/pkg/versioning/inifile.go +++ b/pkg/versioning/inifile.go @@ -5,7 +5,6 @@ import ( "fmt" "os" - "github.com/pkg/errors" "gopkg.in/ini.v1" ) @@ -33,11 +32,11 @@ func (i *INIfile) init() error { if i.content == nil { conf, err := i.readFile(i.path) if err != nil { - return errors.Wrapf(err, "failed to read file '%v'", i.path) + return fmt.Errorf("failed to read file '%v': %w", i.path, err) } i.content, err = ini.Load(conf) if err != nil { - return errors.Wrapf(err, "failed to load content from file '%v'", i.path) + return fmt.Errorf("failed to load content from file '%v': %w", i.path, err) } } return nil @@ -80,7 +79,7 @@ func (i *INIfile) SetVersion(version string) error { i.content.WriteTo(&buf) err := i.writeFile(i.path, buf.Bytes(), 0700) if err != nil { - return errors.Wrapf(err, "failed to write file '%v'", i.path) + return fmt.Errorf("failed to write file '%v': %w", i.path, err) } return nil } diff --git a/pkg/versioning/jsonfile.go b/pkg/versioning/jsonfile.go index 9eddccf3f..b9b449e6f 100644 --- a/pkg/versioning/jsonfile.go +++ b/pkg/versioning/jsonfile.go @@ -7,7 +7,6 @@ import ( "os" "github.com/iancoleman/orderedmap" - "github.com/pkg/errors" ) // JSONfile defines an artifact using a json file for versioning @@ -43,12 +42,12 @@ func (j *JSONfile) GetVersion() (string, error) { content, err := j.readFile(j.path) if err != nil { - return "", errors.Wrapf(err, "failed to read file '%v'", j.path) + return "", fmt.Errorf("failed to read file '%v': %w", j.path, err) } err = json.Unmarshal(content, &j.content) if err != nil { - return "", errors.Wrapf(err, "failed to read json content of file '%v'", j.content) + return "", fmt.Errorf("failed to read json content of file '%v': %w", j.content, err) } version, _ := j.content.Get(j.versionField) @@ -73,11 +72,11 @@ func (j *JSONfile) SetVersion(version string) error { enc.SetEscapeHTML(false) enc.SetIndent("", " ") if err := enc.Encode(j.content); err != nil { - return errors.Wrapf(err, "failed to create json content for '%v'", j.path) + return fmt.Errorf("failed to create json content for '%v': %w", j.path, err) } err := j.writeFile(j.path, buf.Bytes(), 0700) if err != nil { - return errors.Wrapf(err, "failed to write file '%v'", j.path) + return fmt.Errorf("failed to write file '%v': %w", j.path, err) } return nil diff --git a/pkg/versioning/maven.go b/pkg/versioning/maven.go index d5de4f86d..ab0eec649 100644 --- a/pkg/versioning/maven.go +++ b/pkg/versioning/maven.go @@ -5,8 +5,6 @@ import ( "io" "github.com/SAP/jenkins-library/pkg/maven" - - "github.com/pkg/errors" ) type mavenExecRunner interface { @@ -71,7 +69,7 @@ func (m *Maven) GetPackaging() (string, error) { packaging, err := m.runner.Evaluate(&m.options, "project.packaging", m.utils) if err != nil { - return "", errors.Wrap(err, "Maven - getting packaging failed") + return "", fmt.Errorf("Maven - getting packaging failed: %w", err) } return packaging, nil } @@ -82,7 +80,7 @@ func (m *Maven) GetGroupID() (string, error) { groupID, err := m.runner.Evaluate(&m.options, "project.groupId", m.utils) if err != nil { - return "", errors.Wrap(err, "Maven - getting groupId failed") + return "", fmt.Errorf("Maven - getting groupId failed: %w", err) } return groupID, nil } @@ -93,7 +91,7 @@ func (m *Maven) GetArtifactID() (string, error) { artifactID, err := m.runner.Evaluate(&m.options, "project.artifactId", m.utils) if err != nil { - return "", errors.Wrap(err, "Maven - getting artifactId failed") + return "", fmt.Errorf("Maven - getting artifactId failed: %w", err) } return artifactID, nil } @@ -104,7 +102,7 @@ func (m *Maven) GetVersion() (string, error) { version, err := m.runner.Evaluate(&m.options, "project.version", m.utils) if err != nil { - return "", errors.Wrap(err, "Maven - getting version failed") + return "", fmt.Errorf("Maven - getting version failed: %w", err) } //ToDo: how to deal with SNAPSHOT replacement? return version, nil @@ -116,7 +114,7 @@ func (m *Maven) SetVersion(version string) error { groupID, err := m.runner.Evaluate(&m.options, "project.groupId", m.utils) if err != nil { - return errors.Wrap(err, "Maven - getting groupId failed") + return fmt.Errorf("Maven - getting groupId failed: %w", err) } opts := maven.ExecuteOptions{ PomPath: m.options.PomPath, @@ -134,7 +132,7 @@ func (m *Maven) SetVersion(version string) error { } _, err = m.runner.Execute(&opts, m.utils) if err != nil { - return errors.Wrapf(err, "Maven - setting version %v failed", version) + return fmt.Errorf("Maven - setting version %v failed: %w", version, err) } return nil } diff --git a/pkg/versioning/pip.go b/pkg/versioning/pip.go index a09661e56..5b2099dae 100644 --- a/pkg/versioning/pip.go +++ b/pkg/versioning/pip.go @@ -5,8 +5,6 @@ import ( "os" "regexp" "strings" - - "github.com/pkg/errors" ) const ( @@ -37,7 +35,7 @@ func (p *Pip) init() error { if len(p.buildDescriptorContent) == 0 { content, err := p.readFile(p.path) if err != nil { - return errors.Wrapf(err, "failed to read file '%v'", p.path) + return fmt.Errorf("failed to read file '%v': %w", p.path, err) } p.buildDescriptorContent = string(content) } @@ -53,14 +51,14 @@ func (p *Pip) GetVersion() (string, error) { if err != nil { initErr := p.init() if initErr != nil { - return "", errors.Wrapf(initErr, "failed to read file '%v'", p.path) + return "", fmt.Errorf("failed to read file '%v': %w", p.path, initErr) } if evaluateResult(p.buildDescriptorContent, VersionRegex) { compile := regexp.MustCompile(VersionRegex) values := compile.FindStringSubmatch(p.buildDescriptorContent) return values[2], nil } - return "", errors.Wrap(err, "failed to retrieve version") + return "", fmt.Errorf("failed to retrieve version: %w", err) } } artifact := &Versionfile{ @@ -80,7 +78,7 @@ func (p *Pip) SetVersion(v string) error { if err != nil { initErr := p.init() if initErr != nil { - return errors.Wrapf(initErr, "failed to read file '%v'", p.path) + return fmt.Errorf("failed to read file '%v': %w", p.path, initErr) } if evaluateResult(p.buildDescriptorContent, VersionRegex) { compile := regexp.MustCompile(VersionRegex) @@ -89,7 +87,7 @@ func (p *Pip) SetVersion(v string) error { p.buildDescriptorContent = strings.ReplaceAll(p.buildDescriptorContent, fmt.Sprintf("version=\"%v\"", values[2]), fmt.Sprintf("version=\"%v\"", v)) p.writeFile(p.path, []byte(p.buildDescriptorContent), 0600) } else { - return errors.Wrap(err, "failed to retrieve version") + return fmt.Errorf("failed to retrieve version: %w", err) } } } @@ -124,7 +122,7 @@ func (p *Pip) GetCoordinates() (Coordinates, error) { result.Version, err = p.GetVersion() if err != nil { - return result, errors.Wrap(err, "failed to retrieve coordinates") + return result, fmt.Errorf("failed to retrieve coordinates: %w", err) } return result, nil diff --git a/pkg/versioning/properties.go b/pkg/versioning/properties.go index a1b1db240..5284b3046 100644 --- a/pkg/versioning/properties.go +++ b/pkg/versioning/properties.go @@ -6,7 +6,6 @@ import ( "os" "github.com/magiconair/properties" - "github.com/pkg/errors" ) // PropertiesFile defines an artifact using a properties file for versioning @@ -29,7 +28,7 @@ func (p *PropertiesFile) init() error { var err error p.content, err = properties.LoadFile(p.path, properties.UTF8) if err != nil { - return errors.Wrapf(err, "failed to load file %v", p.path) + return fmt.Errorf("failed to load file %v: %w", p.path, err) } } return nil @@ -64,17 +63,17 @@ func (p *PropertiesFile) SetVersion(version string) error { } err = p.content.SetValue(p.versionField, version) if err != nil { - return errors.Wrapf(err, "failed to set version") + return fmt.Errorf("failed to set version: %w", err) } var propsContent bytes.Buffer _, err = p.content.Write(&propsContent, properties.UTF8) if err != nil { - return errors.Wrap(err, "failed to write version") + return fmt.Errorf("failed to write version: %w", err) } err = p.writeFile(p.path, propsContent.Bytes(), 0666) if err != nil { - return errors.Wrap(err, "failed to write file") + return fmt.Errorf("failed to write file: %w", err) } return nil } diff --git a/pkg/versioning/versionfile.go b/pkg/versioning/versionfile.go index a36d3a801..310b9bf95 100644 --- a/pkg/versioning/versionfile.go +++ b/pkg/versioning/versionfile.go @@ -1,10 +1,9 @@ package versioning import ( + "fmt" "os" "strings" - - "github.com/pkg/errors" ) // Versionfile defines an artifact containing the version in a file, e.g. VERSION @@ -42,7 +41,7 @@ func (v *Versionfile) GetVersion() (string, error) { content, err := v.readFile(v.path) if err != nil { - return "", errors.Wrapf(err, "failed to read file '%v'", v.path) + return "", fmt.Errorf("failed to read file '%v': %w", v.path, err) } return strings.TrimSpace(string(content)), nil @@ -54,7 +53,7 @@ func (v *Versionfile) SetVersion(version string) error { err := v.writeFile(v.path, []byte(version), 0700) if err != nil { - return errors.Wrapf(err, "failed to write file '%v'", v.path) + return fmt.Errorf("failed to write file '%v': %w", v.path, err) } return nil diff --git a/pkg/versioning/yamlfile.go b/pkg/versioning/yamlfile.go index 59b5109b0..e8cc3e7f0 100644 --- a/pkg/versioning/yamlfile.go +++ b/pkg/versioning/yamlfile.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/ghodss/yaml" - "github.com/pkg/errors" ) // YAMLDescriptor holds the unique identifier combination for an artifact @@ -48,11 +47,11 @@ func (y *YAMLfile) readContent() error { } content, err := y.readFile(y.path) if err != nil { - return errors.Wrapf(err, "failed to read file '%v'", y.path) + return fmt.Errorf("failed to read file '%v': %w", y.path, err) } err = yaml.Unmarshal(content, &y.content) if err != nil { - return errors.Wrapf(err, "failed to read yaml content of file '%v'", y.content) + return fmt.Errorf("failed to read yaml content of file '%v': %w", y.content, err) } return nil } @@ -60,7 +59,7 @@ func (y *YAMLfile) readContent() error { func (y *YAMLfile) readField(key string) (string, error) { err := y.readContent() if err != nil { - return "", errors.Wrapf(err, "failed to get key %s", key) + return "", fmt.Errorf("failed to get key %s: %w", key, err) } return strings.TrimSpace(fmt.Sprint(y.content[key])), nil } @@ -86,18 +85,18 @@ func (y *YAMLfile) GetVersion() (string, error) { func (y *YAMLfile) SetVersion(version string) error { err := y.readContent() if err != nil { - return errors.Wrapf(err, "failed to set version") + return fmt.Errorf("failed to set version: %w", err) } y.content[y.versionField] = version content, err := yaml.Marshal(y.content) if err != nil { - return errors.Wrapf(err, "failed to create yaml content for '%v'", y.path) + return fmt.Errorf("failed to create yaml content for '%v': %w", y.path, err) } err = y.writeFile(y.path, content, 0700) if err != nil { - return errors.Wrapf(err, "failed to write file '%v'", y.path) + return fmt.Errorf("failed to write file '%v': %w", y.path, err) } return nil diff --git a/pkg/whitesource/configHelper.go b/pkg/whitesource/configHelper.go index 018a9f7b3..e4bfceaac 100644 --- a/pkg/whitesource/configHelper.go +++ b/pkg/whitesource/configHelper.go @@ -10,7 +10,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/maven" "github.com/magiconair/properties" - "github.com/pkg/errors" ) // ConfigOption defines a dedicated WhiteSource config which can be enforced if required @@ -69,12 +68,12 @@ func (s *ScanOptions) RewriteUAConfigurationFile(utils Utils, projectName string var configContent bytes.Buffer _, err = newConfig.Write(&configContent, properties.UTF8) if err != nil { - return "", errors.Wrap(err, "failed to write properties") + return "", fmt.Errorf("failed to write properties: %w", err) } err = utils.FileWrite(newConfigFilePath, configContent.Bytes(), 0666) if err != nil { - return "", errors.Wrap(err, "failed to write file") + return "", fmt.Errorf("failed to write file: %w", err) } return newConfigFilePath, nil diff --git a/pkg/whitesource/reporting.go b/pkg/whitesource/reporting.go index 03c956f32..99c6859be 100644 --- a/pkg/whitesource/reporting.go +++ b/pkg/whitesource/reporting.go @@ -20,7 +20,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/reporting" - "github.com/pkg/errors" ) // CreateCustomVulnerabilityReport creates a vulnerability ScanReport to be used for uploading into various sinks @@ -149,12 +148,12 @@ func WriteCustomVulnerabilityReports(productName string, scan *Scan, scanReport // ignore templating errors since template is in our hands and issues will be detected with the automated tests htmlReport, _ := scanReport.ToHTML() if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } htmlReportPath := filepath.Join(ReportsDirectory, "piper_whitesource_vulnerability_report.html") if err := utils.FileWrite(htmlReportPath, htmlReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write html report") + return reportPaths, fmt.Errorf("failed to write html report: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "WhiteSource Vulnerability Report", Target: htmlReportPath}) @@ -164,11 +163,11 @@ func WriteCustomVulnerabilityReports(productName string, scan *Scan, scanReport if exists, _ := utils.DirExists(reporting.StepReportDirectory); !exists { err := utils.MkdirAll(reporting.StepReportDirectory, 0777) if err != nil { - return reportPaths, errors.Wrap(err, "failed to create step reporting directory") + return reportPaths, fmt.Errorf("failed to create step reporting directory: %w", err) } } if err := utils.FileWrite(filepath.Join(reporting.StepReportDirectory, fmt.Sprintf("whitesourceExecuteScan_oss_%v.json", ReportSha(productName, scan))), jsonReport, 0666); err != nil { - return reportPaths, errors.Wrapf(err, "failed to write json report") + return reportPaths, fmt.Errorf("failed to write json report: %w", err) } // we do not add the json report to the overall list of reports for now, // since it is just an intermediary report used as input for later @@ -335,15 +334,15 @@ func WriteSarifFile(sarif *format.SARIF, utils piperutils.FileUtils) ([]piperuti // ignore templating errors since template is in our hands and issues will be detected with the automated tests sarifReport, errorMarshall := json.Marshal(sarif) if errorMarshall != nil { - return reportPaths, errors.Wrapf(errorMarshall, "failed to marshall SARIF json file") + return reportPaths, fmt.Errorf("failed to marshall SARIF json file: %w", errorMarshall) } if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return reportPaths, errors.Wrapf(err, "failed to create report directory") + return reportPaths, fmt.Errorf("failed to create report directory: %w", err) } sarifReportPath := filepath.Join(ReportsDirectory, "piper_whitesource_vulnerability.sarif") if err := utils.FileWrite(sarifReportPath, sarifReport, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return reportPaths, errors.Wrapf(err, "failed to write SARIF file") + return reportPaths, fmt.Errorf("failed to write SARIF file: %w", err) } reportPaths = append(reportPaths, piperutils.Path{Name: "WhiteSource Vulnerability SARIF file", Target: sarifReportPath}) @@ -554,7 +553,7 @@ func transformAlertsToVulnerabilities(scan *Scan, alerts *[]Alert) []cdx.Vulnera func WriteCycloneSBOM(sbom []byte, utils piperutils.FileUtils) ([]piperutils.Path, error) { paths := []piperutils.Path{} if err := utils.MkdirAll(ReportsDirectory, 0777); err != nil { - return paths, errors.Wrapf(err, "failed to create report directory") + return paths, fmt.Errorf("failed to create report directory: %w", err) } sbomPath := filepath.Join(ReportsDirectory, "piper_whitesource_sbom.xml") @@ -562,7 +561,7 @@ func WriteCycloneSBOM(sbom []byte, utils piperutils.FileUtils) ([]piperutils.Pat // Write file if err := utils.FileWrite(sbomPath, sbom, 0666); err != nil { log.SetErrorCategory(log.ErrorConfiguration) - return paths, errors.Wrapf(err, "failed to write SARIF file") + return paths, fmt.Errorf("failed to write SARIF file: %w", err) } paths = append(paths, piperutils.Path{Name: "WhiteSource SBOM file", Target: sbomPath}) diff --git a/pkg/whitesource/scanNPM.go b/pkg/whitesource/scanNPM.go index 53ba3220f..6e2c27a41 100644 --- a/pkg/whitesource/scanNPM.go +++ b/pkg/whitesource/scanNPM.go @@ -8,7 +8,6 @@ import ( "path/filepath" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const whiteSourceConfig = "whitesource.config.json" @@ -154,7 +153,7 @@ func getNpmProjectName(modulePath string, utils Utils) (string, error) { var packageJSON = make(map[string]interface{}) err = json.Unmarshal(fileContents, &packageJSON) if err != nil { - return "", errors.Wrapf(err, "failed to unmarshall the file '%s'", modulePath) + return "", fmt.Errorf("failed to unmarshall the file '%s': %w", modulePath, err) } projectNameEntry, exists := packageJSON["name"] diff --git a/pkg/whitesource/scanPolling.go b/pkg/whitesource/scanPolling.go index b7163773f..816f3722b 100644 --- a/pkg/whitesource/scanPolling.go +++ b/pkg/whitesource/scanPolling.go @@ -2,8 +2,9 @@ package whitesource import ( "fmt" - "github.com/SAP/jenkins-library/pkg/log" "time" + + "github.com/SAP/jenkins-library/pkg/log" ) type whitesourcePoller interface { diff --git a/pkg/whitesource/scanPolling_test.go b/pkg/whitesource/scanPolling_test.go index 2dd3ccae7..825ab9b9c 100644 --- a/pkg/whitesource/scanPolling_test.go +++ b/pkg/whitesource/scanPolling_test.go @@ -4,10 +4,11 @@ package whitesource import ( - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "testing" "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBlockUntilProjectIsUpdated(t *testing.T) { diff --git a/pkg/whitesource/scanReports.go b/pkg/whitesource/scanReports.go index 43c652c96..c2f03e8da 100644 --- a/pkg/whitesource/scanReports.go +++ b/pkg/whitesource/scanReports.go @@ -8,7 +8,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) // ReportOptions defines options for downloading reports after scanning. @@ -48,13 +47,13 @@ func (s *Scan) DownloadReports(options ReportOptions, utils scanUtils, sys white func downloadVulnerabilityReport(options ReportOptions, project Project, utils scanUtils, sys whitesource) (*piperutils.Path, error) { reportBytes, err := sys.GetProjectVulnerabilityReport(project.Token, options.VulnerabilityReportFormat) if err != nil { - return nil, errors.Wrapf(err, "unable to download vulnerability report from url") + return nil, fmt.Errorf("unable to download vulnerability report from url: %w", err) } rptFileName := fmt.Sprintf("%s-vulnerability-report.%s", strings.ReplaceAll(project.Name, "/", "_"), options.VulnerabilityReportFormat) rptFileName = filepath.Join(options.ReportDirectory, rptFileName) if err := utils.FileWrite(rptFileName, reportBytes, 0644); err != nil { - return nil, errors.Wrapf(err, "unable to copy content from url to file %v", rptFileName) + return nil, fmt.Errorf("unable to copy content from url to file %v: %w", rptFileName, err) } log.Entry().Infof("Successfully downloaded vulnerability report to %s", rptFileName) @@ -65,13 +64,13 @@ func downloadVulnerabilityReport(options ReportOptions, project Project, utils s func downloadRiskReport(options ReportOptions, project Project, utils scanUtils, sys whitesource) (*piperutils.Path, error) { reportBytes, err := sys.GetProjectRiskReport(project.Token) if err != nil { - return nil, errors.Wrapf(err, "unable to download risk report from url") + return nil, fmt.Errorf("unable to download risk report from url: %w", err) } rptFileName := fmt.Sprintf("%s-risk-report.pdf", strings.ReplaceAll(project.Name, "/", "_")) rptFileName = filepath.Join(options.ReportDirectory, rptFileName) if err := utils.FileWrite(rptFileName, reportBytes, 0644); err != nil { - return nil, errors.Wrapf(err, "unable to copy content from url to file %v", rptFileName) + return nil, fmt.Errorf("unable to copy content from url to file %v: %w", rptFileName, err) } log.Entry().Infof("Successfully downloaded risk report to %s", rptFileName) diff --git a/pkg/whitesource/scanUA.go b/pkg/whitesource/scanUA.go index 4eb88e5df..ee33e7e39 100644 --- a/pkg/whitesource/scanUA.go +++ b/pkg/whitesource/scanUA.go @@ -14,7 +14,6 @@ import ( "time" "github.com/SAP/jenkins-library/pkg/log" - "github.com/pkg/errors" ) const jvmTarGz = "jvm.tar.gz" @@ -49,7 +48,7 @@ func (s *Scan) ExecuteUAScanForMTA(config *ScanOptions, utils Utils) error { mavenConfig := *config mavenConfig.BuildTool = "maven" if err := s.ExecuteUAScanInPath(&mavenConfig, utils, config.ScanPath); err != nil { - return errors.Wrap(err, "failed to run scan for maven modules of mta") + return fmt.Errorf("failed to run scan for maven modules of mta: %w", err) } } else { if pomFiles, _ := utils.Glob("**/pom.xml"); len(pomFiles) > 0 { @@ -67,7 +66,7 @@ func (s *Scan) ExecuteUAScanForMultiModuleNPM(config *ScanOptions, utils Utils) packageJSONFiles, err := utils.FindPackageJSONFiles(config) if err != nil { - return errors.Wrap(err, "failed to find package.json files") + return fmt.Errorf("failed to find package.json files: %w", err) } if len(packageJSONFiles) > 0 { npmConfig := *config @@ -77,13 +76,13 @@ func (s *Scan) ExecuteUAScanForMultiModuleNPM(config *ScanOptions, utils Utils) modulePath, _ := filepath.Split(packageJSONFile) projectName, err := getProjectNameFromPackageJSON(packageJSONFile, utils) if err != nil { - return errors.Wrapf(err, "failed retrieve project name") + return fmt.Errorf("failed retrieve project name: %w", err) } npmConfig.ProjectName = projectName // ToDo: likely needs to be refactored, AggregateProjectName should only be available if we want to force aggregation? s.AggregateProjectName = projectName if err := s.ExecuteUAScanInPath(&npmConfig, utils, modulePath); err != nil { - return errors.Wrapf(err, "failed to run scan for npm module %v", modulePath) + return fmt.Errorf("failed to run scan for npm module %v: %w", modulePath, err) } } } @@ -112,7 +111,7 @@ func (s *Scan) ExecuteUAScanInPath(config *ScanOptions, utils Utils, scanPath st utils.Stdout(&versionBuffer) err = utils.RunExecutable(javaPath, "-jar", config.AgentFileName, "-v") if err != nil { - return errors.Wrap(err, "Failed to determine UA version") + return fmt.Errorf("Failed to determine UA version: %w", err) } s.AgentVersion = strings.TrimSpace(versionBuffer.String()) log.Entry().Debugf("Read UA version %v from Stdout", s.AgentVersion) @@ -180,7 +179,7 @@ func (s *Scan) ExecuteUAScanInPath(config *ScanOptions, utils Utils, scanPath st exitCode := utils.GetExitCode() log.Entry().Infof("WhiteSource scan failed with exit code %v", exitCode) evaluateExitCode(exitCode) - return errors.Wrapf(err, "failed to execute WhiteSource scan with exit code %v", exitCode) + return fmt.Errorf("failed to execute WhiteSource scan with exit code %v: %w", exitCode, err) } return nil } @@ -216,7 +215,7 @@ func downloadAgent(config *ScanOptions, utils Utils) error { agentFile := config.AgentFileName exists, err := utils.FileExists(agentFile) if err != nil { - return errors.Wrapf(err, "failed to check if file '%s' exists", agentFile) + return fmt.Errorf("failed to check if file '%s' exists: %w", agentFile, err) } if !exists { err := utils.DownloadFile(config.AgentDownloadURL, agentFile, nil, nil) @@ -231,7 +230,7 @@ func downloadAgent(config *ScanOptions, utils Utils) error { } if err != nil { - return errors.Wrapf(err, "failed to download unified agent from URL '%s' to file '%s'", config.AgentDownloadURL, agentFile) + return fmt.Errorf("failed to download unified agent from URL '%s' to file '%s': %w", config.AgentDownloadURL, agentFile, err) } } return nil @@ -258,13 +257,13 @@ func downloadJre(config *ScanOptions, utils Utils) (string, error) { retries++ if retries >= maxRetries { log.Entry().Errorf("Download failed after %d attempts", retries) - return "", errors.Wrapf(err, "failed to download jre from URL '%s'", config.JreDownloadURL) + return "", fmt.Errorf("failed to download jre from URL '%s': %w", config.JreDownloadURL, err) } time.Sleep(1 * time.Second) } if err != nil { - return "", errors.Wrapf(err, "Even after retry failed to download jre from URL '%s'", config.JreDownloadURL) + return "", fmt.Errorf("Even after retry failed to download jre from URL '%s': %w", config.JreDownloadURL, err) } // ToDo: replace tar call with go library call @@ -272,7 +271,7 @@ func downloadJre(config *ScanOptions, utils Utils) (string, error) { err = utils.RunExecutable("tar", fmt.Sprintf("--directory=%v", jvmDir), "--strip-components=1", "-xzf", jvmTarGz) if err != nil { - return "", errors.Wrapf(err, "failed to extract %v", jvmTarGz) + return "", fmt.Errorf("failed to extract %v: %w", jvmTarGz, err) } log.Entry().Info("Java successfully installed") javaPath = filepath.Join(jvmDir, "bin", "java") @@ -298,11 +297,11 @@ func removeJre(javaPath string, utils Utils) error { func getProjectNameFromPackageJSON(packageJSONPath string, utils Utils) (string, error) { fileContents, err := utils.FileRead(packageJSONPath) if err != nil { - return "", errors.Wrapf(err, "failed to read file %v", packageJSONPath) + return "", fmt.Errorf("failed to read file %v: %w", packageJSONPath, err) } var packageJSON = make(map[string]interface{}) if err := json.Unmarshal(fileContents, &packageJSON); err != nil { - return "", errors.Wrapf(err, "failed to read file content of %v", packageJSONPath) + return "", fmt.Errorf("failed to read file content of %v: %w", packageJSONPath, err) } projectNameEntry, exists := packageJSON["name"] diff --git a/pkg/whitesource/utilsMock.go b/pkg/whitesource/utilsMock.go index d954d2522..334787491 100644 --- a/pkg/whitesource/utilsMock.go +++ b/pkg/whitesource/utilsMock.go @@ -7,9 +7,10 @@ import ( "net/http" "os" + "errors" + "github.com/SAP/jenkins-library/pkg/mock" "github.com/SAP/jenkins-library/pkg/piperutils" - "github.com/pkg/errors" ) func newTestScan(config *ScanOptions) *Scan { diff --git a/pkg/whitesource/whitesource.go b/pkg/whitesource/whitesource.go index 65e13d1be..df7d65642 100644 --- a/pkg/whitesource/whitesource.go +++ b/pkg/whitesource/whitesource.go @@ -14,7 +14,6 @@ import ( "github.com/SAP/jenkins-library/pkg/log" "github.com/SAP/jenkins-library/pkg/reporting" "github.com/package-url/packageurl-go" - "github.com/pkg/errors" ) // ReportsDirectory defines the subfolder for the WhiteSource reports which are generated @@ -374,7 +373,7 @@ func (s *System) GetProductsMetaInfo() ([]Product, error) { func (s *System) GetProductByName(productName string) (Product, error) { products, err := s.GetProductsMetaInfo() if err != nil { - return Product{}, errors.Wrap(err, "failed to retrieve WhiteSource products") + return Product{}, fmt.Errorf("failed to retrieve WhiteSource products: %w", err) } for _, p := range products { @@ -496,7 +495,7 @@ func (s *System) GetProjectByToken(projectToken string) (Project, error) { } if len(wsResponse.ProjectVitals) == 0 { - return Project{}, errors.Wrapf(err, "no project with token '%s' found in WhiteSource", projectToken) + return Project{}, fmt.Errorf("no project with token '%s' found in WhiteSource: %w", projectToken, err) } return wsResponse.ProjectVitals[0], nil @@ -506,7 +505,7 @@ func (s *System) GetProjectByToken(projectToken string) (Project, error) { func (s *System) GetProjectByName(productToken, projectName string) (Project, error) { projects, err := s.GetProjectsMetaInfo(productToken) if err != nil { - return Project{}, errors.Wrap(err, "failed to retrieve WhiteSource project meta info") + return Project{}, fmt.Errorf("failed to retrieve WhiteSource project meta info: %w", err) } for _, project := range projects { @@ -523,7 +522,7 @@ func (s *System) GetProjectByName(productToken, projectName string) (Project, er func (s *System) GetProjectsByIDs(productToken string, projectIDs []int64) ([]Project, error) { projects, err := s.GetProjectsMetaInfo(productToken) if err != nil { - return nil, errors.Wrap(err, "failed to retrieve WhiteSource project meta info") + return nil, fmt.Errorf("failed to retrieve WhiteSource project meta info: %w", err) } var projectsMatched []Project @@ -544,7 +543,7 @@ func (s *System) GetProjectTokens(productToken string, projectNames []string) ([ projectTokens := []string{} projects, err := s.GetProjectsMetaInfo(productToken) if err != nil { - return nil, errors.Wrap(err, "failed to retrieve WhiteSource project meta info") + return nil, fmt.Errorf("failed to retrieve WhiteSource project meta info: %w", err) } for _, project := range projects { @@ -600,7 +599,7 @@ func (s *System) GetProjectRiskReport(projectToken string) ([]byte, error) { respBody, err := s.sendRequest(req) if err != nil { - return nil, errors.Wrap(err, "WhiteSource getProjectRiskReport request failed") + return nil, fmt.Errorf("WhiteSource getProjectRiskReport request failed: %w", err) } return respBody, nil @@ -616,7 +615,7 @@ func (s *System) GetProjectVulnerabilityReport(projectToken string, format strin respBody, err := s.sendRequest(req) if err != nil { - return nil, errors.Wrap(err, "WhiteSource getProjectVulnerabilityReport request failed") + return nil, fmt.Errorf("WhiteSource getProjectVulnerabilityReport request failed: %w", err) } return respBody, nil @@ -722,7 +721,7 @@ func (s *System) sendRequestAndDecodeJSON(req Request, result interface{}) error func (s *System) sendRequestAndDecodeJSONRecursive(req Request, result interface{}, count *int) error { respBody, err := s.sendRequest(req) if err != nil { - return errors.Wrap(err, "sending whiteSource request failed") + return fmt.Errorf("sending whiteSource request failed: %w", err) } log.Entry().Debugf("response: %v", string(respBody)) @@ -745,7 +744,7 @@ func (s *System) sendRequestAndDecodeJSONRecursive(req Request, result interface err = s.sendRequestAndDecodeJSONRecursive(req, result, count) if err != nil { if initial { - return errors.Wrapf(err, "WhiteSource request failed after %v retries", s.maxRetries) + return fmt.Errorf("WhiteSource request failed after %v retries: %w", s.maxRetries, err) } return err } @@ -756,7 +755,7 @@ func (s *System) sendRequestAndDecodeJSONRecursive(req Request, result interface if result != nil { err = json.Unmarshal(respBody, result) if err != nil { - return errors.Wrap(err, "failed to parse WhiteSource response") + return fmt.Errorf("failed to parse WhiteSource response: %w", err) } } return nil @@ -773,7 +772,7 @@ func (s *System) sendRequest(req Request) ([]byte, error) { body, err := json.Marshal(req) if err != nil { - return responseBody, errors.Wrap(err, "failed to create WhiteSource request") + return responseBody, fmt.Errorf("failed to create WhiteSource request: %w", err) } log.Entry().Debugf("request: %v", string(body)) @@ -782,12 +781,12 @@ func (s *System) sendRequest(req Request) ([]byte, error) { headers.Add("Content-Type", "application/json") response, err := s.httpClient.SendRequest(http.MethodPost, s.serverURL, bytes.NewBuffer(body), headers, nil) if err != nil { - return responseBody, errors.Wrap(err, "failed to send request to WhiteSource") + return responseBody, fmt.Errorf("failed to send request to WhiteSource: %w", err) } defer response.Body.Close() responseBody, err = io.ReadAll(response.Body) if err != nil { - return responseBody, errors.Wrap(err, "failed to read WhiteSource response") + return responseBody, fmt.Errorf("failed to read WhiteSource response: %w", err) } return responseBody, nil diff --git a/pkg/xsuaa/xsuaa.go b/pkg/xsuaa/xsuaa.go index 09eb99c89..b88b4c4f2 100644 --- a/pkg/xsuaa/xsuaa.go +++ b/pkg/xsuaa/xsuaa.go @@ -7,8 +7,6 @@ import ( "net/http" "net/url" "time" - - "github.com/pkg/errors" ) const authHeaderKey = "Authorization" @@ -40,7 +38,7 @@ func (x *XSUAA) SetAuthHeaderIfNotPresent(header *http.Header) error { if len(x.OAuthURL) == 0 || len(x.ClientID) == 0 || len(x.ClientSecret) == 0 { - return errors.Errorf("OAuthURL, ClientID and ClientSecret have to be set on the xsuaa instance") + return fmt.Errorf("OAuthURL, ClientID and ClientSecret have to be set on the xsuaa instance") } secondsOfValidityLeft := x.CachedAuthToken.ExpiresAt.Sub(time.Now()).Seconds() @@ -80,8 +78,7 @@ func (x *XSUAA) GetBearerToken() (authToken AuthToken, err error) { response, httpErr := httpClient.Do(request) if httpErr != nil { - err = errors.Wrapf(httpErr, "fetching an access token failed: HTTP %s request to %s failed", - method, entireURL) + err = fmt.Errorf("fetching an access token failed: HTTP %s request to %s failed: %w", method, entireURL, httpErr) return } @@ -91,7 +88,7 @@ func (x *XSUAA) GetBearerToken() (authToken AuthToken, err error) { } if response.StatusCode != http.StatusOK { - err = errors.Errorf("fetching an access token failed: HTTP %s request to %s failed: "+ + err = fmt.Errorf("fetching an access token failed: HTTP %s request to %s failed: "+ "expected response code 200, got '%d', response body: '%s'", method, entireURL, response.StatusCode, bodyText) return @@ -99,12 +96,12 @@ func (x *XSUAA) GetBearerToken() (authToken AuthToken, err error) { parsingErr := json.Unmarshal(bodyText, &authToken) if err != nil { - err = errors.Wrapf(parsingErr, "HTTP response body could not be parsed as JSON: %s", bodyText) + err = fmt.Errorf("HTTP response body could not be parsed as JSON: %s: %w", bodyText, parsingErr) return } if authToken.AccessToken == "" { - err = errors.Errorf("expected authToken field 'access_token' in json response: got response body: '%s'", + err = fmt.Errorf("expected authToken field 'access_token' in json response: got response body: '%s'", bodyText) return } @@ -124,14 +121,14 @@ func setExpireTime(now time.Time, secondsValid time.Duration) time.Time { func readResponseBody(response *http.Response) ([]byte, error) { if response == nil { - return nil, errors.Errorf("did not retrieve an HTTP response") + return nil, fmt.Errorf("did not retrieve an HTTP response") } if response.Body != nil { defer response.Body.Close() } bodyText, readErr := io.ReadAll(response.Body) if readErr != nil { - return nil, errors.Wrap(readErr, "HTTP response body could not be read") + return nil, fmt.Errorf("HTTP response body could not be read: %w", readErr) } return bodyText, nil } diff --git a/pkg/xsuaa/xsuaa_test.go b/pkg/xsuaa/xsuaa_test.go index 2e6be6276..ece0468c2 100644 --- a/pkg/xsuaa/xsuaa_test.go +++ b/pkg/xsuaa/xsuaa_test.go @@ -5,13 +5,14 @@ package xsuaa import ( "encoding/base64" - "github.com/jarcoal/httpmock" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "net/http" "net/http/httptest" "testing" "time" + + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestXSUAA_GetBearerToken(t *testing.T) { diff --git a/pkg/yaml/yamlUtil.go b/pkg/yaml/yamlUtil.go index a6ab5bb2a..93b578311 100644 --- a/pkg/yaml/yamlUtil.go +++ b/pkg/yaml/yamlUtil.go @@ -3,14 +3,15 @@ package yaml import ( "bytes" "fmt" - "github.com/SAP/jenkins-library/pkg/log" - "github.com/SAP/jenkins-library/pkg/piperutils" - "gopkg.in/yaml.v3" "io" "os" "reflect" "regexp" "strings" + + "github.com/SAP/jenkins-library/pkg/log" + "github.com/SAP/jenkins-library/pkg/piperutils" + "gopkg.in/yaml.v3" ) type fUtils interface {