dev: replace raw loops with funcs from slices and maps (#4299)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Oleksandr Redko 2024-01-04 23:43:50 +02:00 committed by GitHub
parent d23c35470b
commit 521a6763ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 44 additions and 70 deletions

2
go.mod
View File

@ -122,7 +122,7 @@ require (
gitlab.com/bosi/decorder v0.4.1 gitlab.com/bosi/decorder v0.4.1
go-simpler.org/musttag v0.8.0 go-simpler.org/musttag v0.8.0
go-simpler.org/sloglint v0.4.0 go-simpler.org/sloglint v0.4.0
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc
golang.org/x/tools v0.16.1 golang.org/x/tools v0.16.1
gopkg.in/yaml.v3 v3.0.1 gopkg.in/yaml.v3 v3.0.1
honnef.co/go/tools v0.4.6 honnef.co/go/tools v0.4.6

4
go.sum generated
View File

@ -625,8 +625,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea h1:vLCWI/yYrdEHyN2JzIzPO3aaQJHQdp89IZBA/+azVC4= golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc h1:ao2WRsKSzW6KuUY9IWPwWahcHCgR0s52IfwutMfEbdM=
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= golang.org/x/exp v0.0.0-20240103183307-be819d1f06fc/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20231219180239-dc181d75b848 h1:UhRVJ0i7bF9n/Hd8YjW3eKjlPVBHzbQdxrBgjbSKl64= golang.org/x/exp/typeparams v0.0.0-20231219180239-dc181d75b848 h1:UhRVJ0i7bF9n/Hd8YjW3eKjlPVBHzbQdxrBgjbSKl64=

View File

@ -17,6 +17,7 @@ import (
"sort" "sort"
"sync" "sync"
"golang.org/x/exp/maps"
"golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages" "golang.org/x/tools/go/packages"
@ -159,10 +160,7 @@ func (r *runner) buildActionFactDeps(act *action, a *analysis.Analyzer, pkg *pac
act.objectFacts = make(map[objectFactKey]analysis.Fact) act.objectFacts = make(map[objectFactKey]analysis.Fact)
act.packageFacts = make(map[packageFactKey]analysis.Fact) act.packageFacts = make(map[packageFactKey]analysis.Fact)
paths := make([]string, 0, len(pkg.Imports)) paths := maps.Keys(pkg.Imports)
for path := range pkg.Imports {
paths = append(paths, path)
}
sort.Strings(paths) // for determinism sort.Strings(paths) // for determinism
for _, path := range paths { for _, path := range paths {
dep := r.makeAction(a, pkg.Imports[path], initialPkgs, actions, actAlloc) dep := r.makeAction(a, pkg.Imports[path], initialPkgs, actions, actAlloc)
@ -212,10 +210,7 @@ func (r *runner) prepareAnalysis(pkgs []*packages.Package,
} }
} }
allActions := make([]*action, 0, len(actions)) allActions := maps.Values(actions)
for _, act := range actions {
allActions = append(allActions, act)
}
debugf("Built %d actions", len(actions)) debugf("Built %d actions", len(actions))

View File

@ -14,6 +14,7 @@ import (
"github.com/go-critic/go-critic/checkers" "github.com/go-critic/go-critic/checkers"
gocriticlinter "github.com/go-critic/go-critic/linter" gocriticlinter "github.com/go-critic/go-critic/linter"
"golang.org/x/exp/maps"
"golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/config"
@ -219,10 +220,7 @@ func (w *goCriticWrapper) configureCheckerInfo(info *gocriticlinter.CheckerInfo,
info.Name, k) info.Name, k)
} }
var supportedKeys []string supportedKeys := maps.Keys(info.Params)
for sk := range info.Params {
supportedKeys = append(supportedKeys, sk)
}
sort.Strings(supportedKeys) sort.Strings(supportedKeys)
return fmt.Errorf("checker %s config param %s doesn't exist, all existing: %s", return fmt.Errorf("checker %s config param %s doesn't exist, all existing: %s",
@ -311,11 +309,7 @@ func (s *goCriticSettingsWrapper) checkerTagsDebugf() {
tagToCheckers := s.buildTagToCheckersMap() tagToCheckers := s.buildTagToCheckersMap()
allTags := make([]string, 0, len(tagToCheckers)) allTags := maps.Keys(tagToCheckers)
for tag := range tagToCheckers {
allTags = append(allTags, tag)
}
sort.Strings(allTags) sort.Strings(allTags)
goCriticDebugf("All gocritic existing tags and checks:") goCriticDebugf("All gocritic existing tags and checks:")
@ -609,12 +603,7 @@ func intersectStringSlice(s1, s2 []string) []string {
} }
func sprintAllowedCheckerNames(allowedNames map[string]bool) string { func sprintAllowedCheckerNames(allowedNames map[string]bool) string {
namesSlice := make([]string, 0, len(allowedNames)) namesSlice := maps.Keys(allowedNames)
for name := range allowedNames {
namesSlice = append(namesSlice, name)
}
return sprintStrings(namesSlice) return sprintStrings(namesSlice)
} }

View File

@ -1,9 +1,9 @@
package golinters package golinters
import ( import (
"sort"
"testing" "testing"
"golang.org/x/exp/slices"
"golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/asmdecl" "golang.org/x/tools/go/analysis/passes/asmdecl"
"golang.org/x/tools/go/analysis/passes/assign" "golang.org/x/tools/go/analysis/passes/assign"
@ -18,39 +18,41 @@ import (
func TestGovet(t *testing.T) { func TestGovet(t *testing.T) {
// Checking that every default analyzer is in "all analyzers" list. // Checking that every default analyzer is in "all analyzers" list.
var checkList []*analysis.Analyzer checkList := append([]*analysis.Analyzer{}, defaultAnalyzers...)
checkList = append(checkList, defaultAnalyzers...)
checkList = append(checkList, shadow.Analyzer) // special case, used in analyzersFromConfig checkList = append(checkList, shadow.Analyzer) // special case, used in analyzersFromConfig
for _, defaultAnalyzer := range checkList { for _, defaultAnalyzer := range checkList {
found := false found := slices.ContainsFunc(allAnalyzers, func(a *analysis.Analyzer) bool {
for _, a := range allAnalyzers { return a.Name == defaultAnalyzer.Name
if a.Name == defaultAnalyzer.Name { })
found = true
break
}
}
if !found { if !found {
t.Errorf("%s is not in allAnalyzers", defaultAnalyzer.Name) t.Errorf("%s is not in allAnalyzers", defaultAnalyzer.Name)
} }
} }
} }
type sortedAnalyzers []*analysis.Analyzer func sortAnalyzers(a, b *analysis.Analyzer) int {
if a.Name < b.Name {
return -1
}
func (p sortedAnalyzers) Len() int { return len(p) } if a.Name > b.Name {
func (p sortedAnalyzers) Less(i, j int) bool { return p[i].Name < p[j].Name } return 1
func (p sortedAnalyzers) Swap(i, j int) { p[i].Name, p[j].Name = p[j].Name, p[i].Name } }
return 0
}
func TestGovetSorted(t *testing.T) { func TestGovetSorted(t *testing.T) {
// Keeping analyzers sorted so their order match the import order. // Keeping analyzers sorted so their order match the import order.
t.Run("All", func(t *testing.T) { t.Run("All", func(t *testing.T) {
if !sort.IsSorted(sortedAnalyzers(allAnalyzers)) { if !slices.IsSortedFunc(allAnalyzers, sortAnalyzers) {
t.Error("please keep all analyzers list sorted by name") t.Error("please keep all analyzers list sorted by name")
} }
}) })
t.Run("Default", func(t *testing.T) { t.Run("Default", func(t *testing.T) {
if !sort.IsSorted(sortedAnalyzers(defaultAnalyzers)) { if !slices.IsSortedFunc(defaultAnalyzers, sortAnalyzers) {
t.Error("please keep default analyzers list sorted by name") t.Error("please keep default analyzers list sorted by name")
} }
}) })

View File

@ -4,6 +4,7 @@ import (
"strings" "strings"
"github.com/kulti/thelper/pkg/analyzer" "github.com/kulti/thelper/pkg/analyzer"
"golang.org/x/exp/maps"
"golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/config"
@ -42,10 +43,7 @@ func NewThelper(cfg *config.ThelperSettings) *goanalysis.Linter {
linterLogger.Fatalf("thelper: at least one option must be enabled") linterLogger.Fatalf("thelper: at least one option must be enabled")
} }
var args []string args := maps.Keys(opts)
for k := range opts {
args = append(args, k)
}
cfgMap := map[string]map[string]any{ cfgMap := map[string]map[string]any{
a.Name: { a.Name: {

View File

@ -4,6 +4,8 @@ import (
"os" "os"
"sort" "sort"
"golang.org/x/exp/maps"
"github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/golinters/goanalysis" "github.com/golangci/golangci-lint/pkg/golinters/goanalysis"
"github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/linter"
@ -115,10 +117,7 @@ func (es EnabledSet) GetOptimizedLinters() ([]*linter.Config, error) {
es.verbosePrintLintersStatus(resultLintersSet) es.verbosePrintLintersStatus(resultLintersSet)
es.combineGoAnalysisLinters(resultLintersSet) es.combineGoAnalysisLinters(resultLintersSet)
var resultLinters []*linter.Config resultLinters := maps.Values(resultLintersSet)
for _, lc := range resultLintersSet {
resultLinters = append(resultLinters, lc)
}
// Make order of execution of linters (go/analysis metalinter and unused) stable. // Make order of execution of linters (go/analysis metalinter and unused) stable.
sort.Slice(resultLinters, func(i, j int) bool { sort.Slice(resultLinters, func(i, j int) bool {
@ -185,10 +184,7 @@ func (es EnabledSet) combineGoAnalysisLinters(linters map[string]*linter.Config)
ml := goanalysis.NewMetaLinter(goanalysisLinters) ml := goanalysis.NewMetaLinter(goanalysisLinters)
var presets []string presets := maps.Keys(goanalysisPresets)
for p := range goanalysisPresets {
presets = append(presets, p)
}
mlConfig := &linter.Config{ mlConfig := &linter.Config{
Linter: ml, Linter: ml,

View File

@ -7,6 +7,7 @@ import (
"sort" "sort"
"github.com/go-xmlfmt/xmlfmt" "github.com/go-xmlfmt/xmlfmt"
"golang.org/x/exp/maps"
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
@ -74,10 +75,7 @@ func (p Checkstyle) Print(issues []result.Issue) error {
file.Errors = append(file.Errors, newError) file.Errors = append(file.Errors, newError)
} }
out.Files = make([]*checkstyleFile, 0, len(files)) out.Files = maps.Values(files)
for _, file := range files {
out.Files = append(out.Files, file)
}
sort.Slice(out.Files, func(i, j int) bool { sort.Slice(out.Files, func(i, j int) bool {
return out.Files[i].Name < out.Files[j].Name return out.Files[i].Name < out.Files[j].Name

View File

@ -7,6 +7,8 @@ import (
"sort" "sort"
"strings" "strings"
"golang.org/x/exp/maps"
"github.com/golangci/golangci-lint/pkg/result" "github.com/golangci/golangci-lint/pkg/result"
) )
@ -71,9 +73,7 @@ func (p JunitXML) Print(issues []result.Issue) error {
} }
var res testSuitesXML var res testSuitesXML
for _, val := range suites { res.TestSuites = maps.Values(suites)
res.TestSuites = append(res.TestSuites, val)
}
sort.Slice(res.TestSuites, func(i, j int) bool { sort.Slice(res.TestSuites, func(i, j int) bool {
return res.TestSuites[i].Suite < res.TestSuites[j].Suite return res.TestSuites[i].Suite < res.TestSuites[j].Suite

View File

@ -9,6 +9,8 @@ import (
"sort" "sort"
"strings" "strings"
"golang.org/x/exp/maps"
"github.com/golangci/golangci-lint/pkg/golinters" "github.com/golangci/golangci-lint/pkg/golinters"
"github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/linter"
"github.com/golangci/golangci-lint/pkg/lint/lintersdb" "github.com/golangci/golangci-lint/pkg/lint/lintersdb"
@ -289,10 +291,7 @@ func (p *Nolint) Finish() {
return return
} }
unknownLinters := make([]string, 0, len(p.unknownLintersSet)) unknownLinters := maps.Keys(p.unknownLintersSet)
for name := range p.unknownLintersSet {
unknownLinters = append(unknownLinters, name)
}
sort.Strings(unknownLinters) sort.Strings(unknownLinters)
p.log.Warnf("Found unknown linters in //nolint directives: %s", strings.Join(unknownLinters, ", ")) p.log.Warnf("Found unknown linters in //nolint directives: %s", strings.Join(unknownLinters, ", "))

View File

@ -16,6 +16,7 @@ import (
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"golang.org/x/exp/maps"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/golangci/golangci-lint/internal/renameio" "github.com/golangci/golangci-lint/internal/renameio"
@ -360,11 +361,7 @@ func getThanksList() string {
} }
} }
var authors []string authors := maps.Keys(addedAuthors)
for author := range addedAuthors {
authors = append(authors, author)
}
sort.Slice(authors, func(i, j int) bool { sort.Slice(authors, func(i, j int) bool {
return strings.ToLower(authors[i]) < strings.ToLower(authors[j]) return strings.ToLower(authors[i]) < strings.ToLower(authors[j])
}) })