Skip to content

Commit 3be5e6b

Browse files
authored
chore: enable go-critic (aquasecurity#5302)
* chore: enable gocritic Signed-off-by: knqyf263 <[email protected]> * refactor: fix lint issues Signed-off-by: knqyf263 <[email protected]> * test: return true for latest versions Signed-off-by: knqyf263 <[email protected]> * chore(lint): enforce map and slice styles Signed-off-by: knqyf263 <[email protected]> --------- Signed-off-by: knqyf263 <[email protected]>
1 parent f6cd21c commit 3be5e6b

File tree

103 files changed

+584
-531
lines changed

Some content is hidden

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

103 files changed

+584
-531
lines changed

.golangci.yaml

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,28 @@ linters-settings:
4343
recommendations:
4444
- github.com/aquasecurity/go-version
4545
reason: "`aquasecurity/go-version` is designed for our use-cases"
46+
gocritic:
47+
disabled-checks:
48+
- appendAssign
49+
- unnamedResult
50+
- whyNoLint
51+
- indexAlloc
52+
- octalLiteral
53+
- hugeParam
54+
- rangeValCopy
55+
- regexpSimplify
56+
- sloppyReassign
57+
- commentedOutCode
58+
enabled-tags:
59+
- diagnostic
60+
- style
61+
- performance
62+
- experimental
63+
- opinionated
64+
settings:
65+
ruleguard:
66+
failOn: all
67+
rules: '${configDir}/misc/lint/rules.go'
4668

4769
linters:
4870
disable-all: true
@@ -62,6 +84,7 @@ linters:
6284
- gci
6385
- gomodguard
6486
- tenv
87+
- gocritic
6588

6689
run:
6790
go: '1.20'

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ require (
7575
github.com/openvex/go-vex v0.2.5
7676
github.com/owenrumney/go-sarif/v2 v2.2.2
7777
github.com/package-url/packageurl-go v0.1.2-0.20230812223828-f8bb31c1f10b
78+
github.com/quasilyte/go-ruleguard/dsl v0.3.22
7879
github.com/samber/lo v1.38.1
7980
github.com/saracen/walker v0.1.3
8081
github.com/secure-systems-lab/go-securesystemslib v0.7.0

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1534,6 +1534,8 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
15341534
github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg=
15351535
github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM=
15361536
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
1537+
github.com/quasilyte/go-ruleguard/dsl v0.3.22 h1:wd8zkOhSNr+I+8Qeciml08ivDt1pSXe60+5DqOpCjPE=
1538+
github.com/quasilyte/go-ruleguard/dsl v0.3.22/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU=
15371539
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM=
15381540
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
15391541
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=

magefiles/magefile.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,11 +393,12 @@ func (Docs) Generate() error {
393393
func findProtoFiles() ([]string, error) {
394394
var files []string
395395
err := filepath.WalkDir("rpc", func(path string, d fs.DirEntry, err error) error {
396-
if err != nil {
396+
switch {
397+
case err != nil:
397398
return err
398-
} else if d.IsDir() {
399+
case d.IsDir():
399400
return nil
400-
} else if filepath.Ext(path) == ".proto" {
401+
case filepath.Ext(path) == ".proto":
401402
files = append(files, path)
402403
}
403404
return nil

misc/lint/rules.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
//go:build ruleguard
2+
3+
package gorules
4+
5+
import "github.com/quasilyte/go-ruleguard/dsl"
6+
7+
// cf. https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices
8+
func declareEmptySlices(m dsl.Matcher) {
9+
m.Match(
10+
`$name := []$t{}`,
11+
`$name := make([]$t, 0)`,
12+
).
13+
Suggest(`var $name []$t`).
14+
Report(`replace '$$' with 'var $name []$t'`)
15+
}
16+
17+
// cf. https://github.com/uber-go/guide/blob/master/style.md#initializing-maps
18+
func initializeMaps(m dsl.Matcher) {
19+
m.Match(`map[$key]$value{}`).
20+
Suggest(`make(map[$key]$value)`).
21+
Report(`replace '$$' with 'make(map[$key]$value)`)
22+
}

pkg/cloud/aws/cache/cache.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ var ErrCacheNotFound = fmt.Errorf("cache record not found")
3737
var ErrCacheIncompatible = fmt.Errorf("cache record used incomatible schema")
3838
var ErrCacheExpired = fmt.Errorf("cache record expired")
3939

40-
func New(cacheDir string, maxCacheAge time.Duration, accountID string, region string) *Cache {
40+
func New(cacheDir string, maxCacheAge time.Duration, accountID, region string) *Cache {
4141
return &Cache{
4242
path: path.Join(cacheDir, "cloud", "aws", accountID, strings.ToLower(region), "data.json"),
4343
accountID: accountID,
@@ -70,7 +70,7 @@ func (c *Cache) load() (*CacheData, error) {
7070
return &data, nil
7171
}
7272

73-
func (c *Cache) ListServices(required []string) (included []string, missing []string) {
73+
func (c *Cache) ListServices(required []string) (included, missing []string) {
7474

7575
data, err := c.load()
7676
if err != nil {
@@ -101,12 +101,11 @@ func (c *Cache) LoadState() (*state.State, error) {
101101
return data.State, nil
102102
}
103103

104-
func (c *Cache) AddServices(state *state.State, includedServices []string) error {
105-
104+
func (c *Cache) AddServices(s *state.State, includedServices []string) error {
106105
data := &CacheData{
107106
SchemaVersion: SchemaVersion,
108-
State: state,
109-
Services: map[string]ServiceMetadata{},
107+
State: s,
108+
Services: make(map[string]ServiceMetadata),
110109
Updated: time.Now(),
111110
}
112111

pkg/cloud/aws/commands/run.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,11 @@ func processOptions(ctx context.Context, opt *flag.Options) error {
9595
}
9696

9797
func filterServices(opt *flag.Options) error {
98-
if len(opt.Services) == 0 && len(opt.SkipServices) == 0 {
98+
switch {
99+
case len(opt.Services) == 0 && len(opt.SkipServices) == 0:
99100
log.Logger.Debug("No service(s) specified, scanning all services...")
100101
opt.Services = allSupportedServicesFunc()
101-
} else if len(opt.SkipServices) > 0 {
102+
case len(opt.SkipServices) > 0:
102103
log.Logger.Debug("excluding services: ", opt.SkipServices)
103104
for _, s := range allSupportedServicesFunc() {
104105
if slices.Contains(opt.SkipServices, s) {
@@ -108,7 +109,7 @@ func filterServices(opt *flag.Options) error {
108109
opt.Services = append(opt.Services, s)
109110
}
110111
}
111-
} else if len(opt.Services) > 0 {
112+
case len(opt.Services) > 0:
112113
log.Logger.Debugf("Specific services were requested: [%s]...", strings.Join(opt.Services, ", "))
113114
for _, service := range opt.Services {
114115
var found bool

pkg/cloud/aws/scanner/scanner.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,19 @@ func (s *AWSScanner) Scan(ctx context.Context, option flag.Options) (scan.Result
8787
return nil, false, xerrors.Errorf("unable to create policyfs: %w", err)
8888
}
8989

90-
scannerOpts = append(scannerOpts, options.ScannerWithPolicyFilesystem(policyFS))
91-
scannerOpts = append(scannerOpts, options.ScannerWithPolicyDirs(policyPaths...))
90+
scannerOpts = append(scannerOpts,
91+
options.ScannerWithPolicyFilesystem(policyFS),
92+
options.ScannerWithPolicyDirs(policyPaths...),
93+
)
9294

9395
dataFS, dataPaths, err := misconf.CreateDataFS(option.RegoOptions.DataPaths)
9496
if err != nil {
9597
log.Logger.Errorf("Could not load config data: %s", err)
9698
}
97-
scannerOpts = append(scannerOpts, options.ScannerWithDataDirs(dataPaths...))
98-
scannerOpts = append(scannerOpts, options.ScannerWithDataFilesystem(dataFS))
99+
scannerOpts = append(scannerOpts,
100+
options.ScannerWithDataDirs(dataPaths...),
101+
options.ScannerWithDataFilesystem(dataFS),
102+
)
99103

100104
scannerOpts = addPolicyNamespaces(option.RegoOptions.PolicyNamespaces, scannerOpts)
101105

pkg/commands/app.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ func NewImageCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
307307
func NewFilesystemCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
308308
reportFlagGroup := flag.NewReportFlagGroup()
309309
reportFormat := flag.ReportFormatFlag
310-
reportFormat.Usage = "specify a compliance report format for the output" //@TODO: support --report summary for non compliance reports
310+
reportFormat.Usage = "specify a compliance report format for the output" // @TODO: support --report summary for non compliance reports
311311
reportFlagGroup.ReportFormat = &reportFormat
312312
reportFlagGroup.ExitOnEOL = nil // disable '--exit-on-eol'
313313

@@ -626,7 +626,7 @@ func NewConfigCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
626626
reportFlagGroup.ListAllPkgs = nil // disable '--list-all-pkgs'
627627
reportFlagGroup.ExitOnEOL = nil // disable '--exit-on-eol'
628628
reportFormat := flag.ReportFormatFlag
629-
reportFormat.Usage = "specify a compliance report format for the output" //@TODO: support --report summary for non compliance reports
629+
reportFormat.Usage = "specify a compliance report format for the output" // @TODO: support --report summary for non compliance reports
630630
reportFlagGroup.ReportFormat = &reportFormat
631631

632632
scanFlags := &flag.ScanFlagGroup{
@@ -1213,6 +1213,6 @@ func flagErrorFunc(command *cobra.Command, err error) error {
12131213
if err := command.Help(); err != nil {
12141214
return err
12151215
}
1216-
command.Println() //add empty line after list of flags
1216+
command.Println() // add empty line after list of flags
12171217
return err
12181218
}

pkg/compliance/report/report.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,10 @@ type Writer interface {
6767
func Write(report *ComplianceReport, option Option) error {
6868
switch option.Format {
6969
case types.FormatJSON:
70-
jwriter := JSONWriter{Output: option.Output, Report: option.Report}
70+
jwriter := JSONWriter{
71+
Output: option.Output,
72+
Report: option.Report,
73+
}
7174
return jwriter.Write(report)
7275
case types.FormatTable:
7376
if !report.empty() {
@@ -93,7 +96,7 @@ func (r ComplianceReport) empty() bool {
9396

9497
// buildControlCheckResults create compliance results data
9598
func buildControlCheckResults(checksMap map[string]types.Results, controls []defsecTypes.Control) []*ControlCheckResult {
96-
complianceResults := make([]*ControlCheckResult, 0)
99+
var complianceResults []*ControlCheckResult
97100
for _, control := range controls {
98101
var results types.Results
99102
for _, c := range control.Checks {
@@ -112,14 +115,14 @@ func buildControlCheckResults(checksMap map[string]types.Results, controls []def
112115
}
113116

114117
// buildComplianceReportResults create compliance results data
115-
func buildComplianceReportResults(checksMap map[string]types.Results, spec defsecTypes.Spec) *ComplianceReport {
116-
controlCheckResult := buildControlCheckResults(checksMap, spec.Controls)
118+
func buildComplianceReportResults(checksMap map[string]types.Results, s defsecTypes.Spec) *ComplianceReport {
119+
controlCheckResult := buildControlCheckResults(checksMap, s.Controls)
117120
return &ComplianceReport{
118-
ID: spec.ID,
119-
Title: spec.Title,
120-
Description: spec.Description,
121-
Version: spec.Version,
122-
RelatedResources: spec.RelatedResources,
121+
ID: s.ID,
122+
Title: s.Title,
123+
Description: s.Description,
124+
Version: s.Version,
125+
RelatedResources: s.RelatedResources,
123126
Results: controlCheckResult,
124127
}
125128
}

0 commit comments

Comments
 (0)