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

Add "revive" linter #1729

Merged
merged 5 commits into from
Feb 14, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions .golangci.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,12 @@ linters-settings:
rowserrcheck:
packages:
- github.com/jmoiron/sqlx
revive:
ignore-generated-header: true
severity: warning
rules:
- name: indent-error-flow
severity: warning
testpackage:
# regexp pattern to skip files
skip-regexp: (export|internal)_test\.go
Expand Down
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ linters:
# - nestif
# - prealloc
# - testpackage
# - revive
# - wsl

issues:
Expand Down
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ require (
github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb // v1.0
github.com/mattn/go-colorable v0.1.8
github.com/mbilski/exhaustivestruct v1.2.0
github.com/mgechev/dots v0.0.0-20190921121421-c36f7dcfbb81
github.com/mgechev/revive v1.0.3
github.com/mitchellh/go-homedir v1.1.0
github.com/mitchellh/go-ps v1.0.0
github.com/moricho/tparallel v0.2.1
Expand Down Expand Up @@ -69,9 +71,8 @@ require (
github.com/ultraware/whitespace v0.0.4
github.com/uudashr/gocognit v1.0.1
github.com/valyala/quicktemplate v1.6.3
golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634 // indirect
golang.org/x/text v0.3.4 // indirect
golang.org/x/tools v0.0.0-20210105210202-9ed45478a130
golang.org/x/tools v0.1.0
gopkg.in/yaml.v2 v2.4.0
honnef.co/go/tools v0.0.1-2020.1.6
mvdan.cc/gofumpt v0.1.0
Expand Down
18 changes: 14 additions & 4 deletions go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ type LintersSettings struct {
Gofumpt GofumptSettings
ErrorLint ErrorLintSettings
Makezero MakezeroSettings
Revive ReviveSettings
Thelper ThelperSettings
Forbidigo ForbidigoSettings
Ifshort IfshortSettings
Expand Down Expand Up @@ -397,6 +398,23 @@ type MakezeroSettings struct {
Always bool
}

type ReviveSettings struct {
IgnoreGeneratedHeader bool `mapstructure:"ignore-generated-header"`
Confidence float64
Severity string
Rules []struct {
Name string
Arguments []interface{}
Severity string
}
ErrorCode int `mapstructure:"error-code"`
WarningCode int `mapstructure:"warning-code"`
Directives []struct {
Name string
Severity string
}
}

type ThelperSettings struct {
Test struct {
First bool `mapstructure:"first"`
Expand Down
187 changes: 187 additions & 0 deletions pkg/golinters/revive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package golinters

import (
"encoding/json"
"fmt"
"go/token"
"io/ioutil"
"strings"

"github.com/mgechev/dots"

"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/golinters/goanalysis"
"github.com/golangci/golangci-lint/pkg/lint/linter"
"github.com/golangci/golangci-lint/pkg/result"

reviveConfig "github.com/mgechev/revive/config"
"github.com/mgechev/revive/lint"
"golang.org/x/tools/go/analysis"
)
sspaink marked this conversation as resolved.
Show resolved Hide resolved

const (
reviveName = "revive"
)

// jsonObject defines a JSON object of an failure
type jsonObject struct {
Severity lint.Severity
lint.Failure `json:",inline"`
}

// NewNewRevive returns a new Revive linter.
func NewRevive(cfg *config.ReviveSettings) *goanalysis.Linter {
var (
issues []goanalysis.Issue
analyzer = &analysis.Analyzer{
Name: goanalysis.TheOnlyAnalyzerName,
Doc: goanalysis.TheOnlyanalyzerDoc,
}
)

return goanalysis.NewLinter(
reviveName,
"Fast, configurable, extensible, flexible, and beautiful linter for Go",
[]*analysis.Analyzer{analyzer},
nil,
).WithContextSetter(func(lintCtx *linter.Context) {
analyzer.Run = func(pass *analysis.Pass) (interface{}, error) {
var (
files = []string{}
)
sspaink marked this conversation as resolved.
Show resolved Hide resolved

for _, file := range pass.Files {
files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename)
}

conf, err := SetReviveConfig(cfg)
sspaink marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}

formatter, err := reviveConfig.GetFormatter("json")
if err != nil {
return nil, err
}

revive := lint.New(ioutil.ReadFile)

lintingRules, err := reviveConfig.GetLintingRules(conf)
if err != nil {
return nil, err
}

packages, err := dots.ResolvePackages(files, normalizeSplit([]string{}))
sspaink marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}

failures, err := revive.Lint(packages, lintingRules, *conf)
if err != nil {
return nil, err
}

formatChan := make(chan lint.Failure)
exitChan := make(chan bool)

var output string
go (func() {
output, _ = formatter.Format(formatChan, *conf)
exitChan <- true
})()

for f := range failures {
if f.Confidence < conf.Confidence {
continue
}

formatChan <- f
}

close(formatChan)
<-exitChan

var results []jsonObject
err = json.Unmarshal([]byte(output), &results)
if err != nil {
return nil, err
}

for i := range results {
issues = append(issues, goanalysis.NewIssue(&result.Issue{
Severity: string(results[i].Severity),
Text: fmt.Sprintf("%q", results[i].Failure.Failure),
Pos: token.Position{
Filename: results[i].Position.Start.Filename,
Line: results[i].Position.Start.Line,
Offset: results[i].Position.Start.Offset,
Column: results[i].Position.Start.Column,
},
LineRange: &result.Range{
From: results[i].Position.Start.Line,
To: results[i].Position.End.Line,
},
FromLinter: reviveName,
}, pass))
}
return nil, nil
}
ldez marked this conversation as resolved.
Show resolved Hide resolved
}).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
return issues
}).WithLoadMode(goanalysis.LoadModeSyntax)
}

