Skip to content

Commit

Permalink
Enable a few more golangci-lint rules (#1280)
Browse files Browse the repository at this point in the history
Some of these were broken in the past. Enabling those now and one
of them caught an actual issue, where we'd shadow the value of
`err` in the command worker, and may not have some errors reported
as we'd have expected.

The nolintlint rule that checks ignore directives may turn out to
be too annoying, but it was at least good to have it help clear out
comments that were not redundant. Leaving it on for now and we can
always disable if it turns out to be irritating.

Signed-off-by: Anders Eknert <anders@styra.com>
  • Loading branch information
anderseknert authored Dec 3, 2024
1 parent 2d6b61c commit da251c9
Show file tree
Hide file tree
Showing 25 changed files with 36 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
- uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1
if: matrix.os.name == 'linux'
with:
version: v1.60.3
version: v1.61.0
- uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: regal-${{ matrix.os.name }}
Expand Down
4 changes: 0 additions & 4 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
linters:
enable-all: true
disable:
# does not work with generics (yet)
- rowserrcheck
- wastedassign
# annoying
- gocyclo
- tagliatelle
Expand All @@ -23,7 +20,6 @@ linters:
- cyclop
- ireturn
- funlen
- nolintlint
- gomoddirectives # need replacements for wasip1
- execinquery # deprecated
- exportloopref # deprecated
Expand Down
5 changes: 1 addition & 4 deletions cmd/new.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// nolint:wrapcheck
//nolint:wrapcheck
package cmd

import (
Expand All @@ -20,9 +20,6 @@ import (
"github.com/styrainc/regal/pkg/config"
)

// The revive check will warn about using underscore in struct names, but it's seemingly not aware of keywords.
//
//nolint:revive
type newRuleCommandParams struct {
type_ string // 'type' is a keyword
category string
Expand Down
3 changes: 2 additions & 1 deletion internal/capabilities/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ func lookupEmbeddedURL(parsedURL *url.URL) (*ast.Capabilities, error) {
}

engine := elems[1]
version := ""

var version string

if len(elems) == 3 {
version = elems[2]
Expand Down
1 change: 0 additions & 1 deletion internal/embeds/embeds.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:gochecknoglobals
package embeds

import (
Expand Down
2 changes: 1 addition & 1 deletion internal/io/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func IsSkipWalkDirectory(info files.DirEntry) bool {
// are passed to the callback, and where directories that should commonly be ignored
// (.git, node_modules, etc.) are skipped.
func WalkFiles(root string, f func(path string) error) error {
return filepath.WalkDir(root, func(path string, info os.DirEntry, _ error) error { // nolint:wrapcheck
return filepath.WalkDir(root, func(path string, info os.DirEntry, _ error) error { //nolint:wrapcheck
if IsSkipWalkDirectory(info) {
return filepath.SkipDir
}
Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/bundles/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func calculateMD5(filePath string) ([]byte, error) {
}
defer file.Close()

// nolint:gosec
//nolint:gosec
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return nil, fmt.Errorf("failed to calculate MD5 hash for file %q: %w", filePath, err)
Expand Down
3 changes: 0 additions & 3 deletions internal/lsp/completions/providers/ruleheadkeyword.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:dupl
package providers

import (
Expand Down Expand Up @@ -74,14 +73,12 @@ func (*RuleHeadKeyword) Run(
case len(words) == 2 && strings.HasPrefix(keyWdAssign, lastWord):
keywords[keyWdAssign] = true
// suggest contains after the name of the rule in the rule head
//nolint:gocritic
case len(words) == 2 && strings.HasPrefix(keyWdContains, lastWord):
keywords[keyWdContains] = true
// suggest if at the end of the rule head
case len(words) == 4 && words[1] == keyWdContains:
keywords[keyWdIf] = true
// suggest if after the rule name
//nolint:gocritic
case len(words) == 2 && strings.HasPrefix(keyWdIf, lastWord):
keywords[keyWdIf] = true
}
Expand Down
1 change: 0 additions & 1 deletion internal/lsp/completions/providers/ruleheadkeyword_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:dupl
package providers

import (
Expand Down
9 changes: 4 additions & 5 deletions internal/lsp/completions/providers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,10 @@ import (
"github.com/styrainc/regal/internal/lsp/types"
)

//nolint:gochecknoglobals
var patternRuleBody = regexp.MustCompile(`^\s+`)

//nolint:gochecknoglobals
var patternWhiteSpace = regexp.MustCompile(`\s+`)
var (
patternRuleBody = regexp.MustCompile(`^\s+`)
patternWhiteSpace = regexp.MustCompile(`\s+`)
)

// completionLineHelper returns the lines of a file and the current line for a given index. This
// function is used by multiple completion providers.
Expand Down
3 changes: 2 additions & 1 deletion internal/lsp/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ type operation struct {

// operations returns the list of operations to convert a into b, consolidating
// operations for multiple lines and not including equal lines.
// nolint:gosec
//
//nolint:gosec
func operations(a, b []string) []*operation {
if len(a) == 0 && len(b) == 0 {
return nil
Expand Down
4 changes: 2 additions & 2 deletions internal/lsp/documentsymbol.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func documentSymbols(

lines := strings.Split(contents, "\n")

// nolint:gosec
//nolint:gosec
pkgRange := types.Range{
Start: types.Position{Line: 0, Character: 0},
End: types.Position{Line: uint(len(lines) - 1), Character: uint(len(lines[len(lines)-1]))},
Expand Down Expand Up @@ -129,7 +129,7 @@ func documentSymbols(
return docSymbols
}

// nolint:gosec
//nolint:gosec
func locationToRange(location *ast.Location) types.Range {
lines := bytes.Split(location.Text, []byte("\n"))

Expand Down
4 changes: 2 additions & 2 deletions internal/lsp/foldingrange.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (s stack) Pop() (stack, scanner.Position) {
return s[:l-1], s[l-1]
}

// nolint:gosec
//nolint:gosec
func TokenFoldingRanges(policy string) []types.FoldingRange {
scn, err := scanner.New(strings.NewReader(policy))
if err != nil {
Expand Down Expand Up @@ -99,7 +99,7 @@ func TokenFoldingRanges(policy string) []types.FoldingRange {
return foldingRanges
}

// nolint:gosec
//nolint:gosec
func findFoldingRanges(text string, module *ast.Module) []types.FoldingRange {
uintZero := uint(0)

Expand Down
2 changes: 1 addition & 1 deletion internal/lsp/hover/hover.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func UpdateBuiltinPositions(cache *cache.Cache, uri string, builtins map[string]

builtinsOnLine := map[uint][]types2.BuiltinPosition{}

// nolint:gosec
//nolint:gosec
for _, call := range rego.AllBuiltinCalls(module, builtins) {
line := uint(call.Location.Row)

Expand Down
4 changes: 2 additions & 2 deletions internal/lsp/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func updateParse(
link = "https://docs.styra.com/opa/errors/" + hints[0]
}

// nolint:gosec
//nolint:gosec
diags = append(diags, types.Diagnostic{
Severity: 1, // parse errors are the only error Diagnostic the server sends
Range: types.Range{
Expand Down Expand Up @@ -323,7 +323,7 @@ type astError struct {
Message string `json:"message"`
}

// nolint:gosec
//nolint:gosec
func getRangeForViolation(item report.Violation) types.Range {
start := types.Position{
Line: uint(max(item.Location.Row-1, 0)),
Expand Down
8 changes: 4 additions & 4 deletions internal/lsp/rego/rego.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type KeywordUseLocation struct {
}

func PositionFromLocation(loc *ast.Location) types.Position {
// nolint:gosec
//nolint:gosec
return types.Position{
Line: uint(loc.Row - 1),
Character: uint(loc.Col - 1),
Expand All @@ -47,8 +47,8 @@ func PositionFromLocation(loc *ast.Location) types.Position {

func LocationFromPosition(pos types.Position) *ast.Location {
return &ast.Location{
Row: int(pos.Line + 1), // nolint: gosec
Col: int(pos.Character + 1), // nolint: gosec
Row: int(pos.Line + 1), //nolint: gosec
Col: int(pos.Character + 1), //nolint: gosec
}
}

Expand Down Expand Up @@ -200,7 +200,7 @@ func queryToValue[T any](ctx context.Context, pq *rego.PreparedEvalQuery, policy

result, err := toValidResult(pq.Eval(ctx, rego.EvalInput(input)))
if err != nil {
return toValue, err //nolint:wrapcheck
return toValue, err
}

if err := rio.JSONRoundTrip(result.Expressions[0].Value, &toValue); err != nil {
Expand Down
15 changes: 9 additions & 6 deletions internal/lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ func (l *LanguageServer) StartConfigWorker(ctx context.Context) {

var regalEvalUseAsInputComment = regexp.MustCompile(`^\s*regal eval:\s*use-as-input`)

func (l *LanguageServer) StartCommandWorker(ctx context.Context) { // nolint:maintidx
func (l *LanguageServer) StartCommandWorker(ctx context.Context) { //nolint:maintidx
// note, in this function conn.Call is used as the workspace/applyEdit message is a request, not a notification
// as per the spec. In order to be 'routed' to the correct handler on the client it must have an ID
// receive responses too.
Expand Down Expand Up @@ -809,7 +809,9 @@ func (l *LanguageServer) StartCommandWorker(ctx context.Context) { // nolint:mai
break
}

allRuleHeadLocations, err := rego.AllRuleHeadLocations(ctx, filepath.Base(file), currentContents, currentModule)
var allRuleHeadLocations rego.RuleHeads

allRuleHeadLocations, err = rego.AllRuleHeadLocations(ctx, filepath.Base(file), currentContents, currentModule)
if err != nil {
l.logf(log.LevelMessage, "failed to get rule head locations: %s", err)

Expand Down Expand Up @@ -840,7 +842,9 @@ func (l *LanguageServer) StartCommandWorker(ctx context.Context) { // nolint:mai
}
}

result, err := l.EvalWorkspacePath(ctx, path, inputMap)
var result EvalPathResult

result, err = l.EvalWorkspacePath(ctx, path, inputMap)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to evaluate workspace path: %v\n", err)

Expand Down Expand Up @@ -899,8 +903,7 @@ func (l *LanguageServer) StartCommandWorker(ctx context.Context) { // nolint:mai

jsonVal, err = json.MarshalIndent(value, "", " ")
if err == nil {
// staticcheck thinks err here is never used, but I think that's false?
_, err = f.Write(jsonVal) //nolint:staticcheck
_, err = f.Write(jsonVal)
}

f.Close()
Expand Down Expand Up @@ -1849,7 +1852,7 @@ func (l *LanguageServer) handleTextDocumentDefinition(
return nil, nil
}

// nolint:gosec
//nolint:gosec
loc := types.Location{
URI: uri.FromPath(l.clientIdentifier, definition.Result.File),
Range: types.Range{
Expand Down
2 changes: 0 additions & 2 deletions internal/lsp/server_aggregates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/styrainc/regal/pkg/report"
)

//nolint:maintidx
func TestLanguageServerLintsUsingAggregateState(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -289,7 +288,6 @@ import data.wow # new
}
}

// nolint:maintidx
func TestLanguageServerAggregateViolationFixedAndReintroducedInUnviolatingFileChange(t *testing.T) {
t.Parallel()

Expand Down
2 changes: 0 additions & 2 deletions internal/lsp/server_multi_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import (
// files in the workspace, the diagnostics worker also processes aggregate violations, there are also changes to when
// workspace diagnostics are run, this test validates that the correct diagnostics are sent to the client in this
// scenario.
//
// nolint:maintidx
func TestLanguageServerMultipleFiles(t *testing.T) {
t.Parallel()

Expand Down
1 change: 0 additions & 1 deletion internal/test/test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//nolint:gochecknoglobals
package test

import (
Expand Down
2 changes: 1 addition & 1 deletion internal/web/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const mainTemplate = "main.tpl"
//go:embed assets/*
var assets embed.FS

//nolint:gochecknoglobals,lll
//nolint:gochecknoglobals
var tpl = template.Must(template.New("main.tpl").ParseFS(assets, "assets/main.tpl"))

type Server struct {
Expand Down
2 changes: 1 addition & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ func (rule *Rule) UnmarshalYAML(value *yaml.Node) error {
return fmt.Errorf("unmarshalling rule failed %w", err)
}

return rule.mapToConfig(result) //nolint:errcheck
return rule.mapToConfig(result)
}

// Note that this function will mutate the result map. This isn't a problem right now
Expand Down
2 changes: 1 addition & 1 deletion pkg/fixer/fixes/directorypackagemismatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (d *DirectoryPackageMismatch) Fix(fc *FixCandidate, opts *RuntimeOptions) (
func getPackagePathDirectory(fc *FixCandidate, config *config.Config) (string, error) {
module, err := ast.ParseModule(fc.Filename, string(fc.Contents))
if err != nil {
return "", err // nolint:wrapcheck
return "", err //nolint:wrapcheck
}

parts := make([]string, len(module.Package.Path)-1)
Expand Down
2 changes: 1 addition & 1 deletion pkg/linter/linter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ func TestLintMergedConfigInheritsLevelFromProvided(t *testing.T) {
fileLength := mergedConfig.Rules["style"]["file-length"].Extra["max-file-length"]

// Ensure the extra attributes are still there.
if fileLength.(int) != 1 { // nolint: forcetypeassert
if fileLength.(int) != 1 { //nolint: forcetypeassert
t.Errorf("expected max-file-length to be 1, got %d %T", fileLength, fileLength)
}
}
Expand Down
3 changes: 0 additions & 3 deletions pkg/reporter/reporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ func TestJSONReporterPublishNoViolations(t *testing.T) {
}
}

// nolint:paralleltest
func TestGitHubReporterPublish(t *testing.T) {
// Can't use t.Parallel() here because t.Setenv() forbids that
t.Setenv("GITHUB_STEP_SUMMARY", "")
Expand All @@ -234,7 +233,6 @@ func TestGitHubReporterPublish(t *testing.T) {
}
}

// nolint:paralleltest
func TestGitHubReporterPublishNoViolations(t *testing.T) {
// Can't use t.Parallel() here because t.Setenv() forbids that
t.Setenv("GITHUB_STEP_SUMMARY", "")
Expand Down Expand Up @@ -307,7 +305,6 @@ func TestSarifReporterPublishNoViolations(t *testing.T) {
}
}

// nolint:lll // the expected output is unfortunately longer than the allowed max line length
func TestJUnitReporterPublish(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit da251c9

Please sign in to comment.