dev: reformat code with gofumpt (#4500)

This commit is contained in:
Oleksandr Redko 2024-03-14 01:09:27 +02:00 committed by GitHub
parent 51a963fa5b
commit ea823733ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 146 additions and 76 deletions

View File

@ -12,10 +12,12 @@ func IsDir(filename string) bool {
return err == nil && fi.IsDir() return err == nil && fi.IsDir()
} }
var cachedWd string var (
var cachedWdError error cachedWd string
var getWdOnce sync.Once cachedWdError error
var useCache = true getWdOnce sync.Once
useCache = true
)
func UseWdCache(use bool) { func UseWdCache(use bool) {
useCache = use useCache = use

View File

@ -61,7 +61,8 @@ type runner struct {
} }
func newRunner(prefix string, logger logutils.Log, pkgCache *pkgcache.Cache, loadGuard *load.Guard, func newRunner(prefix string, logger logutils.Log, pkgCache *pkgcache.Cache, loadGuard *load.Guard,
loadMode LoadMode, sw *timeutils.Stopwatch) *runner { loadMode LoadMode, sw *timeutils.Stopwatch,
) *runner {
return &runner{ return &runner{
prefix: prefix, prefix: prefix,
log: logger, log: logger,
@ -80,7 +81,8 @@ func newRunner(prefix string, logger logutils.Log, pkgCache *pkgcache.Cache, loa
// singlechecker and the multi-analysis commands. // singlechecker and the multi-analysis commands.
// It returns the appropriate exit code. // It returns the appropriate exit code.
func (r *runner) run(analyzers []*analysis.Analyzer, initialPackages []*packages.Package) ([]Diagnostic, func (r *runner) run(analyzers []*analysis.Analyzer, initialPackages []*packages.Package) ([]Diagnostic,
[]error, map[*analysis.Pass]*packages.Package) { []error, map[*analysis.Pass]*packages.Package,
) {
debugf("Analyzing %d packages on load mode %s", len(initialPackages), r.loadMode) debugf("Analyzing %d packages on load mode %s", len(initialPackages), r.loadMode)
defer r.pkgCache.Trim() defer r.pkgCache.Trim()
@ -116,7 +118,8 @@ func (r *runner) markAllActions(a *analysis.Analyzer, pkg *packages.Package, mar
} }
func (r *runner) makeAction(a *analysis.Analyzer, pkg *packages.Package, func (r *runner) makeAction(a *analysis.Analyzer, pkg *packages.Package,
initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator) *action { initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator,
) *action {
k := actKey{a, pkg} k := actKey{a, pkg}
act, ok := actions[k] act, ok := actions[k]
if ok { if ok {
@ -150,7 +153,8 @@ func (r *runner) makeAction(a *analysis.Analyzer, pkg *packages.Package,
} }
func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *packages.Package, func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *packages.Package,
initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator) { initialPkgs map[*packages.Package]bool, actions map[actKey]*action, actAlloc *actionAllocator,
) {
// An analysis that consumes/produces facts // An analysis that consumes/produces facts
// must run on the package's dependencies too. // must run on the package's dependencies too.
if len(a.FactTypes) == 0 { if len(a.FactTypes) == 0 {
@ -175,7 +179,8 @@ func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *pac
//nolint:gocritic //nolint:gocritic
func (r *runner) prepareAnalysis(pkgs []*packages.Package, func (r *runner) prepareAnalysis(pkgs []*packages.Package,
analyzers []*analysis.Analyzer) (map[*packages.Package]bool, []*action, []*action) { analyzers []*analysis.Analyzer,
) (map[*packages.Package]bool, []*action, []*action) {
// Construct the action graph. // Construct the action graph.
// Each graph node (action) is one unit of analysis. // Each graph node (action) is one unit of analysis.

View File

@ -124,7 +124,8 @@ func getIssuesCacheKey(analyzers []*analysis.Analyzer) string {
} }
func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages.Package]bool, func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages.Package]bool,
issues []result.Issue, lintCtx *linter.Context, analyzers []*analysis.Analyzer) { issues []result.Issue, lintCtx *linter.Context, analyzers []*analysis.Analyzer,
) {
startedAt := time.Now() startedAt := time.Now()
perPkgIssues := map[*packages.Package][]result.Issue{} perPkgIssues := map[*packages.Package][]result.Issue{}
for ind := range issues { for ind := range issues {
@ -185,7 +186,8 @@ func saveIssuesToCache(allPkgs []*packages.Package, pkgsFromCache map[*packages.
//nolint:gocritic //nolint:gocritic
func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context, func loadIssuesFromCache(pkgs []*packages.Package, lintCtx *linter.Context,
analyzers []*analysis.Analyzer) ([]result.Issue, map[*packages.Package]bool) { analyzers []*analysis.Analyzer,
) ([]result.Issue, map[*packages.Package]bool) {
startedAt := time.Now() startedAt := time.Now()
lintResKey := getIssuesCacheKey(analyzers) lintResKey := getIssuesCacheKey(analyzers)

View File

@ -151,8 +151,10 @@ func NewLinter(needs Needs, excludes []string) (*Linter, error) {
}, nil }, nil
} }
var leadingSpacePattern = regexp.MustCompile(`^//(\s*)`) var (
var trailingBlankExplanation = regexp.MustCompile(`\s*(//\s*)?$`) leadingSpacePattern = regexp.MustCompile(`^//(\s*)`)
trailingBlankExplanation = regexp.MustCompile(`\s*(//\s*)?$`)
)
//nolint:funlen,gocyclo //nolint:funlen,gocyclo
func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) { func (l Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) {

View File

@ -11,7 +11,7 @@ import (
) )
func NewTestpackage(cfg *config.TestpackageSettings) *goanalysis.Linter { func NewTestpackage(cfg *config.TestpackageSettings) *goanalysis.Linter {
var a = testpackage.NewAnalyzer() a := testpackage.NewAnalyzer()
var settings map[string]map[string]any var settings map[string]map[string]any
if cfg != nil { if cfg != nil {

View File

@ -36,7 +36,8 @@ type ContextLoader struct {
} }
func NewContextLoader(cfg *config.Config, log logutils.Log, goenv *goutil.Env, func NewContextLoader(cfg *config.Config, log logutils.Log, goenv *goutil.Env,
lineCache *fsutils.LineCache, fileCache *fsutils.FileCache, pkgCache *pkgcache.Cache, loadGuard *load.Guard) *ContextLoader { lineCache *fsutils.LineCache, fileCache *fsutils.FileCache, pkgCache *pkgcache.Cache, loadGuard *load.Guard,
) *ContextLoader {
return &ContextLoader{ return &ContextLoader{
cfg: cfg, cfg: cfg,
log: log, log: log,

View File

@ -34,7 +34,8 @@ type Runner struct {
func NewRunner(log logutils.Log, cfg *config.Config, goenv *goutil.Env, func NewRunner(log logutils.Log, cfg *config.Config, goenv *goutil.Env,
lineCache *fsutils.LineCache, fileCache *fsutils.FileCache, lineCache *fsutils.LineCache, fileCache *fsutils.FileCache,
dbManager *lintersdb.Manager, lintCtx *linter.Context) (*Runner, error) { dbManager *lintersdb.Manager, lintCtx *linter.Context,
) (*Runner, error) {
// Beware that some processors need to add the path prefix when working with paths // Beware that some processors need to add the path prefix when working with paths
// because they get invoked before the path prefixer (exclude and severity rules) // because they get invoked before the path prefixer (exclude and severity rules)
// or process other paths (skip files). // or process other paths (skip files).
@ -129,7 +130,8 @@ func (r *Runner) Run(ctx context.Context, linters []*linter.Config) ([]result.Is
} }
func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context, func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context,
lc *linter.Config) (ret []result.Issue, err error) { lc *linter.Config,
) (ret []result.Issue, err error) {
defer func() { defer func() {
if panicData := recover(); panicData != nil { if panicData := recover(); panicData != nil {
if pe, ok := panicData.(*errorutil.PanicError); ok { if pe, ok := panicData.(*errorutil.PanicError); ok {

View File

@ -5,5 +5,7 @@ import (
colorable "github.com/mattn/go-colorable" colorable "github.com/mattn/go-colorable"
) )
var StdOut = color.Output // https://github.com/golangci/golangci-lint/issues/14 var (
var StdErr = colorable.NewColorableStderr() StdOut = color.Output // https://github.com/golangci/golangci-lint/issues/14
StdErr = colorable.NewColorableStderr()
)

View File

@ -13,7 +13,7 @@ import (
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
const defaultFileMode = 0644 const defaultFileMode = 0o644
type issuePrinter interface { type issuePrinter interface {
Print(issues []result.Issue) error Print(issues []result.Issue) error

View File

@ -31,27 +31,39 @@ var replacePatterns = []replacePattern{
{`^composites: (\S+) composite literal uses unkeyed fields$`, "composites: `${1}` composite literal uses unkeyed fields"}, {`^composites: (\S+) composite literal uses unkeyed fields$`, "composites: `${1}` composite literal uses unkeyed fields"},
// gosec // gosec
{`^(\S+): Blacklisted import (\S+): weak cryptographic primitive$`, {
"${1}: Blacklisted import `${2}`: weak cryptographic primitive"}, `^(\S+): Blacklisted import (\S+): weak cryptographic primitive$`,
"${1}: Blacklisted import `${2}`: weak cryptographic primitive",
},
{`^TLS InsecureSkipVerify set true.$`, "TLS `InsecureSkipVerify` set true."}, {`^TLS InsecureSkipVerify set true.$`, "TLS `InsecureSkipVerify` set true."},
// gosimple // gosimple
{`should replace loop with (.*)$`, "should replace loop with `${1}`"}, {`should replace loop with (.*)$`, "should replace loop with `${1}`"},
{`should use a simple channel send/receive instead of select with a single case`, {
"should use a simple channel send/receive instead of `select` with a single case"}, `should use a simple channel send/receive instead of select with a single case`,
{`should omit comparison to bool constant, can be simplified to (.+)$`, "should use a simple channel send/receive instead of `select` with a single case",
"should omit comparison to bool constant, can be simplified to `${1}`"}, },
{
`should omit comparison to bool constant, can be simplified to (.+)$`,
"should omit comparison to bool constant, can be simplified to `${1}`",
},
{`should write (.+) instead of (.+)$`, "should write `${1}` instead of `${2}`"}, {`should write (.+) instead of (.+)$`, "should write `${1}` instead of `${2}`"},
{`redundant return statement$`, "redundant `return` statement"}, {`redundant return statement$`, "redundant `return` statement"},
{`should replace this if statement with an unconditional strings.TrimPrefix`, {
"should replace this `if` statement with an unconditional `strings.TrimPrefix`"}, `should replace this if statement with an unconditional strings.TrimPrefix`,
"should replace this `if` statement with an unconditional `strings.TrimPrefix`",
},
// staticcheck // staticcheck
{`this value of (\S+) is never used$`, "this value of `${1}` is never used"}, {`this value of (\S+) is never used$`, "this value of `${1}` is never used"},
{`should use time.Since instead of time.Now\(\).Sub$`, {
"should use `time.Since` instead of `time.Now().Sub`"}, `should use time.Since instead of time.Now\(\).Sub$`,
{`should check returned error before deferring response.Close\(\)$`, "should use `time.Since` instead of `time.Now().Sub`",
"should check returned error before deferring `response.Close()`"}, },
{
`should check returned error before deferring response.Close\(\)$`,
"should check returned error before deferring `response.Close()`",
},
{`no value of type uint is less than 0$`, "no value of type `uint` is less than `0`"}, {`no value of type uint is less than 0$`, "no value of type `uint` is less than `0`"},
// unused // unused
@ -59,26 +71,40 @@ var replacePatterns = []replacePattern{
// typecheck // typecheck
{`^unknown field (\S+) in struct literal$`, "unknown field `${1}` in struct literal"}, {`^unknown field (\S+) in struct literal$`, "unknown field `${1}` in struct literal"},
{`^invalid operation: (\S+) \(variable of type (\S+)\) has no field or method (\S+)$`, {
"invalid operation: `${1}` (variable of type `${2}`) has no field or method `${3}`"}, `^invalid operation: (\S+) \(variable of type (\S+)\) has no field or method (\S+)$`,
"invalid operation: `${1}` (variable of type `${2}`) has no field or method `${3}`",
},
{`^undeclared name: (\S+)$`, "undeclared name: `${1}`"}, {`^undeclared name: (\S+)$`, "undeclared name: `${1}`"},
{`^cannot use addr \(variable of type (\S+)\) as (\S+) value in argument to (\S+)$`, {
"cannot use addr (variable of type `${1}`) as `${2}` value in argument to `${3}`"}, `^cannot use addr \(variable of type (\S+)\) as (\S+) value in argument to (\S+)$`,
"cannot use addr (variable of type `${1}`) as `${2}` value in argument to `${3}`",
},
{`^other declaration of (\S+)$`, "other declaration of `${1}`"}, {`^other declaration of (\S+)$`, "other declaration of `${1}`"},
{`^(\S+) redeclared in this block$`, "`${1}` redeclared in this block"}, {`^(\S+) redeclared in this block$`, "`${1}` redeclared in this block"},
// golint // golint
{`^exported (type|method|function|var|const) (\S+) should have comment or be unexported$`, {
"exported ${1} `${2}` should have comment or be unexported"}, `^exported (type|method|function|var|const) (\S+) should have comment or be unexported$`,
{`^comment on exported (type|method|function|var|const) (\S+) should be of the form "(\S+) ..."$`, "exported ${1} `${2}` should have comment or be unexported",
"comment on exported ${1} `${2}` should be of the form `${3} ...`"}, },
{
`^comment on exported (type|method|function|var|const) (\S+) should be of the form "(\S+) ..."$`,
"comment on exported ${1} `${2}` should be of the form `${3} ...`",
},
{`^should replace (.+) with (.+)$`, "should replace `${1}` with `${2}`"}, {`^should replace (.+) with (.+)$`, "should replace `${1}` with `${2}`"},
{`^if block ends with a return statement, so drop this else and outdent its block$`, {
"`if` block ends with a `return` statement, so drop this `else` and outdent its block"}, `^if block ends with a return statement, so drop this else and outdent its block$`,
{`^(struct field|var|range var|const|type|(?:func|method|interface method) (?:parameter|result)) (\S+) should be (\S+)$`, "`if` block ends with a `return` statement, so drop this `else` and outdent its block",
"${1} `${2}` should be `${3}`"}, },
{`^don't use underscores in Go names; var (\S+) should be (\S+)$`, {
"don't use underscores in Go names; var `${1}` should be `${2}`"}, `^(struct field|var|range var|const|type|(?:func|method|interface method) (?:parameter|result)) (\S+) should be (\S+)$`,
"${1} `${2}` should be `${3}`",
},
{
`^don't use underscores in Go names; var (\S+) should be (\S+)$`,
"don't use underscores in Go names; var `${1}` should be `${2}`",
},
} }
type IdentifierMarker struct { type IdentifierMarker struct {

View File

@ -13,39 +13,61 @@ func TestIdentifierMarker(t *testing.T) {
//nolint:lll //nolint:lll
cases := []struct{ in, out string }{ cases := []struct{ in, out string }{
{"unknown field Address in struct literal", "unknown field `Address` in struct literal"}, {"unknown field Address in struct literal", "unknown field `Address` in struct literal"},
{"invalid operation: res (variable of type github.com/iotexproject/iotex-core/explorer/idl/explorer.GetBlkOrActResponse) has no field or method Address", {
"invalid operation: `res` (variable of type `github.com/iotexproject/iotex-core/explorer/idl/explorer.GetBlkOrActResponse`) has no field or method `Address`"}, "invalid operation: res (variable of type github.com/iotexproject/iotex-core/explorer/idl/explorer.GetBlkOrActResponse) has no field or method Address",
{"should use a simple channel send/receive instead of select with a single case", "invalid operation: `res` (variable of type `github.com/iotexproject/iotex-core/explorer/idl/explorer.GetBlkOrActResponse`) has no field or method `Address`",
"should use a simple channel send/receive instead of `select` with a single case"}, },
{
"should use a simple channel send/receive instead of select with a single case",
"should use a simple channel send/receive instead of `select` with a single case",
},
{"var testInputs is unused", "var `testInputs` is unused"}, {"var testInputs is unused", "var `testInputs` is unused"},
{"undeclared name: stateIDLabel", "undeclared name: `stateIDLabel`"}, {"undeclared name: stateIDLabel", "undeclared name: `stateIDLabel`"},
{"exported type Metrics should have comment or be unexported", {
"exported type `Metrics` should have comment or be unexported"}, "exported type Metrics should have comment or be unexported",
{`comment on exported function NewMetrics should be of the form "NewMetrics ..."`, "exported type `Metrics` should have comment or be unexported",
"comment on exported function `NewMetrics` should be of the form `NewMetrics ...`"}, },
{"cannot use addr (variable of type string) as github.com/iotexproject/iotex-core/pkg/keypair.PublicKey value in argument to action.FakeSeal", {
"cannot use addr (variable of type `string`) as `github.com/iotexproject/iotex-core/pkg/keypair.PublicKey` value in argument to `action.FakeSeal`"}, `comment on exported function NewMetrics should be of the form "NewMetrics ..."`,
"comment on exported function `NewMetrics` should be of the form `NewMetrics ...`",
},
{
"cannot use addr (variable of type string) as github.com/iotexproject/iotex-core/pkg/keypair.PublicKey value in argument to action.FakeSeal",
"cannot use addr (variable of type `string`) as `github.com/iotexproject/iotex-core/pkg/keypair.PublicKey` value in argument to `action.FakeSeal`",
},
{"other declaration of out", "other declaration of `out`"}, {"other declaration of out", "other declaration of `out`"},
{"should check returned error before deferring response.Close()", "should check returned error before deferring `response.Close()`"}, {"should check returned error before deferring response.Close()", "should check returned error before deferring `response.Close()`"},
{"should use time.Since instead of time.Now().Sub", "should use `time.Since` instead of `time.Now().Sub`"}, {"should use time.Since instead of time.Now().Sub", "should use `time.Since` instead of `time.Now().Sub`"},
{"TestFibZeroCount redeclared in this block", "`TestFibZeroCount` redeclared in this block"}, {"TestFibZeroCount redeclared in this block", "`TestFibZeroCount` redeclared in this block"},
{"should replace i += 1 with i++", "should replace `i += 1` with `i++`"}, {"should replace i += 1 with i++", "should replace `i += 1` with `i++`"},
{"createEntry - result err is always nil", "`createEntry` - result `err` is always `nil`"}, {"createEntry - result err is always nil", "`createEntry` - result `err` is always `nil`"},
{"should omit comparison to bool constant, can be simplified to !projectIntegration.Model.Storage", {
"should omit comparison to bool constant, can be simplified to `!projectIntegration.Model.Storage`"}, "should omit comparison to bool constant, can be simplified to !projectIntegration.Model.Storage",
{"if block ends with a return statement, so drop this else and outdent its block", "should omit comparison to bool constant, can be simplified to `!projectIntegration.Model.Storage`",
"`if` block ends with a `return` statement, so drop this `else` and outdent its block"}, },
{"should write pupData := ms.m[pupID] instead of pupData, _ := ms.m[pupID]", {
"should write `pupData := ms.m[pupID]` instead of `pupData, _ := ms.m[pupID]`"}, "if block ends with a return statement, so drop this else and outdent its block",
"`if` block ends with a `return` statement, so drop this `else` and outdent its block",
},
{
"should write pupData := ms.m[pupID] instead of pupData, _ := ms.m[pupID]",
"should write `pupData := ms.m[pupID]` instead of `pupData, _ := ms.m[pupID]`",
},
{"no value of type uint is less than 0", "no value of type `uint` is less than `0`"}, {"no value of type uint is less than 0", "no value of type `uint` is less than `0`"},
{"redundant return statement", "redundant `return` statement"}, {"redundant return statement", "redundant `return` statement"},
{"struct field Id should be ID", "struct field `Id` should be `ID`"}, {"struct field Id should be ID", "struct field `Id` should be `ID`"},
{"don't use underscores in Go names; var Go_lint should be GoLint", {
"don't use underscores in Go names; var `Go_lint` should be `GoLint`"}, "don't use underscores in Go names; var Go_lint should be GoLint",
{"G501: Blacklisted import crypto/md5: weak cryptographic primitive", "don't use underscores in Go names; var `Go_lint` should be `GoLint`",
"G501: Blacklisted import `crypto/md5`: weak cryptographic primitive"}, },
{"S1017: should replace this if statement with an unconditional strings.TrimPrefix", {
"S1017: should replace this `if` statement with an unconditional `strings.TrimPrefix`"}, "G501: Blacklisted import crypto/md5: weak cryptographic primitive",
"G501: Blacklisted import `crypto/md5`: weak cryptographic primitive",
},
{
"S1017: should replace this if statement with an unconditional strings.TrimPrefix",
"S1017: should replace this `if` statement with an unconditional `strings.TrimPrefix`",
},
} }
p := NewIdentifierMarker() p := NewIdentifierMarker()

View File

@ -5,8 +5,10 @@ import (
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
type linterToCountMap map[string]int type (
type fileToLinterToCountMap map[string]linterToCountMap linterToCountMap map[string]int
fileToLinterToCountMap map[string]linterToCountMap
)
type MaxPerFileFromLinter struct { type MaxPerFileFromLinter struct {
flc fileToLinterToCountMap flc fileToLinterToCountMap

View File

@ -18,8 +18,10 @@ import (
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
var nolintDebugf = logutils.Debug(logutils.DebugKeyNolint) var (
var nolintRe = regexp.MustCompile(`^nolint( |:|$)`) nolintDebugf = logutils.Debug(logutils.DebugKeyNolint)
nolintRe = regexp.MustCompile(`^nolint( |:|$)`)
)
type ignoredRange struct { type ignoredRange struct {
linters []string linters []string

View File

@ -192,7 +192,7 @@ func TestNolintAliases(t *testing.T) {
} }
func TestIgnoredRangeMatches(t *testing.T) { func TestIgnoredRangeMatches(t *testing.T) {
var testcases = []struct { testcases := []struct {
doc string doc string
issue result.Issue issue result.Issue
linters []string linters []string

View File

@ -5,8 +5,10 @@ import (
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
type lineToCount map[int]int type (
type fileToLineToCount map[string]lineToCount lineToCount map[int]int
fileToLineToCount map[string]lineToCount
)
type UniqByLine struct { type UniqByLine struct {
flc fileToLineToCount flc fileToLineToCount

View File

@ -256,7 +256,7 @@ func getLintersSettingSections(node, nextNode *yaml.Node) (string, error) {
return "", err return "", err
} }
var lintersDesc = make(map[string]string) lintersDesc := make(map[string]string)
for _, lc := range linters { for _, lc := range linters {
if lc.Internal { if lc.Internal {
continue continue