func normalizeSplit(strs []string) []string {
res := []string{}
sspaink marked this conversation as resolved.
Show resolved Hide resolved
for _, s := range strs {
t := strings.Trim(s, " \t")
if len(t) > 0 {
res = append(res, t)
}
}
return res
}

func SetReviveConfig(cfg *config.ReviveSettings) (*lint.Config, error) {
sspaink marked this conversation as resolved.
Show resolved Hide resolved
// Get revive default configuration
conf, err := reviveConfig.GetConfig("")
if err != nil {
return nil, err
}

// Default is false
conf.IgnoreGeneratedHeader = cfg.IgnoreGeneratedHeader

if cfg.Severity != "" {
conf.Severity = lint.Severity(cfg.Severity)
}

if cfg.Confidence != 0 {
conf.Confidence = cfg.Confidence
}

// By default golangci-lint ignores missing doc comments, follow same convention by removing this default rule
// Relevant issue: https://github.com/golangci/golangci-lint/issues/456
delete(conf.Rules, "exported")

if len(cfg.Rules) != 0 {
// Clear default rules, only use rules defined in config
conf.Rules = map[string]lint.RuleConfig{}
sspaink marked this conversation as resolved.
Show resolved Hide resolved
}
for _, r := range cfg.Rules {
conf.Rules[r.Name] = lint.RuleConfig{Arguments: r.Arguments, Severity: lint.Severity(r.Severity)}
}

conf.ErrorCode = cfg.ErrorCode
conf.WarningCode = cfg.WarningCode

if len(cfg.Directives) != 0 {
// Clear default Directives, only use Directives defined in config
conf.Directives = map[string]lint.DirectiveConfig{}
sspaink marked this conversation as resolved.
Show resolved Hide resolved
}
for _, d := range cfg.Directives {
conf.Directives[d.Name] = lint.DirectiveConfig{Severity: lint.Severity(d.Severity)}
}

return conf, nil
}
4 changes: 4 additions & 0 deletions pkg/lint/lintersdb/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
var thelperCfg *config.ThelperSettings
var predeclaredCfg *config.PredeclaredSettings
var ifshortCfg *config.IfshortSettings
var reviveCfg *config.ReviveSettings
if m.cfg != nil {
govetCfg = &m.cfg.LintersSettings.Govet
testpackageCfg = &m.cfg.LintersSettings.Testpackage
Expand All @@ -104,6 +105,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
thelperCfg = &m.cfg.LintersSettings.Thelper
predeclaredCfg = &m.cfg.LintersSettings.Predeclared
ifshortCfg = &m.cfg.LintersSettings.Ifshort
reviveCfg = &m.cfg.LintersSettings.Revive
}
const megacheckName = "megacheck"
lcs := []*linter.Config{
Expand Down Expand Up @@ -352,6 +354,8 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
linter.NewConfig(golinters.NewPredeclared(predeclaredCfg)).
WithPresets(linter.PresetStyle).
WithURL("https://github.com/nishanths/predeclared"),
linter.NewConfig(golinters.NewRevive(reviveCfg)).
WithURL("https://github.com/mgechev/revive"),

// nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives
linter.NewConfig(golinters.NewNoLintLint()).
Expand Down
7 changes: 7 additions & 0 deletions test/testdata/configs/revive.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
linters-settings:
revive:
ignore-generated-header: true
severity: warning
rules:
- name: indent-error-flow
severity: warning
sspaink marked this conversation as resolved.
Show resolved Hide resolved
11 changes: 11 additions & 0 deletions test/testdata/revive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//args: -Erevive
//config_path: testdata/configs/revive.yml
package testdata

func testRevive(t string) error {
if t == "" {
return nil
} else { // ERROR "if block ends with a return statement, so drop this else and outdent its block"
return nil
}
}