diff --git a/.golangci.yaml b/.golangci.yaml index 40bfa36e1a64..f3fcd347a223 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -80,6 +80,17 @@ linters-settings: - licence - optimise - simmilar + perfsprint: + # Optimizes even if it requires an int or uint type cast. + int-conversion: false + # 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 + # Optimizes into strings concatenation. + strconcat: false revive: ignore-generated-header: true testifylint: @@ -99,6 +110,7 @@ linters: - govet - ineffassign - misspell + - perfsprint - revive - tenv - testifylint @@ -139,5 +151,8 @@ issues: linters: - gocritic text: "importShadow:" + - linters: + - perfsprint + text: "fmt.Sprint" exclude-use-default: false max-same-issues: 0 diff --git a/examples/module/spring4shell/spring4shell.go b/examples/module/spring4shell/spring4shell.go index 6c527cc946b2..18bda7094b11 100644 --- a/examples/module/spring4shell/spring4shell.go +++ b/examples/module/spring4shell/spring4shell.go @@ -5,6 +5,7 @@ package main import ( "bufio" + "errors" "fmt" "io" "os" @@ -112,7 +113,7 @@ func (Spring4Shell) parseTomcatReleaseNotes(f *os.File, filePath string) (*seria m := tomcatVersionRegex.FindStringSubmatch(string(b)) if len(m) != 2 { - return nil, fmt.Errorf("unknown tomcat release notes format") + return nil, errors.New("unknown tomcat release notes format") } return &serialize.AnalysisResult{ diff --git a/magefiles/schema.go b/magefiles/schema.go index 77d98d75d535..6cbf8b950ad0 100644 --- a/magefiles/schema.go +++ b/magefiles/schema.go @@ -5,7 +5,7 @@ package main import ( "bytes" "encoding/json" - "fmt" + "errors" "log" "os" @@ -66,7 +66,7 @@ func VerifySchema() error { return err } if !bytes.Equal(data, existing) { - return fmt.Errorf("schema is out of date:\n\nplease run 'mage schema:generate' and commit the changes\n") + return errors.New("schema is out of date:\n\nplease run 'mage schema:generate' and commit the changes\n") } return nil } diff --git a/pkg/flag/kubernetes_flags.go b/pkg/flag/kubernetes_flags.go index 6d0d64f4dc56..b8ec034d7169 100644 --- a/pkg/flag/kubernetes_flags.go +++ b/pkg/flag/kubernetes_flags.go @@ -1,6 +1,7 @@ package flag import ( + "errors" "fmt" "strconv" "strings" @@ -192,10 +193,10 @@ func (f *K8sFlagGroup) ToOptions() (K8sOptions, error) { exludeNodeLabels[excludeNodeParts[0]] = excludeNodeParts[1] } if len(f.ExcludeNamespaces.Value()) > 0 && len(f.IncludeNamespaces.Value()) > 0 { - return K8sOptions{}, fmt.Errorf("include-namespaces and exclude-namespaces flags cannot be used together") + return K8sOptions{}, errors.New("include-namespaces and exclude-namespaces flags cannot be used together") } if len(f.ExcludeKinds.Value()) > 0 && len(f.IncludeKinds.Value()) > 0 { - return K8sOptions{}, fmt.Errorf("include-kinds and exclude-kinds flags cannot be used together") + return K8sOptions{}, errors.New("include-kinds and exclude-kinds flags cannot be used together") } return K8sOptions{ @@ -222,12 +223,12 @@ func optionToTolerations(tolerationsOptions []string) ([]corev1.Toleration, erro for _, toleration := range tolerationsOptions { tolerationParts := strings.Split(toleration, ":") if len(tolerationParts) < 2 { - return []corev1.Toleration{}, fmt.Errorf("toleration must include key and effect") + return []corev1.Toleration{}, errors.New("toleration must include key and effect") } if corev1.TaintEffect(tolerationParts[1]) != corev1.TaintEffectNoSchedule && corev1.TaintEffect(tolerationParts[1]) != corev1.TaintEffectPreferNoSchedule && corev1.TaintEffect(tolerationParts[1]) != corev1.TaintEffectNoExecute { - return []corev1.Toleration{}, fmt.Errorf("toleration effect must be a valid value") + return []corev1.Toleration{}, errors.New("toleration effect must be a valid value") } keyValue := strings.Split(tolerationParts[0], "=") operator := corev1.TolerationOpEqual @@ -245,7 +246,7 @@ func optionToTolerations(tolerationsOptions []string) ([]corev1.Toleration, erro if len(tolerationParts) == 3 { tolerationSec, err = strconv.Atoi(tolerationParts[2]) if err != nil { - return nil, fmt.Errorf("TolerationSeconds must must be a number") + return nil, errors.New("TolerationSeconds must must be a number") } toleration.TolerationSeconds = lo.ToPtr(int64(tolerationSec)) } diff --git a/pkg/iac/adapters/cloudformation/aws/ecr/repository.go b/pkg/iac/adapters/cloudformation/aws/ecr/repository.go index 2c08d57a29c6..0bb8e6c626d6 100644 --- a/pkg/iac/adapters/cloudformation/aws/ecr/repository.go +++ b/pkg/iac/adapters/cloudformation/aws/ecr/repository.go @@ -1,7 +1,7 @@ package ecr import ( - "fmt" + "errors" "github.com/liamg/iamgo" @@ -60,7 +60,7 @@ func getRepositories(ctx parser.FileContext) (repositories []ecr.Repository) { func getPolicy(r *parser.Resource) (*iam.Policy, error) { policyProp := r.GetProperty("RepositoryPolicyText") if policyProp.IsNil() { - return nil, fmt.Errorf("missing policy") + return nil, errors.New("missing policy") } parsed, err := iamgo.Parse(policyProp.GetJsonBytes()) diff --git a/pkg/iac/adapters/cloudformation/aws/sqs/queue.go b/pkg/iac/adapters/cloudformation/aws/sqs/queue.go index 555fd54efd90..a2e647083f22 100644 --- a/pkg/iac/adapters/cloudformation/aws/sqs/queue.go +++ b/pkg/iac/adapters/cloudformation/aws/sqs/queue.go @@ -1,7 +1,7 @@ package sqs import ( - "fmt" + "errors" "github.com/liamg/iamgo" @@ -59,5 +59,5 @@ func getPolicy(id string, ctx parser.FileContext) (*iam.Policy, error) { } } } - return nil, fmt.Errorf("no matching policy found") + return nil, errors.New("no matching policy found") } diff --git a/pkg/iac/rego/metadata.go b/pkg/iac/rego/metadata.go index cb1d38724e8a..9229f44617ae 100644 --- a/pkg/iac/rego/metadata.go +++ b/pkg/iac/rego/metadata.go @@ -2,6 +2,7 @@ package rego import ( "context" + "errors" "fmt" "strings" @@ -330,15 +331,15 @@ func (m *MetadataRetriever) RetrieveMetadata(ctx context.Context, module *ast.Mo } if len(set) != 1 { - return nil, fmt.Errorf("failed to parse metadata: unexpected set length") + return nil, errors.New("failed to parse metadata: unexpected set length") } if len(set[0].Expressions) != 1 { - return nil, fmt.Errorf("failed to parse metadata: unexpected expression length") + return nil, errors.New("failed to parse metadata: unexpected expression length") } expression := set[0].Expressions[0] meta, ok := expression.Value.(map[string]any) if !ok { - return nil, fmt.Errorf("failed to parse metadata: not an object") + return nil, errors.New("failed to parse metadata: not an object") } if err := metadata.update(meta); err != nil { diff --git a/pkg/iac/rego/schemas/builder.go b/pkg/iac/rego/schemas/builder.go index 649bf0a1aacf..38f3c0c13594 100644 --- a/pkg/iac/rego/schemas/builder.go +++ b/pkg/iac/rego/schemas/builder.go @@ -1,6 +1,7 @@ package schemas import ( + "errors" "fmt" "reflect" "strings" @@ -56,7 +57,7 @@ func (b *builder) fromInput(inputValue reflect.Value) error { return err } if prop == nil { - return fmt.Errorf("property is nil") + return errors.New("property is nil") } b.schema.Properties = prop.Properties b.schema.Type = prop.Type diff --git a/pkg/iac/scan/code.go b/pkg/iac/scan/code.go index 8388dd4dbf6e..11bd27813dfc 100644 --- a/pkg/iac/scan/code.go +++ b/pkg/iac/scan/code.go @@ -2,6 +2,7 @@ package scan import ( "bufio" + "errors" "fmt" "io/fs" "path/filepath" @@ -141,7 +142,7 @@ func (r *Result) GetCode(opts ...CodeOption) (*Code, error) { fsys := r.Metadata().Range().GetFS() if fsys == nil { - return nil, fmt.Errorf("code unavailable: result was not mapped to a known filesystem") + return nil, errors.New("code unavailable: result was not mapped to a known filesystem") } innerRange := r.metadata.Range() diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/decode.go b/pkg/iac/scanners/azure/arm/parser/armjson/decode.go index c0c476db7681..dcce24f3a5d9 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/decode.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/decode.go @@ -1,6 +1,7 @@ package armjson import ( + "errors" "fmt" "reflect" @@ -40,7 +41,7 @@ func (n *node) decodeToValue(v reflect.Value) error { } if !v.CanSet() { - return fmt.Errorf("target is not settable") + return errors.New("target is not settable") } switch n.kind { @@ -59,7 +60,7 @@ func (n *node) decodeToValue(v reflect.Value) error { case KindComment: return n.decodeString(v) case KindUnknown: - return fmt.Errorf("cannot decode unknown kind") + return errors.New("cannot decode unknown kind") default: return fmt.Errorf("decoding of kind 0x%x is not supported", n.kind) } diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/decode_array.go b/pkg/iac/scanners/azure/arm/parser/armjson/decode_array.go index 483880814383..457b78b5f0d7 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/decode_array.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/decode_array.go @@ -1,7 +1,7 @@ package armjson import ( - "fmt" + "errors" "reflect" ) @@ -14,7 +14,7 @@ func (n *node) decodeArray(v reflect.Value) error { switch v.Kind() { case reflect.Array: if v.Len() != length { - return fmt.Errorf("invalid length") + return errors.New("invalid length") } case reflect.Slice: v.Set(reflect.MakeSlice(v.Type(), length, length)) @@ -24,7 +24,7 @@ func (n *node) decodeArray(v reflect.Value) error { v = reflect.New(slice.Type()).Elem() v.Set(slice) default: - return fmt.Errorf("invalid target type") + return errors.New("invalid target type") } elementType := v.Type().Elem() diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/decode_number.go b/pkg/iac/scanners/azure/arm/parser/armjson/decode_number.go index 653f6f1fbe06..4b477e89ca70 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/decode_number.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/decode_number.go @@ -1,6 +1,7 @@ package armjson import ( + "errors" "fmt" "reflect" ) @@ -42,5 +43,5 @@ func (n *node) decodeNumber(v reflect.Value) error { return fmt.Errorf("cannot decode number value to %s target", v.Kind()) } - return fmt.Errorf("internal value is not numeric") + return errors.New("internal value is not numeric") } diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/decode_object.go b/pkg/iac/scanners/azure/arm/parser/armjson/decode_object.go index fdc58f6c8e34..5d7e15357007 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/decode_object.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/decode_object.go @@ -1,6 +1,7 @@ package armjson import ( + "errors" "fmt" "reflect" "strings" @@ -54,19 +55,19 @@ func (n *node) decodeObjectToMap(v reflect.Value) error { func (n *node) objectAsMap() (map[string]Node, error) { if n.kind != KindObject { - return nil, fmt.Errorf("not an object") + return nil, errors.New("not an object") } properties := make(map[string]Node) contents := n.content for i := 0; i < len(contents); i += 2 { key := contents[i] if key.Kind() != KindString { - return nil, fmt.Errorf("invalid object key - please report this bug") + return nil, errors.New("invalid object key - please report this bug") } keyStr := key.(*node).raw.(string) if i+1 >= len(contents) { - return nil, fmt.Errorf("missing object value - please report this bug") + return nil, errors.New("missing object value - please report this bug") } properties[keyStr] = contents[i+1] } diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/parse_boolean.go b/pkg/iac/scanners/azure/arm/parser/armjson/parse_boolean.go index 30903ea85973..59a5fffb114b 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/parse_boolean.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/parse_boolean.go @@ -1,7 +1,7 @@ package armjson import ( - "fmt" + "errors" "github.com/aquasecurity/trivy/pkg/iac/types" ) @@ -21,7 +21,7 @@ func (p *parser) parseBoolean(parentMetadata *types.Metadata) (Node, error) { if r == 't' { for _, expected := range trueRunes { if !p.swallowIfEqual(expected) { - return nil, fmt.Errorf("unexpected character in boolean value") + return nil, errors.New("unexpected character in boolean value") } } n.raw = true @@ -31,7 +31,7 @@ func (p *parser) parseBoolean(parentMetadata *types.Metadata) (Node, error) { for _, expected := range falseRunes { if !p.swallowIfEqual(expected) { - return nil, fmt.Errorf("unexpected character in boolean value") + return nil, errors.New("unexpected character in boolean value") } } n.raw = false diff --git a/pkg/iac/scanners/azure/arm/parser/armjson/parse_null.go b/pkg/iac/scanners/azure/arm/parser/armjson/parse_null.go index 1a0011ec5dac..0ae20a8c9edf 100644 --- a/pkg/iac/scanners/azure/arm/parser/armjson/parse_null.go +++ b/pkg/iac/scanners/azure/arm/parser/armjson/parse_null.go @@ -1,7 +1,7 @@ package armjson import ( - "fmt" + "errors" "github.com/aquasecurity/trivy/pkg/iac/types" ) @@ -14,7 +14,7 @@ func (p *parser) parseNull(parentMetadata *types.Metadata) (Node, error) { for _, expected := range nullRunes { if !p.swallowIfEqual(expected) { - return nil, fmt.Errorf("unexpected character") + return nil, errors.New("unexpected character") } } n.raw = nil diff --git a/pkg/iac/scanners/azure/expressions/lex.go b/pkg/iac/scanners/azure/expressions/lex.go index f5cfb2a34705..6bbb4717e745 100644 --- a/pkg/iac/scanners/azure/expressions/lex.go +++ b/pkg/iac/scanners/azure/expressions/lex.go @@ -2,6 +2,7 @@ package expressions import ( "bufio" + "errors" "fmt" "strconv" "strings" @@ -119,7 +120,7 @@ func (l *lexer) lexString(terminator rune) (Token, error) { func (l *lexer) readEscapedChar() (rune, error) { r, err := l.read() if err != nil { - return 0, fmt.Errorf("unexpected EOF") + return 0, errors.New("unexpected EOF") } switch r { case 'n': diff --git a/pkg/iac/scanners/azure/functions/date_time_add.go b/pkg/iac/scanners/azure/functions/date_time_add.go index bbd03b47bdfa..2e3c06ae8220 100644 --- a/pkg/iac/scanners/azure/functions/date_time_add.go +++ b/pkg/iac/scanners/azure/functions/date_time_add.go @@ -1,6 +1,7 @@ package functions import ( + "errors" "fmt" "regexp" "strconv" @@ -65,7 +66,7 @@ func parseISO8601(from string) (Iso8601Duration, error) { if pattern.MatchString(from) { match = pattern.FindStringSubmatch(from) } else { - return d, fmt.Errorf("could not parse duration string") + return d, errors.New("could not parse duration string") } for i, name := range pattern.SubexpNames() { diff --git a/pkg/iac/scanners/azure/functions/unique_string.go b/pkg/iac/scanners/azure/functions/unique_string.go index 1411d2b1fdc0..72b5fb5aabc6 100644 --- a/pkg/iac/scanners/azure/functions/unique_string.go +++ b/pkg/iac/scanners/azure/functions/unique_string.go @@ -2,7 +2,7 @@ package functions import ( "crypto/sha256" - "fmt" + "encoding/hex" "strings" ) @@ -17,5 +17,5 @@ func UniqueString(args ...any) any { } hash := sha256.New().Sum([]byte(strings.Join(hashParts, ""))) - return fmt.Sprintf("%x", hash)[:13] + return hex.EncodeToString(hash)[:13] } diff --git a/pkg/iac/scanners/cloudformation/parser/fn_builtin.go b/pkg/iac/scanners/cloudformation/parser/fn_builtin.go index 3fb21dca82de..6859fa0f4ff2 100644 --- a/pkg/iac/scanners/cloudformation/parser/fn_builtin.go +++ b/pkg/iac/scanners/cloudformation/parser/fn_builtin.go @@ -1,7 +1,7 @@ package parser import ( - "fmt" + "errors" "net" "github.com/apparentlymart/go-cidr/cidr" @@ -55,7 +55,7 @@ func calculateCidrs(ipaddress string, count, bit int, original *Property) ([]*Pr for i := 0; i < count; i++ { next, err := cidr.Subnet(network, bit, i) if err != nil { - return nil, fmt.Errorf("failed to create cidr blocks") + return nil, errors.New("failed to create cidr blocks") } cidrProperties = append(cidrProperties, original.deriveResolved(cftypes.String, next.String())) diff --git a/pkg/iac/scanners/cloudformation/parser/parameter.go b/pkg/iac/scanners/cloudformation/parser/parameter.go index 20e2011417d5..5581ea5ab815 100644 --- a/pkg/iac/scanners/cloudformation/parser/parameter.go +++ b/pkg/iac/scanners/cloudformation/parser/parameter.go @@ -3,6 +3,7 @@ package parser import ( "bytes" "encoding/json" + "errors" "fmt" "strconv" "strings" @@ -137,7 +138,7 @@ func (p *Parameters) UnmarshalJSON(data []byte) error { (*p)[param.ParameterKey] = param.ParameterValue } default: - return fmt.Errorf("unsupported parameters format") + return errors.New("unsupported parameters format") } return nil diff --git a/pkg/iac/scanners/helm/parser/parser.go b/pkg/iac/scanners/helm/parser/parser.go index 1a132fdc2f76..e2ddfe3868a6 100644 --- a/pkg/iac/scanners/helm/parser/parser.go +++ b/pkg/iac/scanners/helm/parser/parser.go @@ -222,7 +222,7 @@ func (p *Parser) getRelease(chrt *chart.Chart) (*release.Release, error) { } if r == nil { - return nil, fmt.Errorf("there is nothing in the release") + return nil, errors.New("there is nothing in the release") } return r, nil } diff --git a/pkg/iac/scanners/terraform/parser/funcs/collection.go b/pkg/iac/scanners/terraform/parser/funcs/collection.go index d5deb65a68e5..aea716d1c9b2 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/collection.go +++ b/pkg/iac/scanners/terraform/parser/funcs/collection.go @@ -523,7 +523,7 @@ var SumFunc = function.New(&function.Spec{ if r := recover(); r != nil { if _, ok := r.(big.ErrNaN); ok { ret = cty.NilVal - err = fmt.Errorf("can't compute sum of opposing infinities") + err = errors.New("can't compute sum of opposing infinities") } else { // not a panic we recognize panic(r) @@ -623,10 +623,10 @@ var ListFunc = function.New(&function.Spec{ AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { - return cty.DynamicPseudoType, fmt.Errorf("the \"list\" function was deprecated in Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to write a literal list") + return cty.DynamicPseudoType, errors.New("the \"list\" function was deprecated in Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to write a literal list") }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.DynamicVal, fmt.Errorf("the \"list\" function was deprecated in Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to write a literal list") + return cty.DynamicVal, errors.New("the \"list\" function was deprecated in Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to write a literal list") }, }) @@ -644,9 +644,9 @@ var MapFunc = function.New(&function.Spec{ AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { - return cty.DynamicPseudoType, fmt.Errorf("the \"map\" function was deprecated in Terraform v0.12 and is no longer available; use tomap({ ... }) syntax to write a literal map") + return cty.DynamicPseudoType, errors.New("the \"map\" function was deprecated in Terraform v0.12 and is no longer available; use tomap({ ... }) syntax to write a literal map") }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.DynamicVal, fmt.Errorf("the \"map\" function was deprecated in Terraform v0.12 and is no longer available; use tomap({ ... }) syntax to write a literal map") + return cty.DynamicVal, errors.New("the \"map\" function was deprecated in Terraform v0.12 and is no longer available; use tomap({ ... }) syntax to write a literal map") }, }) diff --git a/pkg/iac/scanners/terraform/parser/funcs/crypto.go b/pkg/iac/scanners/terraform/parser/funcs/crypto.go index 894da1280c1a..76e5a7c13cfe 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/crypto.go +++ b/pkg/iac/scanners/terraform/parser/funcs/crypto.go @@ -10,6 +10,7 @@ import ( "encoding/asn1" "encoding/base64" "encoding/hex" + "errors" "fmt" "hash" "io" @@ -118,7 +119,7 @@ var BcryptFunc = function.New(&function.Spec{ } if len(args) > 2 { - return cty.UnknownVal(cty.String), fmt.Errorf("bcrypt() takes no more than two arguments") + return cty.UnknownVal(cty.String), errors.New("bcrypt() takes no more than two arguments") } input := args[0].AsString() diff --git a/pkg/iac/scanners/terraform/parser/funcs/encoding.go b/pkg/iac/scanners/terraform/parser/funcs/encoding.go index e5fb8490818f..75876dfd33f7 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/encoding.go +++ b/pkg/iac/scanners/terraform/parser/funcs/encoding.go @@ -5,6 +5,7 @@ import ( "bytes" "compress/gzip" "encoding/base64" + "errors" "fmt" "log" "net/url" @@ -35,7 +36,7 @@ var Base64DecodeFunc = function.New(&function.Spec{ } if !utf8.Valid([]byte(sDec)) { log.Printf("[DEBUG] the result of decoding the provided string is not valid UTF-8: %s", redactIfSensitive(sDec, strMarks)) - return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the provided string is not valid UTF-8") + return cty.UnknownVal(cty.String), errors.New("the result of decoding the provided string is not valid UTF-8") } return cty.StringVal(string(sDec)).WithMarks(strMarks), nil }, diff --git a/pkg/iac/scanners/terraform/parser/funcs/filesystem.go b/pkg/iac/scanners/terraform/parser/funcs/filesystem.go index 9d9b94f52b1a..24ac8580ee77 100644 --- a/pkg/iac/scanners/terraform/parser/funcs/filesystem.go +++ b/pkg/iac/scanners/terraform/parser/funcs/filesystem.go @@ -136,7 +136,7 @@ func MakeTemplateFileFunc(target fs.FS, baseDir string, funcsCb func() map[strin funcs[name] = function.New(&function.Spec{ Params: params, Type: func(args []cty.Value) (cty.Type, error) { - return cty.NilType, fmt.Errorf("cannot recursively call templatefile from inside templatefile call") + return cty.NilType, errors.New("cannot recursively call templatefile from inside templatefile call") }, }) continue diff --git a/pkg/iac/scanners/terraform/parser/load_module.go b/pkg/iac/scanners/terraform/parser/load_module.go index 78ebe3430b4e..dcf0f9648ef7 100644 --- a/pkg/iac/scanners/terraform/parser/load_module.go +++ b/pkg/iac/scanners/terraform/parser/load_module.go @@ -2,6 +2,7 @@ package parser import ( "context" + "errors" "fmt" "io/fs" "path" @@ -99,7 +100,7 @@ func (e *evaluator) loadModuleFromTerraformCache(ctx context.Context, b *terrafo } } if modulePath == "" { - return nil, fmt.Errorf("failed to load module from .terraform/modules") + return nil, errors.New("failed to load module from .terraform/modules") } if strings.HasPrefix(source, ".") { source = "" diff --git a/pkg/iac/scanners/terraform/parser/resolvers/cache.go b/pkg/iac/scanners/terraform/parser/resolvers/cache.go index 24f803f60139..5e7641af3333 100644 --- a/pkg/iac/scanners/terraform/parser/resolvers/cache.go +++ b/pkg/iac/scanners/terraform/parser/resolvers/cache.go @@ -4,7 +4,7 @@ import ( "context" "crypto/md5" // #nosec "encoding/hex" - "fmt" + "errors" "io/fs" "os" "path/filepath" @@ -37,7 +37,7 @@ func locateCacheDir(cacheDir string) (string, error) { return "", err } if !isWritable(cacheDir) { - return "", fmt.Errorf("cache directory is not writable") + return "", errors.New("cache directory is not writable") } return cacheDir, nil } diff --git a/pkg/iac/scanners/terraform/parser/resolvers/registry.go b/pkg/iac/scanners/terraform/parser/resolvers/registry.go index 471416463cad..c9b303b3ef77 100644 --- a/pkg/iac/scanners/terraform/parser/resolvers/registry.go +++ b/pkg/iac/scanners/terraform/parser/resolvers/registry.go @@ -3,6 +3,7 @@ package resolvers import ( "context" "encoding/json" + "errors" "fmt" "io/fs" "net/http" @@ -188,7 +189,7 @@ func resolveVersion(input string, versions moduleVersions) (string, error) { return "", fmt.Errorf("1 module expected, found %d", len(versions.Modules)) } if len(versions.Modules[0].Versions) == 0 { - return "", fmt.Errorf("no available versions for module") + return "", errors.New("no available versions for module") } constraints, err := version.NewConstraints(input) diff --git a/pkg/iac/scanners/terraformplan/snapshot/plan.go b/pkg/iac/scanners/terraformplan/snapshot/plan.go index 3f0c3adcd791..71cafb6e0ea0 100644 --- a/pkg/iac/scanners/terraformplan/snapshot/plan.go +++ b/pkg/iac/scanners/terraformplan/snapshot/plan.go @@ -1,6 +1,7 @@ package snapshot import ( + "errors" "fmt" "io" @@ -54,7 +55,7 @@ func readTfPlan(r io.Reader) (*Plan, error) { for k, v := range rawPlan.Variables { if len(v.Msgpack) == 0 { // len(0) because that's the default value for a "bytes" in protobuf - return nil, fmt.Errorf("dynamic value does not have msgpack serialization") + return nil, errors.New("dynamic value does not have msgpack serialization") } plan.variableValues[k] = DynamicValue(v.Msgpack) diff --git a/pkg/iac/terraform/block.go b/pkg/iac/terraform/block.go index 348f938d4559..d40f73cbbf72 100644 --- a/pkg/iac/terraform/block.go +++ b/pkg/iac/terraform/block.go @@ -707,7 +707,7 @@ func (b *Block) iteratorName(blockType string) (string, error) { } if len(traversal) != 1 { - return "", fmt.Errorf("dynamic iterator must be a single variable name") + return "", errors.New("dynamic iterator must be a single variable name") } return traversal.RootName(), nil diff --git a/pkg/iac/terraform/modules.go b/pkg/iac/terraform/modules.go index 515d3dc8007d..24c67e6f161b 100644 --- a/pkg/iac/terraform/modules.go +++ b/pkg/iac/terraform/modules.go @@ -1,7 +1,7 @@ package terraform import ( - "fmt" + "errors" "github.com/aquasecurity/trivy/pkg/iac/types" ) @@ -65,7 +65,7 @@ func (m Modules) GetReferencedBlock(referringAttr *Attribute, parentBlock *Block if bestMatch != nil { return bestMatch, nil } - return nil, fmt.Errorf("block not found") + return nil, errors.New("block not found") } func (m Modules) GetReferencingResources(originalBlock *Block, referencingLabel, referencingAttributeName string) Blocks { @@ -92,7 +92,7 @@ func (m Modules) GetBlockById(id string) (*Block, error) { } } - return nil, fmt.Errorf("block not found") + return nil, errors.New("block not found") } func (m Modules) GetResourceByIDs(id ...string) Blocks { diff --git a/pkg/iac/terraform/reference.go b/pkg/iac/terraform/reference.go index a84fb6175180..de601d7433a0 100644 --- a/pkg/iac/terraform/reference.go +++ b/pkg/iac/terraform/reference.go @@ -1,6 +1,7 @@ package terraform import ( + "errors" "fmt" "github.com/zclconf/go-cty/cty" @@ -30,7 +31,7 @@ func newReference(parts []string, parentKey string) (*Reference, error) { var ref Reference if len(parts) == 0 { - return nil, fmt.Errorf("cannot create empty reference") + return nil, errors.New("cannot create empty reference") } blockType, err := TypeFromRefName(parts[0]) diff --git a/pkg/iac/terraform/type.go b/pkg/iac/terraform/type.go index e7c6cab76f15..5a91fee61a5f 100644 --- a/pkg/iac/terraform/type.go +++ b/pkg/iac/terraform/type.go @@ -1,6 +1,6 @@ package terraform -import "fmt" +import "errors" type Type struct { name string @@ -104,5 +104,5 @@ func TypeFromRefName(name string) (*Type, error) { return &valid, nil } } - return nil, fmt.Errorf("block type not found") + return nil, errors.New("block type not found") } diff --git a/pkg/k8s/scanner/scanner.go b/pkg/k8s/scanner/scanner.go index 70debfe6a85f..8c307a36f094 100644 --- a/pkg/k8s/scanner/scanner.go +++ b/pkg/k8s/scanner/scanner.go @@ -3,6 +3,7 @@ package scanner import ( "bytes" "context" + "errors" "fmt" "sort" "strings" @@ -374,7 +375,7 @@ func (s *Scanner) clusterInfoToReportResources(allArtifact []*artifacts.Artifact // Find the first node name to identify AKS cluster var nodeName string if nodeName = s.findNodeName(allArtifact); nodeName == "" { - return nil, fmt.Errorf("failed to find node name") + return nil, errors.New("failed to find node name") } kbom := core.NewBOM(core.Options{ diff --git a/pkg/oci/artifact_test.go b/pkg/oci/artifact_test.go index a8ce6e542641..6bdbce11f72a 100644 --- a/pkg/oci/artifact_test.go +++ b/pkg/oci/artifact_test.go @@ -2,7 +2,7 @@ package oci_test import ( "context" - "fmt" + "errors" "os" "path/filepath" "testing" @@ -71,7 +71,7 @@ func TestArtifact_Download(t *testing.T) { name: "sad: Layers returns an error", mediaType: "application/vnd.cncf.openpolicyagent.layer.v1.tar+gzip", layersReturns: layersReturns{ - err: fmt.Errorf("error"), + err: errors.New("error"), }, wantErr: "OCI layer error", }, diff --git a/pkg/parallel/pipeline_test.go b/pkg/parallel/pipeline_test.go index 4fb008c9e00e..dd2cf9641494 100644 --- a/pkg/parallel/pipeline_test.go +++ b/pkg/parallel/pipeline_test.go @@ -2,7 +2,7 @@ package parallel_test import ( "context" - "fmt" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -78,7 +78,7 @@ func TestPipeline_Do(t *testing.T) { 3, }, onItem: func(_ context.Context, _ int) (int, error) { - return 0, fmt.Errorf("error") + return 0, errors.New("error") }, }, wantErr: require.Error, @@ -92,7 +92,7 @@ func TestPipeline_Do(t *testing.T) { 2, }, onItem: func(_ context.Context, _ int) (int, error) { - return 0, fmt.Errorf("error") + return 0, errors.New("error") }, }, wantErr: require.Error, diff --git a/pkg/policy/policy_test.go b/pkg/policy/policy_test.go index 4752fa4ce7fc..a11a0336e3ee 100644 --- a/pkg/policy/policy_test.go +++ b/pkg/policy/policy_test.go @@ -3,7 +3,7 @@ package policy_test import ( "context" "encoding/json" - "fmt" + "errors" "io" "os" "path/filepath" @@ -49,7 +49,7 @@ func (b brokenLayer) MediaType() (types.MediaType, error) { } func (b brokenLayer) Compressed() (io.ReadCloser, error) { - return nil, fmt.Errorf("compressed error") + return nil, errors.New("compressed error") } func newBrokenLayer(t *testing.T) v1.Layer { @@ -194,7 +194,7 @@ func TestClient_NeedsUpdate(t *testing.T) { name: "sad: Digest returns an error", clock: fake.NewFakeClock(time.Date(2021, 1, 2, 1, 0, 0, 0, time.UTC)), digestReturns: digestReturns{ - err: fmt.Errorf("error"), + err: errors.New("error"), }, metadata: policy.Metadata{ Digest: `sha256:922e50f14ab484f11ae65540c3d2d76009020213f1027d4331d31141575e5414`, @@ -322,7 +322,7 @@ func TestClient_DownloadBuiltinPolicies(t *testing.T) { layers: []v1.Layer{newFakeLayer(t)}, }, digestReturns: digestReturns{ - err: fmt.Errorf("error"), + err: errors.New("error"), }, want: &policy.Metadata{ Digest: "sha256:01e033e78bd8a59fa4f4577215e7da06c05e1152526094d8d79d2aa06e98cb9d",