Skip to content

Commit 269956c

Browse files
committed
[9.4] .golangci.yml: enable the modernize linter
Enable the modernize linter from golangci-lint's suite. It flags outdated Go syntax and rewrites it to modern equivalents: min/max builtins, range-over-int loops, slices/maps helpers, any, t.Context() in tests, fmt.Appendf, strings.CutPrefix, and more. Keeping it enabled stops outdated patterns from re-entering the codebase, which matters more now that much code is produced by AI agents trained on older Go, and it often yields simpler, more efficient code. The omitzero analyzer is disabled: it rewrites ,omitempty struct tags to ,omitzero, which changes JSON marshaling semantics and is not a mechanical, behavior-preserving fix. The loop also runs `go fix -inline`, which applies //go:fix inline directives. modernize marks its own pointer helpers with the directive, and dependencies/stdlib carry it on deprecated APIs, so this pulls in mechanical migrations such as io/ioutil -> io and reflect.Ptr -> reflect.Pointer. `go fix` inlines the call sites but never deletes the now-dead helper declarations; a follow-up commit removes those. Every Go change here is a linter/`go fix` auto-fix, restricted to the files owned by @elastic/elastic-agent-data-plane; the rest of the repository is modernized in a stacked follow-up PR so each team reviews only its own code. The .golangci.yml change is made by hand. The Go changes (except for some manual changes that were highlighted in the review) are then fully reproducible by running this with bash from the repository root: set -euo pipefail OWNER="@elastic/elastic-agent-data-plane" export CGO_ENABLED=1 MAX_PASSES=10 modernize() { golangci-lint run --enable-only modernize \ --max-issues-per-linter 0 --max-same-issues 0 --timeout=90m --fix ./... } for pass in $(seq "$MAX_PASSES"); do echo ">>> pass $pass: fmt" before="$(git diff | git hash-object --stdin)" golangci-lint fmt ./... echo ">>> pass $pass: modernize --fix" if modernize; then :; fi echo ">>> pass $pass: go fix -inline" if go fix -inline ./...; then :; fi echo ">>> pass $pass done: $(git diff --name-only | wc -l) files changed" [ "$before" = "$(git diff | git hash-object --stdin)" ] && { echo ">>> fixpoint at pass $pass"; break; } done golangci-lint fmt ./... changed="$(mktemp)" keep="$(mktemp)" trap 'rm -f "$changed" "$keep"' EXIT git diff --name-only -- '*.go' | sort -u >"$changed" git diff --name-only -- '*.go' | xargs -r codeowners -o "$OWNER" \ | awk '{print $1}' | sort -u >"$keep" comm -23 "$changed" "$keep" | tr '\n' '\0' | xargs -0 -r git checkout -- echo "PR1 data-plane .go files: $(git diff --name-only -- '*.go' | wc -l)"
1 parent d325362 commit 269956c

599 files changed

Lines changed: 3254 additions & 3582 deletions

File tree

Some content is hidden

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

dev-tools/cmd/license/license_generate.go

Lines changed: 4 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dev-tools/cmd/module_include_list/module_include_list.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ func usageFlag() {
173173
flag.PrintDefaults()
174174
}
175175

