Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: enable all rules from perfsprint #8194

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ linters-settings:
- simmilar
perfsprint:
# Optimizes even if it requires an int or uint type cast.
int-conversion: false
int-conversion: true
# Optimizes into `err.Error()` even if it is only equivalent for non-nil errors.
err-error: true
# Optimizes `fmt.Errorf`.
errorf: true
# Optimizes `fmt.Sprintf` with only one argument.
sprintf1: false
sprintf1: true
# Optimizes into strings concatenation.
strconcat: false
strconcat: true
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally prefer not to use this optimization.

Suggested change
strconcat: true
strconcat: false

@DmitriyLewen @simar7 @nikpivkin However, if you prefer string concatenation, I'm okay with that.

revive:
ignore-generated-header: true
testifylint:
Expand Down Expand Up @@ -152,8 +152,5 @@ issues:
linters:
- gocritic
text: "importShadow:"
- linters:
- perfsprint
text: "fmt.Sprint"
exclude-use-default: false
max-same-issues: 0
2 changes: 1 addition & 1 deletion magefiles/magefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 8 additions & 8 deletions pkg/cache/redis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like it's too much. fmt.Sprintf is easier to read than string concatenation.

require.NoError(t, err)

err = c.PutArtifact(tt.args.artifactID, tt.args.artifactConfig)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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())
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/commands/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 2 additions & 5 deletions pkg/commands/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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", ""),
)
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/dependency/id.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package dependency

import (
"fmt"
"strconv"
"strings"

"github.com/mitchellh/hashstructure/v2"
Expand Down Expand Up @@ -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)
}
3 changes: 1 addition & 2 deletions pkg/dependency/parser/golang/binary/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package binary
import (
"cmp"
"debug/buildinfo"
"fmt"
"runtime/debug"
"slices"
"sort"
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions pkg/dependency/parser/golang/mod/parse.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mod

import (
"fmt"
"io"
"regexp"
"sort"
Expand Down Expand Up @@ -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.
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/dependency/parser/java/pom/artifact.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
2 changes: 1 addition & 1 deletion pkg/dependency/parser/java/pom/pom.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 4 additions & 5 deletions pkg/dependency/parser/ruby/gemspec/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gemspec

import (
"bufio"
"fmt"
"regexp"
"strings"

Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/fanal/analyzer/imgconf/dockerfile/dockerfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
3 changes: 1 addition & 2 deletions pkg/fanal/analyzer/language/rust/cargo/cargo.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cargo
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"maps"
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions pkg/fanal/analyzer/secret/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package secret
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -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{
Expand Down
4 changes: 2 additions & 2 deletions pkg/fanal/applier/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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)
}

Expand Down
3 changes: 1 addition & 2 deletions pkg/fanal/image/daemon/image_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package daemon

import (
"fmt"
"os"
"path/filepath"
"runtime"
Expand Down Expand Up @@ -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())
}
Expand Down
Loading
Loading