Skip to content

Commit 55e87e7

Browse files
authored
Add perfsprint linter (open-policy-agent#7334)
And update code to conform to the rule. - Replace unnecessary fmt.Sprintf with string concatenation - Replace fmt.Sprint with more efficient strconv.Itoa - Replace static fmt.Errorf calls with more efficient errors.New Thanks @srenatus for pushing me down this rabbit hole! Signed-off-by: Anders Eknert <[email protected]>
1 parent 97b8572 commit 55e87e7

File tree

154 files changed

+759
-679
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

154 files changed

+759
-679
lines changed

.golangci.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,15 @@ linters-settings:
143143
govet:
144144
enable:
145145
- deepequalerrors
146+
perfsprint:
147+
# only rule disabled by default, but it's a good one
148+
err-error: true
149+
revive:
150+
rules:
151+
# this mainly complains about us using min/max for variable names,
152+
# which seems like an unlikely source of actual issues
153+
- name: redefines-builtin-id
154+
disabled: true
146155

147156
linters:
148157
disable-all: true
@@ -164,4 +173,5 @@ linters:
164173
- prealloc
165174
- unconvert
166175
- copyloopvar
176+
- perfsprint
167177
# - gosec # too many false positives

ast/parser_ext.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package ast
66

77
import (
8+
"errors"
89
"fmt"
910

1011
v1 "github.com/open-policy-agent/opa/v1/ast"
@@ -279,7 +280,7 @@ func ParseStatement(input string) (Statement, error) {
279280
return nil, err
280281
}
281282
if len(stmts) != 1 {
282-
return nil, fmt.Errorf("expected exactly one statement")
283+
return nil, errors.New("expected exactly one statement")
283284
}
284285
return stmts[0], nil
285286
}

build/generate-cli-docs/generate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func main() {
8888
removed++
8989
continue
9090
}
91-
document = append(document, fmt.Sprintf("%s\n", str))
91+
document = append(document, str+"\n")
9292
}
9393

9494
withHeader := fmt.Sprintf("%s%s", fileHeader, strings.Join(document, ""))

cmd/bench.go

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"bytes"
99
"context"
1010
"encoding/json"
11+
"errors"
1112
"fmt"
1213
"io"
1314
"math"
@@ -190,7 +191,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc
190191
if err != nil {
191192
return err
192193
} else if len(result) == 0 && params.fail {
193-
return fmt.Errorf("undefined result")
194+
return errors.New("undefined result")
194195
}
195196
return nil
196197
}
@@ -207,7 +208,7 @@ func benchMain(args []string, params benchmarkCommandParams, w io.Writer, r benc
207208
if err != nil {
208209
return err
209210
} else if len(result.Queries) == 0 && params.fail {
210-
return fmt.Errorf("undefined result")
211+
return errors.New("undefined result")
211212
}
212213
return nil
213214
}
@@ -307,7 +308,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
307308
// We fix the issue here by binding port 0; this will result in the OS
308309
// allocating us an open port.
309310
rtParams := runtime.Params{
310-
Addrs: &[]string{fmt.Sprintf("%s:0", host)},
311+
Addrs: &[]string{host + ":0"},
311312
Paths: paths,
312313
Logger: logger,
313314
BundleMode: params.bundlePaths.isFlagSet(),
@@ -365,7 +366,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
365366
}
366367
// Check for port still being unbound after retry loop.
367368
if port == 0 {
368-
return fmt.Errorf("unable to bind a port for bench testing")
369+
return errors.New("unable to bind a port for bench testing")
369370
}
370371

