From be6aebd9ed4a71b91727a8a09437825ccfb52330 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Wed, 1 Jan 2025 12:47:18 +0100 Subject: [PATCH] chore: enable strconcat rule from perfsprint Signed-off-by: Matthieu MOREL --- .golangci.yaml | 2 +- magefiles/magefile.go | 2 +- pkg/cache/redis_test.go | 16 +++++++------- pkg/commands/app.go | 2 +- pkg/commands/artifact/run.go | 7 ++----- pkg/dependency/id.go | 4 ++-- pkg/dependency/parser/golang/binary/parse.go | 3 +-- pkg/dependency/parser/golang/mod/parse.go | 3 +-- pkg/dependency/parser/java/pom/artifact.go | 2 +- pkg/dependency/parser/java/pom/pom.go | 2 +- pkg/dependency/parser/ruby/gemspec/parse.go | 9 ++++---- .../analyzer/imgconf/dockerfile/dockerfile.go | 2 +- .../analyzer/language/rust/cargo/cargo.go | 3 +-- pkg/fanal/analyzer/secret/secret.go | 3 +-- pkg/fanal/applier/docker.go | 4 ++-- pkg/fanal/image/daemon/image_test.go | 3 +-- pkg/fanal/image/image_test.go | 21 +++++++++---------- pkg/fanal/test/integration/docker/docker.go | 2 +- pkg/flag/db_flags.go | 4 ++-- pkg/flag/options.go | 2 +- pkg/iac/adapters/arm/database/postgresql.go | 3 +-- pkg/iac/detection/detect_test.go | 8 +++---- pkg/iac/rego/metadata.go | 2 +- pkg/iac/scan/result.go | 5 +++-- .../scanners/azure/functions/utc_now_test.go | 3 ++- .../scanners/cloudformation/parser/fn_sub.go | 2 +- .../cloudformation/parser/intrinsics.go | 5 ++--- .../parser/property_conversion.go | 2 +- .../scanners/terraform/executor/executor.go | 5 +++-- .../terraform/parser/funcs/collection.go | 2 +- .../terraform/parser/funcs/datetime.go | 3 ++- .../terraform/parser/resolvers/registry.go | 2 +- pkg/iac/terraform/module.go | 2 +- pkg/iac/terraform/presets.go | 3 +-- pkg/iac/terraform/resource_block.go | 10 ++++----- pkg/k8s/commands/run.go | 3 +-- pkg/k8s/report/table.go | 2 +- pkg/k8s/writer.go | 3 +-- pkg/misconf/scanner.go | 2 +- pkg/rekor/client.go | 3 +-- pkg/remote/remote.go | 3 +-- pkg/remote/remote_test.go | 16 +++++++------- pkg/report/table/misconfig.go | 5 +++-- pkg/report/table/secret.go | 3 ++- pkg/report/table/vulnerability.go | 5 +---- pkg/sbom/spdx/marshal.go | 7 ++++--- pkg/sbom/spdx/unmarshal.go | 3 +-- pkg/scanner/local/scan.go | 3 +-- pkg/vex/oci_test.go | 2 +- 49 files changed, 99 insertions(+), 114 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 9249f9308e91..6e5a28774a50 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -91,7 +91,7 @@ linters-settings: # Optimizes `fmt.Sprintf` with only one argument. sprintf1: false # Optimizes into strings concatenation. - strconcat: false + strconcat: true revive: ignore-generated-header: true testifylint: diff --git a/magefiles/magefile.go b/magefiles/magefile.go index 6adff2d92864..d3566487b225 100644 --- a/magefiles/magefile.go +++ b/magefiles/magefile.go @@ -54,7 +54,7 @@ func buildLdflags() (string, error) { if err != nil { return "", err } - return fmt.Sprintf("-s -w -X=github.com/aquasecurity/trivy/pkg/version/app.ver=%s", ver), nil + return "-s -w -X=github.com/aquasecurity/trivy/pkg/version/app.ver=" + ver, nil } type Tool mg.Namespace diff --git a/pkg/cache/redis_test.go b/pkg/cache/redis_test.go index 3cc8bbd702ad..5782c1a2cac5 100644 --- a/pkg/cache/redis_test.go +++ b/pkg/cache/redis_test.go @@ -66,7 +66,7 @@ func TestRedisCache_PutArtifact(t *testing.T) { addr = "dummy:16379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) err = c.PutArtifact(tt.args.artifactID, tt.args.artifactConfig) @@ -152,7 +152,7 @@ func TestRedisCache_PutBlob(t *testing.T) { addr = "dummy:16379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) err = c.PutBlob(tt.args.blobID, tt.args.blobConfig) @@ -234,7 +234,7 @@ func TestRedisCache_GetArtifact(t *testing.T) { addr = "dummy:16379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) got, err := c.GetArtifact(tt.artifactID) @@ -324,7 +324,7 @@ func TestRedisCache_GetBlob(t *testing.T) { addr = "dummy:16379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) got, err := c.GetBlob(tt.blobID) @@ -433,7 +433,7 @@ func TestRedisCache_MissingBlobs(t *testing.T) { addr = "dummy:6379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) missingArtifact, missingBlobIDs, err := c.MissingBlobs(tt.args.artifactID, tt.args.blobIDs) @@ -456,7 +456,7 @@ func TestRedisCache_Close(t *testing.T) { defer s.Close() t.Run("close", func(t *testing.T) { - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", s.Addr()), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+s.Addr(), "", "", "", false, 0) require.NoError(t, err) closeErr := c.Close() @@ -478,7 +478,7 @@ func TestRedisCache_Clear(t *testing.T) { s.Set("foo", "bar") t.Run("clear", func(t *testing.T) { - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", s.Addr()), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+s.Addr(), "", "", "", false, 0) require.NoError(t, err) require.NoError(t, c.Clear()) @@ -532,7 +532,7 @@ func TestRedisCache_DeleteBlobs(t *testing.T) { addr = "dummy:16379" } - c, err := cache.NewRedisCache(fmt.Sprintf("redis://%s", addr), "", "", "", false, 0) + c, err := cache.NewRedisCache("redis://"+addr, "", "", "", false, 0) require.NoError(t, err) err = c.DeleteBlobs(tt.args.blobIDs) diff --git a/pkg/commands/app.go b/pkg/commands/app.go index 922ba6e29ba6..6ebe5d30e87c 100644 --- a/pkg/commands/app.go +++ b/pkg/commands/app.go @@ -136,7 +136,7 @@ func loadPluginCommands() []*cobra.Command { for _, p := range plugins { p := p cmd := &cobra.Command{ - Use: fmt.Sprintf("%s [flags]", p.Name), + Use: p.Name + " [flags]", Short: p.Summary, Long: p.Description, GroupID: groupPlugin, diff --git a/pkg/commands/artifact/run.go b/pkg/commands/artifact/run.go index 8769ede2b8cb..ec1a69620cdc 100644 --- a/pkg/commands/artifact/run.go +++ b/pkg/commands/artifact/run.go @@ -341,16 +341,13 @@ func Run(ctx context.Context, opts flag.Options, targetKind TargetKind) (err err defer func() { if errors.Is(err, context.DeadlineExceeded) { // e.g. https://aquasecurity.github.io/trivy/latest/docs/configuration/ - log.WarnContext(ctx, fmt.Sprintf("Provide a higher timeout value, see %s", doc.URL("/docs/configuration/", ""))) + log.WarnContext(ctx, "Provide a higher timeout value, see "+doc.URL("/docs/configuration/", "")) } }() if opts.ServerAddr != "" && opts.Scanners.AnyEnabled(types.MisconfigScanner, types.SecretScanner) { log.WarnContext(ctx, - fmt.Sprintf( - "Trivy runs in client/server mode, but misconfiguration and license scanning will be done on the client side, see %s", - doc.URL("/docs/references/modes/client-server", ""), - ), + "Trivy runs in client/server mode, but misconfiguration and license scanning will be done on the client side, see "+doc.URL("/docs/references/modes/client-server", ""), ) } diff --git a/pkg/dependency/id.go b/pkg/dependency/id.go index 12ef6ef773b3..309abe946c5a 100644 --- a/pkg/dependency/id.go +++ b/pkg/dependency/id.go @@ -1,7 +1,7 @@ package dependency import ( - "fmt" + "strconv" "strings" "github.com/mitchellh/hashstructure/v2" @@ -52,5 +52,5 @@ func UID(filePath string, pkg types.Package) string { if err != nil { log.Warn("Failed to calculate the package hash", log.String("pkg", pkg.Name), log.Err(err)) } - return fmt.Sprintf("%x", hash) + return strconv.FormatUint(hash, 16) } diff --git a/pkg/dependency/parser/golang/binary/parse.go b/pkg/dependency/parser/golang/binary/parse.go index 617303dd5497..206064c5ad2b 100644 --- a/pkg/dependency/parser/golang/binary/parse.go +++ b/pkg/dependency/parser/golang/binary/parse.go @@ -3,7 +3,6 @@ package binary import ( "cmp" "debug/buildinfo" - "fmt" "runtime/debug" "slices" "sort" @@ -60,7 +59,7 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependenc stdlibVersion := strings.TrimPrefix(info.GoVersion, "go") stdlibVersion, _, _ = strings.Cut(stdlibVersion, " ") // Add the `v` prefix to be consistent with module and dependency versions. - stdlibVersion = fmt.Sprintf("v%s", stdlibVersion) + stdlibVersion = "v" + stdlibVersion ldflags := p.ldFlags(info.Settings) pkgs := make(ftypes.Packages, 0, len(info.Deps)+2) diff --git a/pkg/dependency/parser/golang/mod/parse.go b/pkg/dependency/parser/golang/mod/parse.go index f108b2101890..36b0bc868a01 100644 --- a/pkg/dependency/parser/golang/mod/parse.go +++ b/pkg/dependency/parser/golang/mod/parse.go @@ -1,7 +1,6 @@ package mod import ( - "fmt" "io" "regexp" "sort" @@ -96,7 +95,7 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependenc Name: "stdlib", // Our versioning library doesn't support canonical (goX.Y.Z) format, // So we need to add `v` prefix for consistency (with module and dependency versions). - Version: fmt.Sprintf("v%s", toolchainVer), + Version: "v" + toolchainVer, Relationship: ftypes.RelationshipDirect, // Considered a direct dependency as the main module depends on the standard packages. } } diff --git a/pkg/dependency/parser/java/pom/artifact.go b/pkg/dependency/parser/java/pom/artifact.go index 00f4843f0b9d..5e26dbeb4426 100644 --- a/pkg/dependency/parser/java/pom/artifact.go +++ b/pkg/dependency/parser/java/pom/artifact.go @@ -170,7 +170,7 @@ func evaluateVariable(s string, props map[string]string, seenProps []string) str func printLoopedPropertiesStack(env string, usedProps []string) { var s string for _, prop := range usedProps { - s += fmt.Sprintf("%s -> ", prop) + s += prop + " -> " } log.Warn("Lopped properties were detected", log.String("prop", s+env)) } diff --git a/pkg/dependency/parser/java/pom/pom.go b/pkg/dependency/parser/java/pom/pom.go index 695a9feb950a..19a2b044680e 100644 --- a/pkg/dependency/parser/java/pom/pom.go +++ b/pkg/dependency/parser/java/pom/pom.go @@ -69,7 +69,7 @@ func (p *pom) projectProperties() map[string]string { } // e.g. ${project.groupId} - key := fmt.Sprintf("project.%s", k) + key := "project." + k projectProperties[key] = v // It is deprecated, but still available. diff --git a/pkg/dependency/parser/ruby/gemspec/parse.go b/pkg/dependency/parser/ruby/gemspec/parse.go index 6fa0b140deda..db6201406336 100644 --- a/pkg/dependency/parser/ruby/gemspec/parse.go +++ b/pkg/dependency/parser/ruby/gemspec/parse.go @@ -2,7 +2,6 @@ package gemspec import ( "bufio" - "fmt" "regexp" "strings" @@ -64,19 +63,19 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) (pkgs []ftypes.Package, deps []ftypes // Capture name, version, license, and licenses switch { - case strings.HasPrefix(line, fmt.Sprintf("%s.name", newVar)): + case strings.HasPrefix(line, newVar+".name"): // https://guides.rubygems.org/specification-reference/#name name = findSubString(nameRegexp, line, "name") name = trim(name) - case strings.HasPrefix(line, fmt.Sprintf("%s.version", newVar)): + case strings.HasPrefix(line, newVar+".version"): // https://guides.rubygems.org/specification-reference/#version version = findSubString(versionRegexp, line, "version") version = trim(version) - case strings.HasPrefix(line, fmt.Sprintf("%s.licenses", newVar)): + case strings.HasPrefix(line, newVar+".licenses"): // https://guides.rubygems.org/specification-reference/#licenses= license = findSubString(licensesRegexp, line, "licenses") license = parseLicenses(license) - case strings.HasPrefix(line, fmt.Sprintf("%s.license", newVar)): + case strings.HasPrefix(line, newVar+".license"): // https://guides.rubygems.org/specification-reference/#license= license = findSubString(licenseRegexp, line, "license") license = trim(license) diff --git a/pkg/fanal/analyzer/imgconf/dockerfile/dockerfile.go b/pkg/fanal/analyzer/imgconf/dockerfile/dockerfile.go index 35a4fc12fea1..52ba9ebea113 100644 --- a/pkg/fanal/analyzer/imgconf/dockerfile/dockerfile.go +++ b/pkg/fanal/analyzer/imgconf/dockerfile/dockerfile.go @@ -98,7 +98,7 @@ func (a *historyAnalyzer) Analyze(ctx context.Context, input analyzer.ConfigAnal } if !userFound && input.Config.Config.User != "" { - user := fmt.Sprintf("USER %s", input.Config.Config.User) + user := "USER " + input.Config.Config.User dockerfile.WriteString(user) } diff --git a/pkg/fanal/analyzer/language/rust/cargo/cargo.go b/pkg/fanal/analyzer/language/rust/cargo/cargo.go index ab436bf95fe2..f64524511c99 100644 --- a/pkg/fanal/analyzer/language/rust/cargo/cargo.go +++ b/pkg/fanal/analyzer/language/rust/cargo/cargo.go @@ -3,7 +3,6 @@ package cargo import ( "context" "errors" - "fmt" "io" "io/fs" "maps" @@ -238,7 +237,7 @@ func (a cargoAnalyzer) matchVersion(currentVersion, constraint string) (bool, er // - 1.2.* -> 1.2.* // - ^1.2 -> ^1.2 if _, err := goversion.Parse(constraint); err == nil { - constraint = fmt.Sprintf("^%s", constraint) + constraint = "^" + constraint } ver, err := semver.Parse(currentVersion) diff --git a/pkg/fanal/analyzer/secret/secret.go b/pkg/fanal/analyzer/secret/secret.go index bdb3e96d1428..c73cd561e96c 100644 --- a/pkg/fanal/analyzer/secret/secret.go +++ b/pkg/fanal/analyzer/secret/secret.go @@ -3,7 +3,6 @@ package secret import ( "bytes" "context" - "fmt" "io" "os" "path/filepath" @@ -131,7 +130,7 @@ func (a *SecretAnalyzer) Analyze(_ context.Context, input analyzer.AnalysisInput // Also, paths to these files do not have "/" prefix. // We need to add a "/" prefix to properly filter paths from the config file. if input.Dir == "" { // add leading `/` for files extracted from image - filePath = fmt.Sprintf("/%s", filePath) + filePath = "/" + filePath } result := a.scanner.Scan(secret.ScanArgs{ diff --git a/pkg/fanal/applier/docker.go b/pkg/fanal/applier/docker.go index c14c95538c65..8923596bd578 100644 --- a/pkg/fanal/applier/docker.go +++ b/pkg/fanal/applier/docker.go @@ -115,7 +115,7 @@ func ApplyLayers(layers []ftypes.BlobInfo) ftypes.ArtifactDetail { // Apply OS packages for _, pkgInfo := range layer.PackageInfos { - key := fmt.Sprintf("%s/type:ospkg", pkgInfo.FilePath) + key := pkgInfo.FilePath + "/type:ospkg" nestedMap.SetByString(key, sep, pkgInfo) } @@ -131,7 +131,7 @@ func ApplyLayers(layers []ftypes.BlobInfo) ftypes.ArtifactDetail { Digest: layer.Digest, DiffID: layer.DiffID, } - key := fmt.Sprintf("%s/type:config", config.FilePath) + key := config.FilePath + "/type:config" nestedMap.SetByString(key, sep, config) } diff --git a/pkg/fanal/image/daemon/image_test.go b/pkg/fanal/image/daemon/image_test.go index 35ac8f278137..aded02998fc5 100644 --- a/pkg/fanal/image/daemon/image_test.go +++ b/pkg/fanal/image/daemon/image_test.go @@ -1,7 +1,6 @@ package daemon import ( - "fmt" "os" "path/filepath" "runtime" @@ -33,7 +32,7 @@ func TestMain(m *testing.M) { te := engine.NewDockerEngine(opt) defer te.Close() - os.Setenv("DOCKER_HOST", fmt.Sprintf("tcp://%s", te.Listener.Addr().String())) + os.Setenv("DOCKER_HOST", "tcp://"+te.Listener.Addr().String()) os.Exit(m.Run()) } diff --git a/pkg/fanal/image/image_test.go b/pkg/fanal/image/image_test.go index 2728ddc45184..0e8c16ac33b1 100644 --- a/pkg/fanal/image/image_test.go +++ b/pkg/fanal/image/image_test.go @@ -2,7 +2,6 @@ package image import ( "context" - "fmt" "net/http/httptest" "testing" "time" @@ -39,7 +38,7 @@ func setupEngineAndRegistry(t *testing.T) (*httptest.Server, *httptest.Server) { Auth: auth.Auth{}, }) - t.Setenv("DOCKER_HOST", fmt.Sprintf("tcp://%s", te.Listener.Addr().String())) + t.Setenv("DOCKER_HOST", "tcp://"+te.Listener.Addr().String()) return te, tr } @@ -154,7 +153,7 @@ func TestNewDockerImage(t *testing.T) { { name: "happy path with Docker Registry", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", }, wantID: "sha256:af341ccd2df8b0e2d67cf8dd32e087bfda4e5756ebd1c76bbf3efa0dc246590e", wantRepoTags: []string{serverAddr + "/library/alpine:3.10"}, @@ -202,7 +201,7 @@ func TestNewDockerImage(t *testing.T) { { name: "happy path with insecure Docker Registry", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.ImageOptions{ RegistryOptions: types.RegistryOptions{ Credentials: []types.Credential{ @@ -260,14 +259,14 @@ func TestNewDockerImage(t *testing.T) { { name: "sad path with invalid tag", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.11!!!", serverAddr), + imageName: serverAddr + "/library/alpine:3.11!!!", }, wantErr: true, }, { name: "sad path with non-exist image", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:100", serverAddr), + imageName: serverAddr + "/library/alpine:100", }, wantErr: true, }, @@ -343,7 +342,7 @@ func TestNewDockerImageWithPrivateRegistry(t *testing.T) { { name: "happy path with private Docker Registry", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.ImageOptions{ RegistryOptions: types.RegistryOptions{ Credentials: []types.Credential{ @@ -360,7 +359,7 @@ func TestNewDockerImageWithPrivateRegistry(t *testing.T) { { name: "happy path with registry token", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.ImageOptions{ RegistryOptions: types.RegistryOptions{ RegistryToken: registryToken, @@ -372,14 +371,14 @@ func TestNewDockerImageWithPrivateRegistry(t *testing.T) { { name: "sad path without a credential", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.11", serverAddr), + imageName: serverAddr + "/library/alpine:3.11", }, wantErr: "unexpected status code 401", }, { name: "sad path with invalid registry token", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.11", serverAddr), + imageName: serverAddr + "/library/alpine:3.11", option: types.ImageOptions{ RegistryOptions: types.RegistryOptions{ RegistryToken: registryToken + "invalid", @@ -542,7 +541,7 @@ func TestDockerPlatformArguments(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - imageName := fmt.Sprintf("%s/library/alpine:3.10", serverAddr) + imageName := serverAddr + "/library/alpine:3.10" tt.args.option.ImageSources = types.AllImageSources _, cleanup, err := NewContainerImage(context.Background(), imageName, tt.args.option) defer cleanup() diff --git a/pkg/fanal/test/integration/docker/docker.go b/pkg/fanal/test/integration/docker/docker.go index 82a1671fb8d1..ab5a6a4198ce 100644 --- a/pkg/fanal/test/integration/docker/docker.go +++ b/pkg/fanal/test/integration/docker/docker.go @@ -42,7 +42,7 @@ func (c RegistryConfig) GetRegistryAuth() (string, error) { } func (c RegistryConfig) GetBasicAuthorization() string { - return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.Username, c.Password)))) + return "Basic " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.Username, c.Password))) } type Docker struct { diff --git a/pkg/flag/db_flags.go b/pkg/flag/db_flags.go index cea4b82eaec6..c6887c98292e 100644 --- a/pkg/flag/db_flags.go +++ b/pkg/flag/db_flags.go @@ -1,7 +1,7 @@ package flag import ( - "fmt" + "strconv" "github.com/google/go-containerregistry/pkg/name" "golang.org/x/xerrors" @@ -188,7 +188,7 @@ func parseRepository(repo string, dbSchemaVersion int) (name.Reference, error) { return dbRepository, nil } - dbRepository = t.Tag(fmt.Sprint(dbSchemaVersion)) + dbRepository = t.Tag(strconv.Itoa(dbSchemaVersion)) log.Info("Adding schema version to the DB repository for backward compatibility", log.String("repository", dbRepository.String())) diff --git a/pkg/flag/options.go b/pkg/flag/options.go index a3bcb0f61ec2..117d1a2e62d9 100644 --- a/pkg/flag/options.go +++ b/pkg/flag/options.go @@ -664,7 +664,7 @@ func (f *Flags) Usages(cmd *cobra.Command) string { continue } - usages += fmt.Sprintf("%s Flags\n", group.Name()) + usages += group.Name() + " Flags\n" usages += flags.FlagUsages() + "\n" } return strings.TrimSpace(usages) diff --git a/pkg/iac/adapters/arm/database/postgresql.go b/pkg/iac/adapters/arm/database/postgresql.go index 155667c65f39..ecc912ebf381 100644 --- a/pkg/iac/adapters/arm/database/postgresql.go +++ b/pkg/iac/adapters/arm/database/postgresql.go @@ -1,7 +1,6 @@ package database import ( - "fmt" "strings" "github.com/aquasecurity/trivy/pkg/iac/providers/azure/database" @@ -33,7 +32,7 @@ func adaptPostgreSQLServer(resource azure.Resource, deployment azure.Deployment) func adaptPostgreSQLConfiguration(resource azure.Resource, deployment azure.Deployment) database.PostgresSQLConfig { - parent := fmt.Sprintf("%s/", resource.Name.AsString()) + parent := resource.Name.AsString() + "/" config := database.PostgresSQLConfig{ Metadata: resource.Metadata, diff --git a/pkg/iac/detection/detect_test.go b/pkg/iac/detection/detect_test.go index f082220f2f00..622674618e01 100644 --- a/pkg/iac/detection/detect_test.go +++ b/pkg/iac/detection/detect_test.go @@ -454,24 +454,24 @@ rules: } func BenchmarkIsType_SmallFile(b *testing.B) { - data, err := os.ReadFile(fmt.Sprintf("./testdata/%s", "small.file")) + data, err := os.ReadFile("./testdata/" + "small.file") require.NoError(b, err) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - _ = IsType(fmt.Sprintf("./testdata/%s", "small.file"), bytes.NewReader(data), FileTypeAzureARM) + _ = IsType("./testdata/"+"small.file", bytes.NewReader(data), FileTypeAzureARM) } } func BenchmarkIsType_BigFile(b *testing.B) { - data, err := os.ReadFile(fmt.Sprintf("./testdata/%s", "big.file")) + data, err := os.ReadFile("./testdata/" + "big.file") require.NoError(b, err) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { - _ = IsType(fmt.Sprintf("./testdata/%s", "big.file"), bytes.NewReader(data), FileTypeAzureARM) + _ = IsType("./testdata/"+"big.file", bytes.NewReader(data), FileTypeAzureARM) } } diff --git a/pkg/iac/rego/metadata.go b/pkg/iac/rego/metadata.go index b5a42f3c0ab5..3d785a105a46 100644 --- a/pkg/iac/rego/metadata.go +++ b/pkg/iac/rego/metadata.go @@ -47,7 +47,7 @@ func NewStaticMetadata(pkgPath string, inputOpt InputOptions) *StaticMetadata { ID: "N/A", Title: "N/A", Severity: "UNKNOWN", - Description: fmt.Sprintf("Rego module: %s", pkgPath), + Description: "Rego module: " + pkgPath, Package: pkgPath, InputOptions: inputOpt, Frameworks: map[framework.Framework][]string{ diff --git a/pkg/iac/scan/result.go b/pkg/iac/scan/result.go index 9c9e8c5e3274..f00e5691836e 100644 --- a/pkg/iac/scan/result.go +++ b/pkg/iac/scan/result.go @@ -5,6 +5,7 @@ import ( "io/fs" "path/filepath" "reflect" + "strconv" "strings" "github.com/aquasecurity/trivy/pkg/iac/ignore" @@ -311,9 +312,9 @@ func rawToString(raw any) string { } switch t := raw.(type) { case int: - return fmt.Sprintf("%d", t) + return strconv.Itoa(t) case bool: - return fmt.Sprintf("%t", t) + return strconv.FormatBool(t) case float64: return fmt.Sprintf("%f", t) case string: diff --git a/pkg/iac/scanners/azure/functions/utc_now_test.go b/pkg/iac/scanners/azure/functions/utc_now_test.go index 5ee8a3c78021..94263af9f9aa 100644 --- a/pkg/iac/scanners/azure/functions/utc_now_test.go +++ b/pkg/iac/scanners/azure/functions/utc_now_test.go @@ -2,6 +2,7 @@ package functions import ( "fmt" + "strconv" "testing" "time" @@ -20,7 +21,7 @@ func Test_UTCNow(t *testing.T) { args: []any{ "d", }, - expected: fmt.Sprintf("%d", time.Now().UTC().Day()), + expected: strconv.Itoa(time.Now().UTC().Day()), }, { name: "utc now date", diff --git a/pkg/iac/scanners/cloudformation/parser/fn_sub.go b/pkg/iac/scanners/cloudformation/parser/fn_sub.go index 52db66cf9757..ad990bba3b32 100644 --- a/pkg/iac/scanners/cloudformation/parser/fn_sub.go +++ b/pkg/iac/scanners/cloudformation/parser/fn_sub.go @@ -46,7 +46,7 @@ func resolveMapSub(refValue, original *Property) (*Property, bool) { case cftypes.Int: replacement = strconv.Itoa(v.AsInt()) case cftypes.Bool: - replacement = fmt.Sprintf("%v", v.AsBool()) + replacement = strconv.FormatBool(v.AsBool()) case cftypes.List: var parts []string for _, p := range v.AsList() { diff --git a/pkg/iac/scanners/cloudformation/parser/intrinsics.go b/pkg/iac/scanners/cloudformation/parser/intrinsics.go index cda2bde29e41..38473cf49c32 100644 --- a/pkg/iac/scanners/cloudformation/parser/intrinsics.go +++ b/pkg/iac/scanners/cloudformation/parser/intrinsics.go @@ -1,7 +1,6 @@ package parser import ( - "fmt" "strings" "gopkg.in/yaml.v3" @@ -48,7 +47,7 @@ func IsIntrinsicFunc(node *yaml.Node) bool { nodeTag := strings.TrimPrefix(node.Tag, "!") if nodeTag != "Ref" && nodeTag != "Condition" { - nodeTag = fmt.Sprintf("Fn::%s", nodeTag) + nodeTag = "Fn::" + nodeTag } for tag := range intrinsicFuncs { @@ -96,7 +95,7 @@ func getIntrinsicTag(tag string) string { case "Ref", "Contains": return tag default: - return fmt.Sprintf("Fn::%s", tag) + return "Fn::" + tag } } diff --git a/pkg/iac/scanners/cloudformation/parser/property_conversion.go b/pkg/iac/scanners/cloudformation/parser/property_conversion.go index 95f6a48bf380..1053afa1b3f7 100644 --- a/pkg/iac/scanners/cloudformation/parser/property_conversion.go +++ b/pkg/iac/scanners/cloudformation/parser/property_conversion.go @@ -98,7 +98,7 @@ func (p *Property) convertToString() *Property { case cftypes.Int: return p.deriveResolved(cftypes.String, strconv.Itoa(p.AsInt())) case cftypes.Bool: - return p.deriveResolved(cftypes.String, fmt.Sprintf("%v", p.AsBool())) + return p.deriveResolved(cftypes.String, strconv.FormatBool(p.AsBool())) case cftypes.List: var parts []string for _, property := range p.AsList() { diff --git a/pkg/iac/scanners/terraform/executor/executor.go b/pkg/iac/scanners/terraform/executor/executor.go index 2714d50be6fe..339ea7e1aca6 100644 --- a/pkg/iac/scanners/terraform/executor/executor.go +++ b/pkg/iac/scanners/terraform/executor/executor.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "sort" + "strconv" "github.com/zclconf/go-cty/cty" @@ -123,13 +124,13 @@ func ignoreByParams(params map[string]string, modules terraform.Modules, m *type case cty.Number: bf := val.AsBigFloat() f64, _ := bf.Float64() - comparableInt := fmt.Sprintf("%d", int(f64)) + comparableInt := strconv.Itoa(int(f64)) comparableFloat := fmt.Sprintf("%f", f64) if param != comparableInt && param != comparableFloat { return false } case cty.Bool: - if fmt.Sprintf("%t", val.True()) != param { + if strconv.FormatBool(val.True()) != param { return false } default: diff --git a/pkg/iac/scanners/terraform/parser/funcs/collection.go b/pkg/iac/scanners/terraform/parser/funcs/collection.go index aea716d1c9b2..5da1c0399d6c 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/collection.go +++ b/pkg/iac/scanners/terraform/parser/funcs/collection.go @@ -509,7 +509,7 @@ var SumFunc = function.New(&function.Spec{ ty := args[0].Type() if !ty.IsListType() && !ty.IsSetType() && !ty.IsTupleType() { - return cty.NilVal, function.NewArgErrorf(0, fmt.Sprintf("argument must be list, set, or tuple. Received %s", ty.FriendlyName())) + return cty.NilVal, function.NewArgErrorf(0, "argument must be list, set, or tuple. Received "+ty.FriendlyName()) } if !args[0].IsWhollyKnown() { diff --git a/pkg/iac/scanners/terraform/parser/funcs/datetime.go b/pkg/iac/scanners/terraform/parser/funcs/datetime.go index 11ed3c8a2214..b191ab2b1c38 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/datetime.go +++ b/pkg/iac/scanners/terraform/parser/funcs/datetime.go @@ -2,6 +2,7 @@ package funcs import ( + "errors" "fmt" "time" @@ -132,7 +133,7 @@ func parseTimestamp(ts string) (time.Time, error) { case "Z07:00": what = "UTC offset" case "T": - return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: missing required time introducer 'T'") + return time.Time{}, errors.New("not a valid RFC3339 timestamp: missing required time introducer 'T'") case ":", "-": if err.ValueElem == "" { return time.Time{}, fmt.Errorf("not a valid RFC3339 timestamp: end of string where %q is expected", err.LayoutElem) diff --git a/pkg/iac/scanners/terraform/parser/resolvers/registry.go b/pkg/iac/scanners/terraform/parser/resolvers/registry.go index 3b37134b307a..abd656e8a187 100644 --- a/pkg/iac/scanners/terraform/parser/resolvers/registry.go +++ b/pkg/iac/scanners/terraform/parser/resolvers/registry.go @@ -174,7 +174,7 @@ func getPrivateRegistryTokenFromEnvVars(hostname string) (string, error) { return "", fmt.Errorf("could not convert hostname %s to a punycode encoded ASCII string so cannot find token for this registry", hostname) } - envVar := fmt.Sprintf("TF_TOKEN_%s", strings.ReplaceAll(asciiHostname, ".", "_")) + envVar := "TF_TOKEN_" + strings.ReplaceAll(asciiHostname, ".", "_") token = os.Getenv(envVar) // Dashes in the hostname can optionally be converted to double underscores diff --git a/pkg/iac/terraform/module.go b/pkg/iac/terraform/module.go index fec6ad7c8d0e..76ecc1810c21 100644 --- a/pkg/iac/terraform/module.go +++ b/pkg/iac/terraform/module.go @@ -104,7 +104,7 @@ func (c *Module) GetProviderBlocksByProvider(providerName, alias string) Blocks for _, block := range c.blocks { if block.Type() == "provider" && len(block.Labels()) > 0 && block.TypeLabel() == providerName { if alias != "" { - if block.HasChild("alias") && block.GetAttribute("alias").Equals(strings.ReplaceAll(alias, fmt.Sprintf("%s.", providerName), "")) { + if block.HasChild("alias") && block.GetAttribute("alias").Equals(strings.ReplaceAll(alias, providerName+".", "")) { results = append(results, block) } diff --git a/pkg/iac/terraform/presets.go b/pkg/iac/terraform/presets.go index 61ac78bccd2e..09ec239a04cd 100644 --- a/pkg/iac/terraform/presets.go +++ b/pkg/iac/terraform/presets.go @@ -1,7 +1,6 @@ package terraform import ( - "fmt" "math/rand/v2" "strings" @@ -67,7 +66,7 @@ func postProcessValues(b *Block, input map[string]cty.Value) map[string]cty.Valu if bucket := input["bucket"]; bucket.Type().Equals(cty.String) { bucketName = bucket.AsString() } - input["arn"] = cty.StringVal(fmt.Sprintf("arn:aws:s3:::%s", bucketName)) + input["arn"] = cty.StringVal("arn:aws:s3:::" + bucketName) } return input diff --git a/pkg/iac/terraform/resource_block.go b/pkg/iac/terraform/resource_block.go index abce0fcb040e..9d08c0b10db7 100644 --- a/pkg/iac/terraform/resource_block.go +++ b/pkg/iac/terraform/resource_block.go @@ -75,14 +75,14 @@ var resourceTemplate = `{{ .BlockType }} "{{ .Type }}" "{{ .Name }}" { func renderTemplateValue(val any) string { switch t := val.(type) { case map[string]any: - return fmt.Sprintf("= %s", renderMap(t)) + return "= " + renderMap(t) case []any: if isMapSlice(t) { return renderSlice(t) } - return fmt.Sprintf("= %s", renderSlice(t)) + return "= " + renderSlice(t) default: - return fmt.Sprintf("= %s", renderPrimitive(val)) + return "= " + renderPrimitive(val) } } @@ -145,7 +145,7 @@ func renderSlice(vals []any) string { for _, v := range vals { result = fmt.Sprintf("%s\t%v,\n", result, renderPrimitive(v)) } - result = fmt.Sprintf("%s]", result) + result = result + "]" return result } } @@ -162,7 +162,7 @@ func renderMap(val map[string]any) string { } result = fmt.Sprintf("%s\t%s = %s\n", result, k, renderPrimitive(v)) } - result = fmt.Sprintf("%s}", result) + result = result + "}" return result } diff --git a/pkg/k8s/commands/run.go b/pkg/k8s/commands/run.go index 1650cfa1446f..e8bb5cca1cf8 100644 --- a/pkg/k8s/commands/run.go +++ b/pkg/k8s/commands/run.go @@ -3,7 +3,6 @@ package commands import ( "context" "errors" - "fmt" "github.com/spf13/viper" "golang.org/x/xerrors" @@ -42,7 +41,7 @@ func Run(ctx context.Context, args []string, opts flag.Options) error { cancel() if errors.Is(err, context.DeadlineExceeded) { // e.g. https://aquasecurity.github.io/trivy/latest/docs/configuration - log.WarnContext(ctx, fmt.Sprintf("Provide a higher timeout value, see %s", doc.URL("/docs/configuration/", ""))) + log.WarnContext(ctx, "Provide a higher timeout value, see "+doc.URL("/docs/configuration/", "")) } }() opts.K8sVersion = cluster.GetClusterVersion() diff --git a/pkg/k8s/report/table.go b/pkg/k8s/report/table.go index 13dbe026912a..c9d4d731e41f 100644 --- a/pkg/k8s/report/table.go +++ b/pkg/k8s/report/table.go @@ -78,7 +78,7 @@ func (tw TableWriter) Write(ctx context.Context, report Report) error { func updateTargetContext(r *Resource) { targetName := fmt.Sprintf("namespace: %s, %s: %s", r.Namespace, strings.ToLower(r.Kind), r.Name) if r.Kind == "NodeComponents" || r.Kind == "NodeInfo" { - targetName = fmt.Sprintf("node: %s", r.Name) + targetName = "node: " + r.Name } for i := range r.Report.Results { r.Report.Results[i].Target = targetName diff --git a/pkg/k8s/writer.go b/pkg/k8s/writer.go index abc5bb381b64..e02a1f4eff33 100644 --- a/pkg/k8s/writer.go +++ b/pkg/k8s/writer.go @@ -2,7 +2,6 @@ package k8s import ( "context" - "fmt" cdx "github.com/CycloneDX/cyclonedx-go" @@ -26,7 +25,7 @@ func Write(ctx context.Context, k8sreport report.Report, option report.Option) e separatedReports := report.SeparateMisconfigReports(k8sreport, option.Scanners) if option.Report == report.SummaryReport { - target := fmt.Sprintf("Summary Report for %s", k8sreport.ClusterName) + target := "Summary Report for " + k8sreport.ClusterName table.RenderTarget(option.Output, target, table.IsOutputToTerminal(option.Output)) } diff --git a/pkg/misconf/scanner.go b/pkg/misconf/scanner.go index a32ef5c105e0..34e780854758 100644 --- a/pkg/misconf/scanner.go +++ b/pkg/misconf/scanner.go @@ -457,7 +457,7 @@ func ResultsToMisconf(configType types.ConfigType, scannerName string, results s PolicyMetadata: types.PolicyMetadata{ ID: ruleID, AVDID: result.Rule().AVDID, - Type: fmt.Sprintf("%s Security Check", scannerName), + Type: scannerName + " Security Check", Title: result.Rule().Summary, Description: result.Rule().Explanation, Severity: string(flattened.Severity), diff --git a/pkg/rekor/client.go b/pkg/rekor/client.go index c6390f9679db..4fcebd6c7d82 100644 --- a/pkg/rekor/client.go +++ b/pkg/rekor/client.go @@ -2,7 +2,6 @@ package rekor import ( "context" - "fmt" "slices" pkgclient "github.com/sigstore/rekor/pkg/client" @@ -64,7 +63,7 @@ type Client struct { } func NewClient(rekorURL string) (*Client, error) { - c, err := pkgclient.GetRekorClient(rekorURL, pkgclient.WithUserAgent(fmt.Sprintf("trivy/%s", app.Version()))) + c, err := pkgclient.GetRekorClient(rekorURL, pkgclient.WithUserAgent("trivy/"+app.Version())) if err != nil { return nil, xerrors.Errorf("failed to create rekor client: %w", err) } diff --git a/pkg/remote/remote.go b/pkg/remote/remote.go index a8bca7aafe1f..b851dfffe725 100644 --- a/pkg/remote/remote.go +++ b/pkg/remote/remote.go @@ -3,7 +3,6 @@ package remote import ( "context" "crypto/tls" - "fmt" "net" "net/http" "time" @@ -142,7 +141,7 @@ func httpTransport(option types.RegistryOptions) (http.RoundTripper, error) { tr.TLSClientConfig.Certificates = []tls.Certificate{cert} } - tripper := transport.NewUserAgent(tr, fmt.Sprintf("trivy/%s", app.Version())) + tripper := transport.NewUserAgent(tr, "trivy/"+app.Version()) return tripper, nil } diff --git a/pkg/remote/remote_test.go b/pkg/remote/remote_test.go index 27ea8079153b..519f035da0ba 100644 --- a/pkg/remote/remote_test.go +++ b/pkg/remote/remote_test.go @@ -81,7 +81,7 @@ func TestGet(t *testing.T) { { name: "single credential", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.RegistryOptions{ Credentials: []types.Credential{ { @@ -96,7 +96,7 @@ func TestGet(t *testing.T) { { name: "multiple credential", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.RegistryOptions{ Credentials: []types.Credential{ { @@ -115,7 +115,7 @@ func TestGet(t *testing.T) { { name: "keychain", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", config: fmt.Sprintf(`{"auths": {%q: {"auth": %q}}}`, serverAddr, encode("test", "testpass")), option: types.RegistryOptions{ Insecure: true, @@ -125,7 +125,7 @@ func TestGet(t *testing.T) { { name: "platform", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.RegistryOptions{ Credentials: []types.Credential{ { @@ -146,7 +146,7 @@ func TestGet(t *testing.T) { { name: "force platform", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.RegistryOptions{ Credentials: []types.Credential{ { @@ -169,7 +169,7 @@ func TestGet(t *testing.T) { { name: "bad credential", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", option: types.RegistryOptions{ Credentials: []types.Credential{ { @@ -185,7 +185,7 @@ func TestGet(t *testing.T) { { name: "bad keychain", args: args{ - imageName: fmt.Sprintf("%s/library/alpine:3.10", serverAddr), + imageName: serverAddr + "/library/alpine:3.10", config: fmt.Sprintf(`{"auths": {%q: {"auth": %q}}}`, serverAddr, encode("foo", "bar")), option: types.RegistryOptions{ Insecure: true, @@ -257,7 +257,7 @@ func TestUserAgents(t *testing.T) { serverAddr := tr.Listener.Addr().String() - n, err := name.ParseReference(fmt.Sprintf("%s/library/alpine:3.10", serverAddr)) + n, err := name.ParseReference(serverAddr + "/library/alpine:3.10") require.NoError(t, err) _, err = Get(context.Background(), n, types.RegistryOptions{ diff --git a/pkg/report/table/misconfig.go b/pkg/report/table/misconfig.go index 41f111d883c9..604b7db0be67 100644 --- a/pkg/report/table/misconfig.go +++ b/pkg/report/table/misconfig.go @@ -3,6 +3,7 @@ package table import ( "bytes" "fmt" + "strconv" "strings" "github.com/fatih/color" @@ -168,7 +169,7 @@ func (r *misconfigRenderer) renderCode(misconf types.DetectedMisconfiguration) { for i, occ := range misconf.CauseMetadata.Occurrences { lineInfo := fmt.Sprintf("%d-%d", occ.Location.StartLine, occ.Location.EndLine) if occ.Location.StartLine >= occ.Location.EndLine { - lineInfo = fmt.Sprintf("%d", occ.Location.StartLine) + lineInfo = strconv.Itoa(occ.Location.StartLine) } r.printf( @@ -184,7 +185,7 @@ func (r *misconfigRenderer) renderCode(misconf types.DetectedMisconfiguration) { for i, line := range lines { switch { case line.Truncated: - r.printf("%4s ", strings.Repeat(".", len(fmt.Sprintf("%d", line.Number)))) + r.printf("%4s ", strings.Repeat(".", len(strconv.Itoa(line.Number)))) case line.IsCause: r.printf("%4d ", line.Number) switch { diff --git a/pkg/report/table/secret.go b/pkg/report/table/secret.go index cff91a98d9ed..1b1cf78dda21 100644 --- a/pkg/report/table/secret.go +++ b/pkg/report/table/secret.go @@ -3,6 +3,7 @@ package table import ( "bytes" "fmt" + "strconv" "strings" "golang.org/x/term" @@ -141,7 +142,7 @@ func (r *secretRenderer) renderCode(secret types.DetectedSecret) { for i, line := range lines { switch { case line.Truncated: - r.printf("%4s ", strings.Repeat(".", len(fmt.Sprintf("%d", line.Number)))) + r.printf("%4s ", strings.Repeat(".", len(strconv.Itoa(line.Number)))) case line.IsCause: r.printf("%4d ", line.Number) switch { diff --git a/pkg/report/table/vulnerability.go b/pkg/report/table/vulnerability.go index 1c08236a033c..53954b4ad2eb 100644 --- a/pkg/report/table/vulnerability.go +++ b/pkg/report/table/vulnerability.go @@ -249,10 +249,7 @@ func (r *vulnerabilityRenderer) renderDependencyTree() { } ancestors := traverseAncestors(r.result.Packages, parents) - root := treeprint.NewWithRoot(fmt.Sprintf(` -Dependency Origin Tree (Reversed) -================================= -%s`, r.result.Target)) + root := treeprint.NewWithRoot("\nDependency Origin Tree (Reversed)\n=================================\n" + r.result.Target) // This count is next to the package ID. // e.g. node-fetch@1.7.3 (MEDIUM: 2, HIGH: 1, CRITICAL: 3) diff --git a/pkg/sbom/spdx/marshal.go b/pkg/sbom/spdx/marshal.go index 51f9144f682d..89ed563d7dd5 100644 --- a/pkg/sbom/spdx/marshal.go +++ b/pkg/sbom/spdx/marshal.go @@ -5,6 +5,7 @@ import ( "fmt" "slices" "sort" + "strconv" "strings" "time" @@ -237,7 +238,7 @@ func (m *Marshaler) packageDownloadLocation(root *core.Component) string { // Trivy currently only supports git repositories. Format examples: // git+https://git.myproject.org/MyProject.git // git+http://git.myproject.org/MyProject - location = fmt.Sprintf("git+%s", root.Name) + location = "git+" + root.Name } return location } @@ -440,7 +441,7 @@ func (m *Marshaler) spdxFile(filePath string, digests []digest.Digest) (*spdx.Fi return nil, xerrors.Errorf("failed to get %s package ID: %w", filePath, err) } return &spdx.File{ - FileSPDXIdentifier: spdx.ElementID(fmt.Sprintf("File-%s", pkgID)), + FileSPDXIdentifier: spdx.ElementID("File-" + pkgID), FileName: filePath, Checksums: m.spdxChecksums(digests), }, nil @@ -527,7 +528,7 @@ func calcPkgID(h Hash, v any) (string, error) { return "", xerrors.Errorf("could not build package ID for %+v: %w", v, err) } - return fmt.Sprintf("%x", f), nil + return strconv.FormatUint(f, 16), nil } func camelCase(inputUnderScoreStr string) (camelCase string) { diff --git a/pkg/sbom/spdx/unmarshal.go b/pkg/sbom/spdx/unmarshal.go index c7ed6b0905dd..3ddd1b3a5f47 100644 --- a/pkg/sbom/spdx/unmarshal.go +++ b/pkg/sbom/spdx/unmarshal.go @@ -2,7 +2,6 @@ package spdx import ( "bytes" - "fmt" "io" "strings" @@ -178,7 +177,7 @@ func (s *SPDX) parsePackage(spdxPkg spdx.Package) (*core.Component, error) { // Source package if strings.HasPrefix(spdxPkg.PackageSourceInfo, SourcePackagePrefix) { - srcPkgName := strings.TrimPrefix(spdxPkg.PackageSourceInfo, fmt.Sprintf("%s: ", SourcePackagePrefix)) + srcPkgName := strings.TrimPrefix(spdxPkg.PackageSourceInfo, SourcePackagePrefix+": ") component.SrcName, component.SrcVersion, _ = strings.Cut(srcPkgName, " ") } diff --git a/pkg/scanner/local/scan.go b/pkg/scanner/local/scan.go index 1d117999ede1..e4513a9aa6d5 100644 --- a/pkg/scanner/local/scan.go +++ b/pkg/scanner/local/scan.go @@ -3,7 +3,6 @@ package local import ( "context" "errors" - "fmt" "slices" "sort" "strings" @@ -345,7 +344,7 @@ func toDetectedMisconfiguration(res ftypes.MisconfResult, defaultSeverity dbType // empty namespace implies a go rule from defsec, "builtin" refers to a built-in rego rule // this ensures we don't generate bad links for custom policies if res.Namespace == "" || rego.IsBuiltinNamespace(res.Namespace) { - primaryURL = fmt.Sprintf("https://avd.aquasec.com/misconfig/%s", strings.ToLower(res.ID)) + primaryURL = "https://avd.aquasec.com/misconfig/" + strings.ToLower(res.ID) res.References = append(res.References, primaryURL) } diff --git a/pkg/vex/oci_test.go b/pkg/vex/oci_test.go index e803d6ab20aa..333ab84d0fca 100644 --- a/pkg/vex/oci_test.go +++ b/pkg/vex/oci_test.go @@ -35,7 +35,7 @@ func setUpRegistry(t *testing.T) (*httptest.Server, v1.Hash) { images := map[string]v1.Image{ "v2/debian:latest": imgWithVEX, "v2/debian:no-vex": setUpImage(t), - fmt.Sprintf("v2/debian@%s", d.String()): imgWithVEX, + "v2/debian@" + d.String(): imgWithVEX, fmt.Sprintf("v2/debian:sha256-%s.att", d.Hex): setUpVEXAttestation(t), // VEX attestation }