From dfd947b7e15b67656aa50d30b16514aa3b320fd2 Mon Sep 17 00:00:00 2001 From: Valentin <16714035+bitmaskit@users.noreply.github.com> Date: Thu, 12 Dec 2024 17:32:12 +0200 Subject: [PATCH] Update go version to 1.23 and removed some helper methods in favor of STD library (#5200) * update go version * fix go vet errors * replaces stringutils with slices std package * added slices package * 1.22.4 to 1.23.4 --------- Co-authored-by: Valentin --- .editorconfig | 1 - .github/workflows/documentation.yml | 2 +- .github/workflows/update-go-dependencies.yml | 2 +- .github/workflows/upload-go-master.yml | 2 +- .github/workflows/verify-go.yml | 10 ++--- Dockerfile | 2 +- cmd/cloudFoundryDeploy.go | 3 +- cmd/cnbBuild.go | 3 +- cmd/detectExecuteScan.go | 3 +- cmd/fortifyExecuteScan.go | 3 +- cmd/fortifyExecuteScan_test.go | 4 +- cmd/kanikoExecute.go | 3 +- cmd/newmanExecute_test.go | 4 +- cmd/terraformExecute.go | 7 ++-- go.mod | 2 +- .../golang-project1/go.mod | 2 +- .../golang-project2/go.mod | 2 +- pkg/blackduck/reporting.go | 5 ++- pkg/blackduck/reporting_test.go | 5 ++- pkg/checkmarx/checkmarx.go | 4 +- pkg/checkmarxone/checkmarxone.go | 4 +- pkg/config/evaluation.go | 3 +- pkg/docker/docker.go | 3 +- pkg/documentation/generator/description.go | 8 ++-- pkg/fortify/fortify.go | 8 ++-- pkg/generator/helper/helper.go | 4 +- pkg/maven/model.go | 4 +- pkg/maven/settings.go | 9 ++--- pkg/mock/fileUtils.go | 6 +-- pkg/multiarch/multiarch.go | 6 +-- pkg/npm/publish.go | 4 +- pkg/npm/publish_test.go | 6 +-- pkg/piperutils/maps_test.go | 17 +++++---- pkg/piperutils/slices.go | 38 +++---------------- pkg/piperutils/slices_test.go | 35 ----------------- pkg/whitesource/reporting.go | 3 +- src/com/sap/piper/PiperGoUtils.groovy | 2 +- 37 files changed, 89 insertions(+), 140 deletions(-) diff --git a/.editorconfig b/.editorconfig index 0aa9c24746..fb326c32c8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -24,4 +24,3 @@ indent_style = none indent_size = none [{go.mod,go.sum,*.go,*.golden}] indent_style = tab -indent_size = 8 diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 10febb1bb3..132997c45b 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Install Groovy run: sudo apt-get update && sudo apt-get install groovy -y diff --git a/.github/workflows/update-go-dependencies.yml b/.github/workflows/update-go-dependencies.yml index fe7f350d3a..0157cbb697 100644 --- a/.github/workflows/update-go-dependencies.yml +++ b/.github/workflows/update-go-dependencies.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Perform update run: | git checkout -B gh-action-update-golang-dependencies diff --git a/.github/workflows/upload-go-master.yml b/.github/workflows/upload-go-master.yml index 9f88021517..b56c1f8771 100644 --- a/.github/workflows/upload-go-master.yml +++ b/.github/workflows/upload-go-master.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - env: CGO_ENABLED: 0 run: | diff --git a/.github/workflows/verify-go.yml b/.github/workflows/verify-go.yml index 8226c83165..715e87f990 100644 --- a/.github/workflows/verify-go.yml +++ b/.github/workflows/verify-go.yml @@ -15,7 +15,7 @@ jobs: - uses: styfle/cancel-workflow-action@0.11.0 - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Cache Golang Packages uses: actions/cache@v3 with: @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Cache Golang Packages uses: actions/cache@v3 with: @@ -63,7 +63,7 @@ jobs: steps: - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: checkout uses: actions/checkout@v4 with: @@ -78,7 +78,7 @@ jobs: steps: - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Cache Golang Packages uses: actions/cache@v3 with: @@ -98,7 +98,7 @@ jobs: steps: - uses: actions/setup-go@v5 with: - go-version: '1.22.4' + go-version: '1.23.4' - name: Cache Golang Packages uses: actions/cache@v3 with: diff --git a/Dockerfile b/Dockerfile index 7a44ad5c56..1b6639dcb8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.22.4 AS build-env +FROM golang:1.23.4 AS build-env COPY . /build WORKDIR /build diff --git a/cmd/cloudFoundryDeploy.go b/cmd/cloudFoundryDeploy.go index 79a4e19aa2..6e9ac13662 100644 --- a/cmd/cloudFoundryDeploy.go +++ b/cmd/cloudFoundryDeploy.go @@ -6,6 +6,7 @@ import ( "io" "os" "regexp" + "slices" "sort" "strings" "time" @@ -414,7 +415,7 @@ func deployMta(config *cloudFoundryDeployOptions, mtarFilePath string, command c deployCommand = "bg-deploy" const noConfirmFlag = "--no-confirm" - if !piperutils.ContainsString(deployParams, noConfirmFlag) { + if !slices.Contains(deployParams, noConfirmFlag) { deployParams = append(deployParams, noConfirmFlag) } } diff --git a/cmd/cnbBuild.go b/cmd/cnbBuild.go index 1bc012df79..3fea419bf9 100644 --- a/cmd/cnbBuild.go +++ b/cmd/cnbBuild.go @@ -6,6 +6,7 @@ import ( "os" "path" "path/filepath" + "slices" "github.com/SAP/jenkins-library/pkg/buildpacks" "github.com/SAP/jenkins-library/pkg/buildsettings" @@ -594,7 +595,7 @@ func runCnbBuild(config *cnbBuildOptions, telemetry *buildpacks.Telemetry, image } for _, tag := range config.AdditionalTags { target := fmt.Sprintf("%s:%s", containerImage, tag) - if !piperutils.ContainsString(creatorArgs, target) { + if !slices.Contains(creatorArgs, target) { creatorArgs = append(creatorArgs, "-tag", target) } } diff --git a/cmd/detectExecuteScan.go b/cmd/detectExecuteScan.go index 5fc5561a10..9dd948f7a8 100644 --- a/cmd/detectExecuteScan.go +++ b/cmd/detectExecuteScan.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -467,7 +468,7 @@ func addDetectArgs(args []string, config detectExecuteScanOptions, utils detectU handleExcludedDirectories(&args, &config) if config.Unmap { - if !piperutils.ContainsString(config.ScanProperties, "--detect.project.codelocation.unmap=true") { + if !slices.Contains(config.ScanProperties, "--detect.project.codelocation.unmap=true") { args = append(args, "--detect.project.codelocation.unmap=true") } config.ScanProperties, _ = piperutils.RemoveAll(config.ScanProperties, "--detect.project.codelocation.unmap=false") diff --git a/cmd/fortifyExecuteScan.go b/cmd/fortifyExecuteScan.go index f2110fa552..ac8898a728 100644 --- a/cmd/fortifyExecuteScan.go +++ b/cmd/fortifyExecuteScan.go @@ -11,6 +11,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strconv" "strings" "time" @@ -211,7 +212,7 @@ func runFortifyScan(ctx context.Context, config fortifyExecuteScanOptions, sys f prID, prAuthor := determinePullRequestMerge(config) if prID != "0" { log.Entry().Debugf("Determined PR ID '%v' for merge check", prID) - if len(prAuthor) > 0 && !piperutils.ContainsString(config.Assignees, prAuthor) { + if len(prAuthor) > 0 && !slices.Contains(config.Assignees, prAuthor) { log.Entry().Debugf("Determined PR Author '%v' for result assignment", prAuthor) config.Assignees = append(config.Assignees, prAuthor) } else { diff --git a/cmd/fortifyExecuteScan_test.go b/cmd/fortifyExecuteScan_test.go index 3f47ec3a9d..b5933e46c7 100644 --- a/cmd/fortifyExecuteScan_test.go +++ b/cmd/fortifyExecuteScan_test.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "strings" "testing" "time" @@ -21,7 +22,6 @@ import ( "github.com/SAP/jenkins-library/pkg/fortify" "github.com/SAP/jenkins-library/pkg/log" - "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/versioning" "github.com/google/go-github/v45/github" @@ -421,7 +421,7 @@ func (er *execRunnerMock) Stderr(err io.Writer) { func (er *execRunnerMock) RunExecutable(e string, p ...string) error { er.numExecutions++ er.currentExecution().executable = e - if len(p) > 0 && piperutils.ContainsString(p, "--failTranslate") { + if len(p) > 0 && slices.Contains(p, "--failTranslate") { return errors.New("Translate failed") } er.currentExecution().parameters = p diff --git a/cmd/kanikoExecute.go b/cmd/kanikoExecute.go index 1937dd66af..3eaf4c9180 100644 --- a/cmd/kanikoExecute.go +++ b/cmd/kanikoExecute.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "slices" "strings" "github.com/mitchellh/mapstructure" @@ -287,7 +288,7 @@ func runKanikoExecute(config *kanikoExecuteOptions, telemetryData *telemetry.Cus } return nil - case piperutils.ContainsString(config.BuildOptions, "--destination"): + case slices.Contains(config.BuildOptions, "--destination"): log.Entry().Infof("Running Kaniko build with destination defined via buildOptions: %v", config.BuildOptions) for i, o := range config.BuildOptions { diff --git a/cmd/newmanExecute_test.go b/cmd/newmanExecute_test.go index f209005dbf..ffb7429883 100644 --- a/cmd/newmanExecute_test.go +++ b/cmd/newmanExecute_test.go @@ -6,10 +6,10 @@ package cmd import ( "os" "path/filepath" + "slices" "strings" "testing" - sliceUtils "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/google/uuid" "github.com/pkg/errors" "github.com/stretchr/testify/assert" @@ -317,7 +317,7 @@ func (e *newmanExecuteMockUtils) RunExecutable(executable string, params ...stri if e.errorOnNewmanExecution && strings.Contains(executable, "newman") { return errors.New("error on newman execution") } - if e.errorOnNewmanInstall && sliceUtils.ContainsString(params, "install") { + if e.errorOnNewmanInstall && slices.Contains(params, "install") { return errors.New("error on newman install") } diff --git a/cmd/terraformExecute.go b/cmd/terraformExecute.go index e85344b729..bd2b8fa4fe 100644 --- a/cmd/terraformExecute.go +++ b/cmd/terraformExecute.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "fmt" + "slices" "github.com/SAP/jenkins-library/pkg/command" "github.com/SAP/jenkins-library/pkg/log" @@ -53,15 +54,15 @@ func runTerraformExecute(config *terraformExecuteOptions, telemetryData *telemet args := []string{} - if piperutils.ContainsString([]string{"apply", "destroy"}, config.Command) { + if slices.Contains([]string{"apply", "destroy"}, config.Command) { args = append(args, "-auto-approve") } - if piperutils.ContainsString([]string{"apply", "plan"}, config.Command) && config.TerraformSecrets != "" { + if slices.Contains([]string{"apply", "plan"}, config.Command) && config.TerraformSecrets != "" { args = append(args, fmt.Sprintf("-var-file=%s", config.TerraformSecrets)) } - if piperutils.ContainsString([]string{"init", "validate", "plan", "apply", "destroy"}, config.Command) { + if slices.Contains([]string{"init", "validate", "plan", "apply", "destroy"}, config.Command) { args = append(args, "-no-color") } diff --git a/go.mod b/go.mod index 426478796e..847e98c055 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/SAP/jenkins-library -go 1.22.4 +go 1.23.4 require ( cloud.google.com/go/pubsub v1.36.1 diff --git a/integration/testdata/TestGolangIntegration/golang-project1/go.mod b/integration/testdata/TestGolangIntegration/golang-project1/go.mod index abe4430d88..c538e6fc76 100644 --- a/integration/testdata/TestGolangIntegration/golang-project1/go.mod +++ b/integration/testdata/TestGolangIntegration/golang-project1/go.mod @@ -1,5 +1,5 @@ module github.com/example/golang-app -go 1.22.4 +go 1.23.4 require github.com/gorilla/mux v1.8.0 diff --git a/integration/testdata/TestGolangIntegration/golang-project2/go.mod b/integration/testdata/TestGolangIntegration/golang-project2/go.mod index e0e21c40a1..d07e0384a1 100644 --- a/integration/testdata/TestGolangIntegration/golang-project2/go.mod +++ b/integration/testdata/TestGolangIntegration/golang-project2/go.mod @@ -1,3 +1,3 @@ module github.com/example/golang-app -go 1.22.4 +go 1.23.4 diff --git a/pkg/blackduck/reporting.go b/pkg/blackduck/reporting.go index 960c0c3357..a1faa41f90 100644 --- a/pkg/blackduck/reporting.go +++ b/pkg/blackduck/reporting.go @@ -6,6 +6,7 @@ import ( "fmt" "path/filepath" "runtime" + "slices" "strings" "github.com/SAP/jenkins-library/pkg/format" @@ -89,12 +90,12 @@ func CreateSarifResultFile(vulns *Vulnerabilities, projectName, projectVersion, results = append(results, result) // append taxonomies - if len(v.VulnerabilityWithRemediation.CweID) > 0 && !piperutils.ContainsString(cweIdsForTaxonomies, v.VulnerabilityWithRemediation.CweID) { + if len(v.VulnerabilityWithRemediation.CweID) > 0 && !slices.Contains(cweIdsForTaxonomies, v.VulnerabilityWithRemediation.CweID) { cweIdsForTaxonomies = append(cweIdsForTaxonomies, v.VulnerabilityWithRemediation.CweID) } // only create rule on new CVE - if !piperutils.ContainsString(collectedRules, result.RuleID) { + if !slices.Contains(collectedRules, result.RuleID) { collectedRules = append(collectedRules, result.RuleID) // set information about BlackDuck project diff --git a/pkg/blackduck/reporting_test.go b/pkg/blackduck/reporting_test.go index e0c86bc35e..6e29d3c952 100644 --- a/pkg/blackduck/reporting_test.go +++ b/pkg/blackduck/reporting_test.go @@ -6,6 +6,7 @@ package blackduck import ( "fmt" "path/filepath" + "slices" "testing" "github.com/SAP/jenkins-library/pkg/format" @@ -132,13 +133,13 @@ func TestCreateSarifResultFile(t *testing.T) { collectedRules := []string{} for _, rule := range sarif.Runs[0].Tool.Driver.Rules { - piperutils.ContainsString(vulnerabilities, rule.ID) + slices.Contains(vulnerabilities, rule.ID) collectedRules = append(collectedRules, rule.ID) } collectedResults := []string{} for _, result := range sarif.Runs[0].Results { - piperutils.ContainsString(vulnerabilities, result.RuleID) + slices.Contains(vulnerabilities, result.RuleID) collectedResults = append(collectedResults, result.RuleID) } diff --git a/pkg/checkmarx/checkmarx.go b/pkg/checkmarx/checkmarx.go index e8c4c552df..bccc87a463 100644 --- a/pkg/checkmarx/checkmarx.go +++ b/pkg/checkmarx/checkmarx.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/url" + "slices" "strconv" "strings" "time" @@ -15,7 +16,6 @@ import ( 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" "github.com/sirupsen/logrus" ) @@ -301,7 +301,7 @@ func sendRequestInternal(sys *SystemInstance, method, url string, body io.Reader defer closer.Close() } response, err := sys.client.SendRequest(method, fmt.Sprintf("%v/cxrestapi%v", sys.serverURL, url), requestBody, header, nil) - if err != nil && (response == nil || !piperutils.ContainsInt(acceptedErrorCodes, response.StatusCode)) { + if err != nil && (response == nil || !slices.Contains(acceptedErrorCodes, response.StatusCode)) { sys.recordRequestDetailsInErrorCase(requestBodyCopy, response) sys.logger.Errorf("HTTP request failed with error: %s", err) return nil, err diff --git a/pkg/checkmarxone/checkmarxone.go b/pkg/checkmarxone/checkmarxone.go index 6d5d14ab54..8f63053fb2 100644 --- a/pkg/checkmarxone/checkmarxone.go +++ b/pkg/checkmarxone/checkmarxone.go @@ -8,13 +8,13 @@ import ( "net/http" "net/url" "os" + "slices" "strconv" "strings" "time" 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" "github.com/sirupsen/logrus" ) @@ -410,7 +410,7 @@ func sendRequestInternal(sys *SystemInstance, method, url string, body io.Reader //header.Set("User-Agent", "Project-Piper.io cicd pipeline") // currently this causes some requests to fail due to unknown UA validation in the backend. response, err := sys.client.SendRequest(method, url, requestBody, header, nil) - if err != nil && (response == nil || !piperutils.ContainsInt(acceptedErrorCodes, response.StatusCode)) { + if err != nil && (response == nil || !slices.Contains(acceptedErrorCodes, response.StatusCode)) { var resBodyBytes []byte if response != nil && response.Body != nil { diff --git a/pkg/config/evaluation.go b/pkg/config/evaluation.go index 4482a2d296..af90ac9059 100644 --- a/pkg/config/evaluation.go +++ b/pkg/config/evaluation.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "path" + "slices" "strings" "github.com/pkg/errors" @@ -49,7 +50,7 @@ func (r *RunConfigV1) evaluateConditionsV1(config *Config, utils piperutils.File stepConfigCache := make(map[string]StepConfig, len(stage.Steps)) for _, step := range stage.Steps { // Consider only orchestrator-specific steps if the orchestrator limitation is set. - if len(step.Orchestrators) > 0 && !piperutils.ContainsString(step.Orchestrators, currentOrchestrator) { + if len(step.Orchestrators) > 0 && !slices.Contains(step.Orchestrators, currentOrchestrator) { continue } diff --git a/pkg/docker/docker.go b/pkg/docker/docker.go index d4f757e00c..30e287abf4 100644 --- a/pkg/docker/docker.go +++ b/pkg/docker/docker.go @@ -9,6 +9,7 @@ import ( "path" "path/filepath" "regexp" + "slices" "strings" "github.com/docker/cli/cli/config" @@ -306,7 +307,7 @@ func ImageListWithFilePath(imageName string, excludes []string, trimDir string, // ToDo: needs rework // dockerfilePath = strings.ReplaceAll(dockerfilePath, cwd, ".") - if piperutils.ContainsString(excludes, dockerfilePath) { + if slices.Contains(excludes, dockerfilePath) { log.Entry().Infof("Discard %v since it is in the exclude list %v", dockerfilePath, excludes) continue } diff --git a/pkg/documentation/generator/description.go b/pkg/documentation/generator/description.go index 744a15d1b9..022833caae 100644 --- a/pkg/documentation/generator/description.go +++ b/pkg/documentation/generator/description.go @@ -29,10 +29,10 @@ var CustomLibrarySteps = []CustomLibrary{} // CustomLibrary represents a custom library with it's custom step names, binary name and library name. type CustomLibrary struct { - Name string `yaml: "name,omitempty"` - BinaryName string `yaml: "binaryName,omitempty"` - LibraryName string `yaml: "libraryName,omitempty"` - Steps []string `yaml: "steps,omitempty"` + Name string `yaml:"name,omitempty"` + BinaryName string `yaml:"binaryName,omitempty"` + LibraryName string `yaml:"libraryName,omitempty"` + Steps []string `yaml:"steps,omitempty"` } // Replaces the StepName placeholder with the content from the yaml diff --git a/pkg/fortify/fortify.go b/pkg/fortify/fortify.go index 6d03e8e3fd..58952311d2 100644 --- a/pkg/fortify/fortify.go +++ b/pkg/fortify/fortify.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "os" + "slices" "strings" "time" @@ -30,7 +31,6 @@ import ( piperHttp "github.com/SAP/jenkins-library/pkg/http" "github.com/SAP/jenkins-library/pkg/log" - "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" @@ -529,7 +529,7 @@ func (sys *SystemInstance) ReduceIssueFilterSelectorSet(issueFilterSelectorSet * groupingList := []*models.IssueSelector{} if issueFilterSelectorSet.GroupBySet != nil { for _, group := range issueFilterSelectorSet.GroupBySet { - if piperutils.ContainsString(names, *group.DisplayName) { + if slices.Contains(names, *group.DisplayName) { log.Entry().Debugf("adding new grouping '%v' to reduced list", *group.DisplayName) groupingList = append(groupingList, group) } @@ -538,7 +538,7 @@ func (sys *SystemInstance) ReduceIssueFilterSelectorSet(issueFilterSelectorSet * filterList := []*models.IssueFilterSelector{} if issueFilterSelectorSet.FilterBySet != nil { for _, filter := range issueFilterSelectorSet.FilterBySet { - if piperutils.ContainsString(names, filter.DisplayName) { + if slices.Contains(names, filter.DisplayName) { newFilter := &models.IssueFilterSelector{} newFilter.DisplayName = filter.DisplayName newFilter.Description = filter.Description @@ -548,7 +548,7 @@ func (sys *SystemInstance) ReduceIssueFilterSelectorSet(issueFilterSelectorSet * newFilter.Value = filter.Value newFilter.SelectorOptions = []*models.SelectorOption{} for _, option := range filter.SelectorOptions { - if (nil != options && piperutils.ContainsString(options, option.DisplayName)) || options == nil || len(options) == 0 { + if (nil != options && slices.Contains(options, option.DisplayName)) || options == nil || len(options) == 0 { log.Entry().Debugf("adding selector option '%v' to list for filter selector '%v'", option.DisplayName, newFilter.DisplayName) newFilter.SelectorOptions = append(newFilter.SelectorOptions, option) } diff --git a/pkg/generator/helper/helper.go b/pkg/generator/helper/helper.go index 00301040e4..1a29d49a3c 100644 --- a/pkg/generator/helper/helper.go +++ b/pkg/generator/helper/helper.go @@ -7,11 +7,11 @@ import ( "os" "path/filepath" "reflect" + "slices" "strings" "text/template" "github.com/Masterminds/sprig" - "github.com/SAP/jenkins-library/pkg/config" "github.com/SAP/jenkins-library/pkg/piperutils" ) @@ -924,7 +924,7 @@ func mustUniqName(list []config.StepParameters) ([]config.StepParameters, error) var item config.StepParameters for i := 0; i < l; i++ { item = l2.Index(i).Interface().(config.StepParameters) - if !piperutils.ContainsString(names, item.Name) { + if !slices.Contains(names, item.Name) { names = append(names, item.Name) dest = append(dest, item) } diff --git a/pkg/maven/model.go b/pkg/maven/model.go index 2a4f9b74b2..9c5d72c273 100644 --- a/pkg/maven/model.go +++ b/pkg/maven/model.go @@ -3,8 +3,8 @@ package maven import ( "encoding/xml" "fmt" - "github.com/SAP/jenkins-library/pkg/piperutils" "path/filepath" + "slices" ) // Project describes the Maven object model. @@ -71,7 +71,7 @@ type visitUtils interface { // VisitAllMavenModules ... func VisitAllMavenModules(path string, utils visitUtils, excludes []string, callback func(info ModuleInfo) error) error { pomXMLPath := filepath.Join(path, "pom.xml") - if piperutils.ContainsString(excludes, pomXMLPath) { + if slices.Contains(excludes, pomXMLPath) { return nil } diff --git a/pkg/maven/settings.go b/pkg/maven/settings.go index 151b516ca9..880039a08a 100644 --- a/pkg/maven/settings.go +++ b/pkg/maven/settings.go @@ -218,7 +218,7 @@ func addServerTagtoProjectSettingsXML(projectSettingsFile string, altDeploymentR settingsXml, err := xml.MarshalIndent(projectSettings, "", " ") if err != nil { - fmt.Errorf("failed to marshal maven project settings xml: %w", err) + return fmt.Errorf("failed to marshal maven project settings xml: %w", err) } settingsXmlString := string(settingsXml) Replacer := strings.NewReplacer(" ", "", " ", "") @@ -226,12 +226,11 @@ func addServerTagtoProjectSettingsXML(projectSettingsFile string, altDeploymentR xmlstring := []byte(xml.Header + settingsXmlString) - err = utils.FileWrite(projectSettingsFile, xmlstring, 0777) - if err != nil { - fmt.Errorf("failed to write maven Settings xml: %w", err) + if err = utils.FileWrite(projectSettingsFile, xmlstring, 0777); err != nil { + return fmt.Errorf("failed to write maven Settings xml: %w", err) } - log.Entry().Infof("Successfully updated details in maven project settings file : '%s'", projectSettingsFile) + log.Entry().Infof("Successfully updated details in maven project settings file : '%s'", projectSettingsFile) return nil } diff --git a/pkg/mock/fileUtils.go b/pkg/mock/fileUtils.go index b8d13ff6cd..3c368aa67a 100644 --- a/pkg/mock/fileUtils.go +++ b/pkg/mock/fileUtils.go @@ -13,11 +13,11 @@ import ( "io" "os" "path/filepath" + "slices" "sort" "strings" "time" - "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/bmatcuk/doublestar" ) @@ -158,13 +158,13 @@ func (f *FilesMock) HasFile(path string) bool { // HasRemovedFile returns true if the virtual file system at one point contained an entry for the given path, // and it was removed via FileRemove(). func (f *FilesMock) HasRemovedFile(path string) bool { - return piperutils.ContainsString(f.removedFiles, f.toAbsPath(path)) + return slices.Contains(f.removedFiles, f.toAbsPath(path)) } // HasWrittenFile returns true if the virtual file system at one point contained an entry for the given path, // and it was written via FileWrite(). func (f *FilesMock) HasWrittenFile(path string) bool { - return piperutils.ContainsString(f.writtenFiles, f.toAbsPath(path)) + return slices.Contains(f.writtenFiles, f.toAbsPath(path)) } // HasCopiedFile returns true if the virtual file system at one point contained an entry for the given source and destination, diff --git a/pkg/multiarch/multiarch.go b/pkg/multiarch/multiarch.go index ce9c6cfa00..be2291651f 100644 --- a/pkg/multiarch/multiarch.go +++ b/pkg/multiarch/multiarch.go @@ -3,10 +3,10 @@ package multiarch import ( "fmt" "regexp" + "slices" "strings" "github.com/SAP/jenkins-library/pkg/log" - "github.com/SAP/jenkins-library/pkg/piperutils" ) var knownGoos = []string{"aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", "ios", "js", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows", "zos"} @@ -42,13 +42,13 @@ func ParsePlatformString(s string) (Platform, error) { p.OS = strings.Trim(matches[1], " ") - if !piperutils.ContainsString(knownGoos, p.OS) { + if !slices.Contains(knownGoos, p.OS) { log.Entry().Warningf("OS '%s' is unknown to us", p.OS) } p.Arch = strings.Trim(matches[2], " ") - if !piperutils.ContainsString(knownGoarch, p.Arch) { + if !slices.Contains(knownGoarch, p.Arch) { log.Entry().Warningf("Architecture '%s' is unknown to us", p.Arch) } diff --git a/pkg/npm/publish.go b/pkg/npm/publish.go index a5626281b3..212d62cf84 100644 --- a/pkg/npm/publish.go +++ b/pkg/npm/publish.go @@ -16,8 +16,8 @@ import ( ) type npmMinimalPackageDescriptor struct { - Name string `json:version` - Version string `json:version` + Name string `json:"name"` + Version string `json:"version"` } func (pd *npmMinimalPackageDescriptor) Scope() string { diff --git a/pkg/npm/publish_test.go b/pkg/npm/publish_test.go index bdbdf8b655..a08d7e7db6 100644 --- a/pkg/npm/publish_test.go +++ b/pkg/npm/publish_test.go @@ -6,11 +6,11 @@ package npm import ( "io" "path/filepath" + "slices" "testing" "github.com/SAP/jenkins-library/pkg/mock" - "github.com/SAP/jenkins-library/pkg/piperutils" "github.com/SAP/jenkins-library/pkg/versioning" "github.com/stretchr/testify/assert" ) @@ -548,12 +548,12 @@ func TestNpmPublish(t *testing.T) { assert.Equal(t, "publish", publishCmd.Params[0]) if len(test.wants.tarballPath) > 0 && assert.Contains(t, publishCmd.Params, "--tarball") { - tarballPath := publishCmd.Params[piperutils.FindString(publishCmd.Params, "--tarball")+1] + tarballPath := publishCmd.Params[slices.Index(publishCmd.Params, "--tarball")+1] assert.Equal(t, test.wants.tarballPath, filepath.ToSlash(tarballPath)) } if assert.Contains(t, publishCmd.Params, "--userconfig") { - effectivePublishConfigPath := publishCmd.Params[piperutils.FindString(publishCmd.Params, "--userconfig")+1] + effectivePublishConfigPath := publishCmd.Params[slices.Index(publishCmd.Params, "--userconfig")+1] assert.Regexp(t, test.wants.publishConfigPath, filepath.ToSlash(effectivePublishConfigPath)) diff --git a/pkg/piperutils/maps_test.go b/pkg/piperutils/maps_test.go index f36ab43f5c..af8472ecb0 100644 --- a/pkg/piperutils/maps_test.go +++ b/pkg/piperutils/maps_test.go @@ -4,6 +4,7 @@ package piperutils import ( + "slices" "testing" "github.com/stretchr/testify/assert" @@ -15,10 +16,10 @@ func TestKeys(t *testing.T) { intList := Keys(intStringMap) assert.Equal(t, 4, len(intList)) - assert.Equal(t, true, ContainsInt(intList, 1)) - assert.Equal(t, true, ContainsInt(intList, 2)) - assert.Equal(t, true, ContainsInt(intList, 3)) - assert.Equal(t, true, ContainsInt(intList, 4)) + assert.Equal(t, true, slices.Contains(intList, 1)) + assert.Equal(t, true, slices.Contains(intList, 2)) + assert.Equal(t, true, slices.Contains(intList, 3)) + assert.Equal(t, true, slices.Contains(intList, 4)) } func TestValues(t *testing.T) { @@ -27,8 +28,8 @@ func TestValues(t *testing.T) { intList := Values(intStringMap) assert.Equal(t, 4, len(intList)) - assert.Equal(t, true, ContainsString(intList, "eins")) - assert.Equal(t, true, ContainsString(intList, "zwei")) - assert.Equal(t, true, ContainsString(intList, "drei")) - assert.Equal(t, true, ContainsString(intList, "vier")) + assert.Equal(t, true, slices.Contains(intList, "eins")) + assert.Equal(t, true, slices.Contains(intList, "zwei")) + assert.Equal(t, true, slices.Contains(intList, "drei")) + assert.Equal(t, true, slices.Contains(intList, "vier")) } diff --git a/pkg/piperutils/slices.go b/pkg/piperutils/slices.go index 5b7ea72131..c5f7bbf49b 100644 --- a/pkg/piperutils/slices.go +++ b/pkg/piperutils/slices.go @@ -5,32 +5,6 @@ import ( "strings" ) -// ContainsInt checks whether the element is part of the slice -func ContainsInt(s []int, e int) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - -// ContainsString checks whether the element is part of the slice -func ContainsString(s []string, e string) bool { - return FindString(s, e) >= 0 -} - -// FindString returns the position of element e in the given slice or -1 if it's not in -func FindString(s []string, e string) int { - for i, a := range s { - if a == e { - return i - } - } - - return -1 -} - // ContainsStringPart checks whether the element is contained as part of one of the elements of the slice func ContainsStringPart(s []string, part string) bool { for _, a := range s { @@ -43,14 +17,14 @@ func ContainsStringPart(s []string, part string) bool { // RemoveAll removes all instances of element from the slice and returns a truncated slice as well as // a boolean to indicate whether at least one element was found and removed. -func RemoveAll(s []string, e string) ([]string, bool) { - var r []string - for _, a := range s { - if a != e { - r = append(r, a) +func RemoveAll(arr []string, item string) ([]string, bool) { + res := make([]string, 0, len(arr)) + for _, a := range arr { + if a != item { + res = append(res, a) } } - return r, len(s) != len(r) + return res, len(arr) != len(res) } // Prefix adds a prefix to each element of the slice diff --git a/pkg/piperutils/slices_test.go b/pkg/piperutils/slices_test.go index bd10429153..fd156ad019 100644 --- a/pkg/piperutils/slices_test.go +++ b/pkg/piperutils/slices_test.go @@ -9,41 +9,6 @@ import ( "github.com/stretchr/testify/assert" ) -func TestContainsInt(t *testing.T) { - var intList []int - assert.Equal(t, false, ContainsInt(intList, 4)) - - intList = append(intList, 1, 2, 3, 4, 5, 6, 20) - assert.Equal(t, true, ContainsInt(intList, 20)) - assert.Equal(t, true, ContainsInt(intList, 1)) - assert.Equal(t, true, ContainsInt(intList, 4)) - assert.Equal(t, false, ContainsInt(intList, 13)) -} - -func TestContainsString(t *testing.T) { - var stringList []string - assert.False(t, ContainsString(stringList, "test")) - assert.False(t, ContainsString(stringList, "")) - - stringList = append(stringList, "", "foo", "bar", "foo") - assert.True(t, ContainsString(stringList, "")) - assert.True(t, ContainsString(stringList, "bar")) - assert.True(t, ContainsString(stringList, "foo")) - assert.False(t, ContainsString(stringList, "baz")) -} - -func TestFindString(t *testing.T) { - var stringList []string - assert.Equal(t, -1, FindString(stringList, "test")) - assert.Equal(t, -1, FindString(stringList, "")) - - stringList = append(stringList, "", "foo", "bar", "foo") - assert.Equal(t, 0, FindString(stringList, "")) - assert.Equal(t, 2, FindString(stringList, "bar")) - assert.Equal(t, 1, FindString(stringList, "foo")) - assert.Equal(t, -1, FindString(stringList, "baz")) -} - func TestRemoveAll(t *testing.T) { t.Parallel() t.Run("empty array", func(t *testing.T) { diff --git a/pkg/whitesource/reporting.go b/pkg/whitesource/reporting.go index 56e5cefa0d..03c956f32f 100644 --- a/pkg/whitesource/reporting.go +++ b/pkg/whitesource/reporting.go @@ -8,6 +8,7 @@ import ( "fmt" "path/filepath" "runtime" + "slices" "sort" "strings" "time" @@ -217,7 +218,7 @@ func CreateSarifResultFile(scan *Scan, alerts *[]Alert) *format.SARIF { sarif.Runs[0].Results = append(sarif.Runs[0].Results, result) // only create rule on new CVE - if !piperutils.ContainsString(collectedRules, ruleId) { + if !slices.Contains(collectedRules, ruleId) { collectedRules = append(collectedRules, ruleId) sarifRule := *new(format.SarifRule) diff --git a/src/com/sap/piper/PiperGoUtils.groovy b/src/com/sap/piper/PiperGoUtils.groovy index 3c2f63036e..f4765de7da 100644 --- a/src/com/sap/piper/PiperGoUtils.groovy +++ b/src/com/sap/piper/PiperGoUtils.groovy @@ -30,7 +30,7 @@ class PiperGoUtils implements Serializable { if (steps.env.REPOSITORY_UNDER_TEST && steps.env.LIBRARY_VERSION_UNDER_TEST) { steps.echo("Running in a consumer test, building unit-under-test binary for verification.") - steps.dockerExecute(script: steps, dockerImage: 'golang:1.22.4', dockerOptions: '-u 0', dockerEnvVars: [ + steps.dockerExecute(script: steps, dockerImage: 'golang:1.23.4', dockerOptions: '-u 0', dockerEnvVars: [ REPOSITORY_UNDER_TEST: steps.env.REPOSITORY_UNDER_TEST, LIBRARY_VERSION_UNDER_TEST: steps.env.LIBRARY_VERSION_UNDER_TEST ]) {