371372
query, err := readQuery(params, args)
@@ -399,7 +400,7 @@ func benchE2E(ctx context.Context, args []string, params benchmarkCommandParams,
399400
} else {
400401
_, err := ast.ParseBody(query)
401402
if err != nil {
402-
return fmt.Errorf("error occurred while parsing query")
403+
return errors.New("error occurred while parsing query")
403404
}
404405

405406
if strings.HasPrefix(query, "data.") {
@@ -536,7 +537,7 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
536537
}
537538

538539
if result.Result == nil && params.fail {
539-
return nil, fmt.Errorf("undefined result")
540+
return nil, errors.New("undefined result")
540541
}
541542

542543
return result.Metrics, nil
@@ -549,31 +550,31 @@ func e2eQuery(params benchmarkCommandParams, url string, input map[string]interf
549550

550551
if params.fail {
551552
if result.Result == nil {
552-
return nil, fmt.Errorf("undefined result")
553+
return nil, errors.New("undefined result")
553554
}
554555

555556
i := *result.Result
556557

557558
peResult, ok := i.(map[string]interface{})
558559
if !ok {
559-
return nil, fmt.Errorf("invalid result for compile response")
560+
return nil, errors.New("invalid result for compile response")
560561
}
561562

562563
if len(peResult) == 0 {
563-
return nil, fmt.Errorf("undefined result")
564+
return nil, errors.New("undefined result")
564565
}
565566

566567
if val, ok := peResult["queries"]; ok {
567568
queries, ok := val.([]interface{})
568569
if !ok {
569-
return nil, fmt.Errorf("invalid result for output of partial evaluation")
570+
return nil, errors.New("invalid result for output of partial evaluation")
570571
}
571572

572573
if len(queries) == 0 {
573-
return nil, fmt.Errorf("undefined result")
574+
return nil, errors.New("undefined result")
574575
}
575576
} else {
576-
return nil, fmt.Errorf("invalid result for output of partial evaluation")
577+
return nil, errors.New("invalid result for output of partial evaluation")
577578
}
578579
}
579580

@@ -606,14 +607,14 @@ func renderBenchmarkResult(params benchmarkCommandParams, br testing.BenchmarkRe
606607
fmt.Fprintf(w, "\n")
607608
default:
608609
data := [][]string{
609-
{"samples", fmt.Sprintf("%d", br.N)},
610+
{"samples", strconv.Itoa(br.N)},
610611
{"ns/op", prettyFormatFloat(float64(br.T.Nanoseconds()) / float64(br.N))},
611612
}
612613
if params.benchMem {
613614
data = append(data, []string{
614-
"B/op", fmt.Sprintf("%d", br.AllocedBytesPerOp()),
615+
"B/op", strconv.FormatInt(br.AllocedBytesPerOp(), 10),
615616
}, []string{
616-
"allocs/op", fmt.Sprintf("%d", br.AllocsPerOp()),
617+
"allocs/op", strconv.FormatInt(br.AllocsPerOp(), 10),
617618
})
618619
}
619620

cmd/bench_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,7 @@ func validateBenchMainPrep(t *testing.T, args []string, params benchmarkCommandP
498498
}
499499

500500
if len(rs) == 0 {
501-
return testing.BenchmarkResult{}, fmt.Errorf("expected result, got none")
501+
return testing.BenchmarkResult{}, errors.New("expected result, got none")
502502
}
503503

504504
return testing.BenchmarkResult{}, nil

cmd/build.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package cmd
77
import (
88
"bytes"
99
"context"
10+
"errors"
1011
"fmt"
1112
"io"
1213
"os"
@@ -232,7 +233,7 @@ against OPA v0.22.0:
232233
`,
233234
PreRunE: func(Cmd *cobra.Command, args []string) error {
234235
if len(args) == 0 {
235-
return fmt.Errorf("expected at least one path")
236+
return errors.New("expected at least one path")
236237
}
237238
return env.CmdFlags.CheckEnvironmentVariables(Cmd)
238239
},
@@ -293,7 +294,7 @@ func dobuild(params buildParams, args []string) error {
293294
}
294295

295296
if (bvc != nil || bsc != nil) && !params.bundleMode {
296-
return fmt.Errorf("enable bundle mode (ie. --bundle) to verify or sign bundle files or directories")
297+
return errors.New("enable bundle mode (ie. --bundle) to verify or sign bundle files or directories")
297298
}
298299

299300
var capabilities *ast.Capabilities

cmd/build_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ import (
44
"archive/tar"
55
"compress/gzip"
66
"encoding/json"
7+
"errors"
78
"fmt"
89
"io"
910
"os"
1011
"path"
1112
"path/filepath"
1213
"reflect"
14+
"strconv"
1315
"strings"
1416
"testing"
1517

@@ -637,7 +639,7 @@ p contains 1
637639
f(x) if { p[x] }
638640
`,
639641
},
640-
err: fmt.Errorf("plan compilation requires at least one entrypoint"),
642+
err: errors.New("plan compilation requires at least one entrypoint"),
641643
},
642644
}
643645
for _, tc := range tests {
@@ -942,7 +944,7 @@ p2 := 2
942944
tr := tar.NewReader(gr)
943945

944946
expManifest := strings.ReplaceAll(tc.manifest, "%REGO_VERSION%",
945-
fmt.Sprintf("%d", ast.DefaultRegoVersion.Int()))
947+
strconv.Itoa(ast.DefaultRegoVersion.Int()))
946948

947949
found := false
948950
for {
@@ -1868,7 +1870,7 @@ q contains 1 if {
18681870
}
18691871
expVal = strings.ReplaceAll(expVal, "%ROOT%", root)
18701872
expVal = strings.ReplaceAll(expVal, "%DEFAULT_REGO_VERSION%",
1871-
fmt.Sprintf("%d", ast.DefaultRegoVersion.Int()))
1873+
strconv.Itoa(ast.DefaultRegoVersion.Int()))
18721874
if string(b) != expVal {
18731875
t.Fatalf("expected %v:\n\n%v\n\nbut got:\n\n%v", expName, expVal, string(b))
18741876
}

cmd/check.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package cmd
66

77
import (
8+
"errors"
89
"fmt"
910
"io"
1011
"io/fs"
@@ -174,7 +175,7 @@ func init() {
174175

175176
PreRunE: func(cmd *cobra.Command, args []string) error {
176177
if len(args) == 0 {
177-
return fmt.Errorf("specify at least one file")
178+
return errors.New("specify at least one file")
178179
}
179180
return env.CmdFlags.CheckEnvironmentVariables(cmd)
180181
},

cmd/eval.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ func validateEvalParams(p *evalCommandParams, cmdArgs []string) error {
155155

156156
if p.optimizationLevel > 0 {
157157
if len(p.dataPaths.v) > 0 && p.bundlePaths.isFlagSet() {
158-
return fmt.Errorf("specify either --data or --bundle flag with optimization level greater than 0")
158+
return errors.New("specify either --data or --bundle flag with optimization level greater than 0")
159159
}
160160
}
161161

@@ -699,7 +699,7 @@ func setupEval(args []string, params evalCommandParams) (*evalContext, error) {
699699
if params.strictBuiltinErrors {
700700
regoArgs = append(regoArgs, rego.StrictBuiltinErrors(true))
701701
if params.showBuiltinErrors {
702-
return nil, fmt.Errorf("cannot use --show-builtin-errors with --strict-builtin-errors, --strict-builtin-errors will return the first built-in error encountered immediately")
702+
return nil, errors.New("cannot use --show-builtin-errors with --strict-builtin-errors, --strict-builtin-errors will return the first built-in error encountered immediately")
703703
}
704704
}
705705

cmd/eval_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -619,17 +619,17 @@ func testReadParamWithSchemaDir(input string, inputSchema string) error {
619619
}
620620

621621
if schemaSet == nil {
622-
err = fmt.Errorf("Schema set is empty")
622+
err = errors.New("Schema set is empty")
623623
return
624624
}
625625

626626
if schemaSet.Get(ast.MustParseRef("schema.input")) == nil {
627-
err = fmt.Errorf("Expected schema for input in schemaSet but got none")
627+
err = errors.New("Expected schema for input in schemaSet but got none")
628628
return
629629
}
630630

631631
if schemaSet.Get(ast.MustParseRef(`schema.kubernetes["data-schema"]`)) == nil {
632-
err = fmt.Errorf("Expected schemas for data in schemaSet but got none")
632+
err = errors.New("Expected schemas for data in schemaSet but got none")
633633
return
634634
}
635635

0 commit comments

Comments
 (0)