176-
var Template = template.Must(template.New("normalizations").Funcs(map[string]interface{}{
176+
var Template = template.Must(template.New("normalizations").Funcs(map[string]any{
177177
"trim": strings.TrimSpace,
178178
}).Parse(`
179179
{{ .License | trim }}

dev-tools/cmd/update_go/update_go_version.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ package main
2020
import (
2121
"flag"
2222
"fmt"
23-
"io/ioutil"
2423
"os"
2524
"strings"
2625
)
@@ -51,7 +50,7 @@ func main() {
5150
}
5251

5352
func getGoVersion() string {
54-
version, err := ioutil.ReadFile(".go-version")
53+
version, err := os.ReadFile(".go-version")
5554
checkErr(err)
5655
return strings.TrimRight(string(version), "\r\n")
5756
}
@@ -65,10 +64,10 @@ func checkErr(err error) {
6564
func updateGoVersion(oldVersion, newVersion string) {
6665
for _, file := range files {
6766
fmt.Printf("Updating Go version from %s to %s in %s\n", oldVersion, newVersion, file)
68-
content, err := ioutil.ReadFile(file)
67+
content, err := os.ReadFile(file)
6968
checkErr(err)
7069
updatedContent := strings.ReplaceAll(string(content), oldVersion, newVersion)
71-
err = ioutil.WriteFile(file, []byte(updatedContent), 0644)
70+
err = os.WriteFile(file, []byte(updatedContent), 0644)
7271
checkErr(err)
7372
}
7473
}

dev-tools/mage/build.go

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,11 @@ import (
2222
"fmt"
2323
"go/build"
2424
"log"
25+
"maps"
2526
"os"
2627
"path/filepath"
2728
"regexp"
29+
"slices"
2830
"strings"
2931

3032
"github.com/josephspurrier/goversioninfo"
@@ -114,9 +116,7 @@ func DefaultBuildArgs() BuildArgs {
114116
args.ExtraFlags = append(args.ExtraFlags, "-tags="+tag)
115117
}
116118
args.CGO = args.CGO || FIPSConfig.Compile.CGO
117-
for varName, value := range FIPSConfig.Compile.Env {
118-
args.Env[varName] = value
119-
}
119+
maps.Copy(args.Env, FIPSConfig.Compile.Env)
120120
}
121121

122122
return args
@@ -138,12 +138,7 @@ func positionIndependentCodeSupported() bool {
138138
}
139139

140140
func oneOf(value string, lst ...string) bool {
141-
for _, other := range lst {
142-
if other == value {
143-
return true
144-
}
145-
}
146-
return false
141+
return slices.Contains(lst, value)
147142
}
148143

149144
// DefaultGolangCrossBuildArgs returns the default BuildArgs for use in

dev-tools/mage/check.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import (
2222
"bytes"
2323
"encoding/json"
2424
"fmt"
25-
"io/ioutil"
25+
2626
"log"
2727
"os"
2828
"os/exec"
@@ -230,7 +230,7 @@ func CheckDashboardsFormat() error {
230230

231231
hasErrors := false
232232
for _, file := range dashboardFiles {
233-
d, err := ioutil.ReadFile(file)
233+
d, err := os.ReadFile(file)
234234
if err != nil {
235235
return fmt.Errorf("failed to read dashboard file %s: %w", file, err)
236236
}

dev-tools/mage/common.go

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import (
3333
"fmt"
3434
"io"
3535
"log"
36+
"maps"
3637
"net/http"
3738
"os"
3839
"os/exec"
@@ -54,13 +55,13 @@ import (
5455
)
5556

5657
// Expand expands the given Go text/template string.
57-
func Expand(in string, args ...map[string]interface{}) (string, error) {
58+
func Expand(in string, args ...map[string]any) (string, error) {
5859
return expandTemplate("inline", in, FuncMap, EnvMap(args...))
5960
}
6061

6162
// MustExpand expands the given Go text/template string. It panics if there is
6263
// an error.
63-
func MustExpand(in string, args ...map[string]interface{}) string {
64+
func MustExpand(in string, args ...map[string]any) string {
6465
out, err := Expand(in, args...)
6566
if err != nil {
6667
panic(err)
@@ -70,19 +71,19 @@ func MustExpand(in string, args ...map[string]interface{}) string {
7071

7172
// ExpandFile expands the Go text/template read from src and writes the output
7273
// to dst.
73-
func ExpandFile(src, dst string, args ...map[string]interface{}) error {
74+
func ExpandFile(src, dst string, args ...map[string]any) error {
7475
return expandFile(src, dst, EnvMap(args...))
7576
}
7677

7778
// MustExpandFile expands the Go text/template read from src and writes the
7879
// output to dst. It panics if there is an error.
79-
func MustExpandFile(src, dst string, args ...map[string]interface{}) {
80+
func MustExpandFile(src, dst string, args ...map[string]any) {
8081
if err := ExpandFile(src, dst, args...); err != nil {
8182
panic(err)
8283
}
8384
}
8485

85-
func expandTemplate(name, tmpl string, funcs template.FuncMap, args ...map[string]interface{}) (string, error) {
86+
func expandTemplate(name, tmpl string, funcs template.FuncMap, args ...map[string]any) (string, error) {
8687
t := template.New(name).Option("missingkey=error")
8788
if len(funcs) > 0 {
8889
t = t.Funcs(funcs)
@@ -107,24 +108,22 @@ func expandTemplate(name, tmpl string, funcs template.FuncMap, args ...map[strin
107108
return buf.String(), nil
108109
}
109110

110-
func joinMaps(args ...map[string]interface{}) map[string]interface{} {
111+
func joinMaps(args ...map[string]any) map[string]any {
111112
switch len(args) {
112113
case 0:
113114
return nil
114115
case 1:
115116
return args[0]
116117
}
117118

118-
out := map[string]interface{}{}
119+
out := map[string]any{}
119120
for _, m := range args {
120-
for k, v := range m {
121-
out[k] = v
122-
}
121+
maps.Copy(out, m)
123122
}
124123
return out
125124
}
126125

127-
func expandFile(src, dst string, args ...map[string]interface{}) error {
126+
func expandFile(src, dst string, args ...map[string]any) error {
128127
tmplData, err := os.ReadFile(src)
129128
if err != nil {
130129
return fmt.Errorf("failed reading from template %v: %w", src, err)
@@ -662,7 +661,7 @@ func numParallel() int {
662661
// ParallelCtx runs the given functions in parallel with an upper limit set
663662
// based on GOMAXPROCS. The provided ctx is passed to the functions (if they
664663
// accept it as a param).
665-
func ParallelCtx(ctx context.Context, fns ...interface{}) {
664+
func ParallelCtx(ctx context.Context, fns ...any) {
666665
var fnWrappers []func(context.Context) error
667666
for _, f := range fns {
668667
fnWrapper := funcTypeWrap(f)
@@ -707,12 +706,12 @@ func ParallelCtx(ctx context.Context, fns ...interface{}) {
707706

708707
// Parallel runs the given functions in parallel with an upper limit set based
709708
// on GOMAXPROCS.
710-
func Parallel(fns ...interface{}) {
709+
func Parallel(fns ...any) {
711710
ParallelCtx(context.TODO(), fns...)
712711
}
713712

714713
// funcTypeWrap wraps a valid FuncType to FuncContextError
715-
func funcTypeWrap(fn interface{}) func(context.Context) error {
714+
func funcTypeWrap(fn any) func(context.Context) error {
716715
switch f := fn.(type) {
717716
case func():
718717
return func(context.Context) error {
@@ -1019,9 +1018,9 @@ func ListMatchingEnvVars(prefixes ...string) []string {
10191018
for _, v := range os.Environ() {
10201019
for _, prefix := range prefixes {
10211020
if strings.HasPrefix(v, prefix) {
1022-
eqIdx := strings.Index(v, "=")
1023-
if eqIdx != -1 {
1024-
vars = append(vars, v[:eqIdx])
1021+
before, _, ok := strings.Cut(v, "=")
1022+
if ok {
1023+
vars = append(vars, before)
10251024
}
10261025
break
10271026
}
@@ -1072,8 +1071,8 @@ func ReadGLIBCRequirement(elfFile string) (*SemanticVersion, error) {
10721071

10731072
versionSet := map[SemanticVersion]struct{}{}
10741073
for _, sym := range symbols {
1075-
if strings.HasPrefix(sym.Version, "GLIBC_") {
1076-
semver, err := NewSemanticVersion(strings.TrimPrefix(sym.Version, "GLIBC_"))
1074+
if after, ok := strings.CutPrefix(sym.Version, "GLIBC_"); ok {
1075+
semver, err := NewSemanticVersion(after)
10771076
if err != nil {
10781077
continue
10791078
}

dev-tools/mage/config.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,19 +66,19 @@ func (t ConfigFileType) IsDocker() bool { return t&DockerConfigType > 0 }
6666
// ConfigFileParams defines the files that make up each config file.
6767
type ConfigFileParams struct {
6868
Templates []string // List of files or globs to load.
69-
ExtraVars map[string]interface{}
69+
ExtraVars map[string]any
7070
Short, Reference, Docker ConfigParams
7171
}
7272

7373
type ConfigParams struct {
7474
Template string
75-
Deps []interface{}
75+
Deps []any
7676
}
7777

7878
func DefaultConfigFileParams() ConfigFileParams {
7979
return ConfigFileParams{
8080
Templates: []string{LibbeatDir("_meta/config/*.tmpl")},
81-
ExtraVars: map[string]interface{}{},
81+
ExtraVars: map[string]any{},
8282
Short: ConfigParams{
8383
Template: LibbeatDir("_meta/config/default.short.yml.tmpl"),
8484
},
@@ -124,17 +124,17 @@ func Config(types ConfigFileType, args ConfigFileParams, targetDir string) error
124124
func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigFileParams, typ ConfigFileType) error {
125125
// Determine what type to build and set some parameters.
126126
var confFile ConfigParams
127-
var tmplParams map[string]interface{}
127+
var tmplParams map[string]any
128128
switch typ {
129129
case ShortConfigType:
130130
confFile = confParams.Short
131-
tmplParams = map[string]interface{}{}
131+
tmplParams = map[string]any{}
132132
case ReferenceConfigType:
133133
confFile = confParams.Reference
134-
tmplParams = map[string]interface{}{"Reference": true}
134+
tmplParams = map[string]any{"Reference": true}
135135
case DockerConfigType:
136136
confFile = confParams.Docker
137-
tmplParams = map[string]interface{}{"Docker": true}
137+
tmplParams = map[string]any{"Docker": true}
138138
default:
139139
panic(fmt.Errorf("Invalid config file type: %v", typ))
140140
}
@@ -146,7 +146,7 @@ func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigF
146146
// Rather than adding more "ExcludeX"/"UseX" options consider overwriting
147147
// one of the libbeat templates in your project by adding a file with the
148148
// same name to your _meta/config directory.
149-
params := map[string]interface{}{
149+
params := map[string]any{
150150
"GOOS": EnvOr("DEV_OS", "linux"),
151151
"GOARCH": EnvOr("DEV_ARCH", "amd64"),
152152
"CI": EnvOr("CI", ""),
@@ -172,7 +172,7 @@ func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigF
172172
// include is necessary because you cannot pipe 'template' to a function
173173
// since 'template' is an action. This allows you to include a
174174
// template and indent it (e.g. {{ include "x.tmpl" . | indent 4 }}).
175-
"include": func(name string, data interface{}) (string, error) {
175+
"include": func(name string, data any) (string, error) {
176176
buf := bytes.NewBuffer(nil)
177177
if err := tmpl.ExecuteTemplate(buf, name, data); err != nil {
178178
return "", err
@@ -196,7 +196,7 @@ func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigF
196196
}
197197
}
198198

199-
data, err := ioutil.ReadFile(confFile.Template)
199+
data, err := os.ReadFile(confFile.Template)
200200
if err != nil {
201201
return fmt.Errorf("failed to read config template %q: %w", confFile.Template, err)
202202
}
@@ -265,7 +265,7 @@ type moduleFieldsYmlData []struct {
265265
}
266266

267267
func readModuleFieldsYml(path string) (title string, useShort bool, err error) {
268-
data, err := ioutil.ReadFile(path)
268+
data, err := os.ReadFile(path)
269269
if err != nil {
270270
return "", false, err
271271
}
@@ -327,7 +327,7 @@ func GenerateModuleReferenceConfig(out string, moduleDirs ...string) error {
327327

328328
var data []byte
329329
for _, f := range files {
330-
data, err = ioutil.ReadFile(f)
330+
data, err = os.ReadFile(f)
331331
if err != nil {
332332
if os.IsNotExist(err) {
333333
continue
@@ -361,9 +361,9 @@ func GenerateModuleReferenceConfig(out string, moduleDirs ...string) error {
361361
return moduleConfigs[i].ID < moduleConfigs[j].ID
362362
})
363363

364-
config := MustExpand(moduleConfigTemplate, map[string]interface{}{
364+
config := MustExpand(moduleConfigTemplate, map[string]any{
365365
"Modules": moduleConfigs,
366366
})
367367

368-
return ioutil.WriteFile(createDir(out), []byte(config), 0644)
368+
return os.WriteFile(createDir(out), []byte(config), 0644)
369369
}

dev-tools/mage/crossbuild.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ var Platforms = BuildPlatforms.Defaults()
5454
// values are ignored.
5555
func ParsePackageTypes(packageTypes string) []PackageType {
5656
var parsed []PackageType
57-
for _, packageType := range strings.Split(packageTypes, ",") {
57+
for packageType := range strings.SplitSeq(packageTypes, ",") {
5858
packageType = strings.TrimSpace(packageType)
5959
if packageType == "" {
6060
continue
@@ -199,7 +199,7 @@ func CrossBuild(options ...CrossBuildOption) error {
199199
mg.Deps(buildMage)
200200

201201
log.Println("crossBuild: Platform list =", params.Platforms)
202-
var deps []interface{}
202+
var deps []any
203203
for _, buildPlatform := range params.Platforms {
204204
if !buildPlatform.Flags.CanCrossBuild() {
205205
return fmt.Errorf("unsupported cross build platform %v", buildPlatform.Name)
@@ -501,7 +501,7 @@ func gitAlternateObjectDirMounts(objectsDir, containerObjectsDir string, alterna
501501
var mounts []dockerVolumeMount
502502
seen := map[string]struct{}{}
503503

504-
for _, line := range strings.Split(string(alternates), "\n") {
504+
for line := range strings.SplitSeq(string(alternates), "\n") {
505505
alternate := strings.TrimSpace(line)
506506
if alternate == "" || strings.HasPrefix(alternate, "#") {
507507
continue

dev-tools/mage/dashboard.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func ExportDashboard() error {
7171
// - KIBANA_INSECURE: Disable TLS verification.
7272
// - KIBANA_ALWAYS: Connect to Kibana without checking ES version. Default true.
7373
// - ES_URL: URL of Elasticsearch (only used with KIBANA_ALWAYS=false).
74-
func ImportDashboards(buildDep, dashboardDep interface{}) error {
74+
func ImportDashboards(buildDep, dashboardDep any) error {
7575
mg.Deps(buildDep, dashboardDep)
7676

7777
setupDashboards := sh.RunCmd(CWD(BeatName+binaryExtension(GOOS)),

0 commit comments

Comments
 (0)