From 265859b0ed5af9e3e0d47374cf070d438b948641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Wed, 13 Nov 2024 08:24:35 +0100 Subject: [PATCH] chore: Enable `revive:enforce-slice-style` rule (#16173) (cherry picked from commit 0d30797c08fb2e788e95bf5d3b20675a69582ef7) --- .golangci.yml | 2 ++ agent/accumulator_test.go | 2 +- agent/agent_test.go | 1 - agent/tick_test.go | 10 ++++------ cmd/telegraf/cmd_win_service_notwindows.go | 2 +- cmd/telegraf/printer.go | 10 +++++----- config/config.go | 4 ++-- config/config_test.go | 3 --- config/secret_test.go | 6 +++--- filter/filter_test.go | 6 +++--- internal/process/process.go | 2 +- internal/snmp/field_test.go | 6 +++--- internal/snmp/mib_loader.go | 2 +- internal/snmp/translator_netsnmp_mocks_test.go | 2 +- metric/series_grouper.go | 2 +- models/buffer_disk.go | 2 +- models/filter.go | 4 ++-- models/running_output_test.go | 4 ---- plugins/aggregators/basicstats/basicstats_test.go | 2 +- plugins/aggregators/histogram/histogram.go | 3 +-- plugins/inputs/dmcache/dmcache_notlinux.go | 2 +- .../inputs/win_perf_counters/win_perf_counters_test.go | 2 +- .../win_services/win_services_integration_test.go | 2 +- testutil/container.go | 4 +--- tools/readme_linter/main.go | 2 +- tools/readme_linter/rules.go | 6 +++--- 26 files changed, 41 insertions(+), 52 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b2eeca80b9fca..fd620a72f829c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -265,6 +265,8 @@ linters-settings: - name: enforce-map-style arguments: ["make"] exclude: [ "TEST" ] + - name: enforce-slice-style + arguments: ["make"] - name: error-naming - name: error-return - name: error-strings diff --git a/agent/accumulator_test.go b/agent/accumulator_test.go index 3d660e8657724..6e5dc66c5daac 100644 --- a/agent/accumulator_test.go +++ b/agent/accumulator_test.go @@ -127,7 +127,7 @@ func TestSetPrecision(t *testing.T) { func TestAddTrackingMetricGroupEmpty(t *testing.T) { ch := make(chan telegraf.Metric, 10) - metrics := []telegraf.Metric{} + metrics := make([]telegraf.Metric, 0) acc := NewAccumulator(&TestMetricMaker{}, ch).WithTracking(1) id := acc.AddTrackingMetricGroup(metrics) diff --git a/agent/agent_test.go b/agent/agent_test.go index 849b491b766eb..9741dfe93f151 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -83,7 +83,6 @@ func TestAgent_LoadOutput(t *testing.T) { require.Len(t, a.Config.Outputs, 1) c = config.NewConfig() - c.OutputFilters = []string{} err = c.LoadConfig("../config/testdata/telegraf-agent.toml") require.NoError(t, err) a = NewAgent(c) diff --git a/agent/tick_test.go b/agent/tick_test.go index 001ac85d954f2..078d50be92b57 100644 --- a/agent/tick_test.go +++ b/agent/tick_test.go @@ -37,8 +37,7 @@ func TestAlignedTicker(t *testing.T) { time.Unix(60, 0).UTC(), } - actual := []time.Time{} - + actual := make([]time.Time, 0) clk.Add(10 * time.Second) for !clk.Now().After(until) { tm := <-ticker.Elapsed() @@ -109,8 +108,7 @@ func TestAlignedTickerOffset(t *testing.T) { time.Unix(53, 0).UTC(), } - actual := []time.Time{} - + actual := make([]time.Time, 0) clk.Add(10*time.Second + offset) for !clk.Now().After(until) { tm := <-ticker.Elapsed() @@ -174,7 +172,7 @@ func TestUnalignedTicker(t *testing.T) { time.Unix(61, 0).UTC(), } - actual := []time.Time{} + actual := make([]time.Time, 0) for !clk.Now().After(until) { select { case tm := <-ticker.Elapsed(): @@ -215,7 +213,7 @@ func TestRollingTicker(t *testing.T) { time.Unix(61, 0).UTC(), } - actual := []time.Time{} + actual := make([]time.Time, 0) for !clk.Now().After(until) { select { case tm := <-ticker.Elapsed(): diff --git a/cmd/telegraf/cmd_win_service_notwindows.go b/cmd/telegraf/cmd_win_service_notwindows.go index ebf58cd514508..258d5c95d3826 100644 --- a/cmd/telegraf/cmd_win_service_notwindows.go +++ b/cmd/telegraf/cmd_win_service_notwindows.go @@ -9,7 +9,7 @@ import ( ) func cliFlags() []cli.Flag { - return []cli.Flag{} + return make([]cli.Flag, 0) } func getServiceCommands(io.Writer) []*cli.Command { diff --git a/cmd/telegraf/printer.go b/cmd/telegraf/printer.go index 02428125cff87..de92d6f5be6c4 100644 --- a/cmd/telegraf/printer.go +++ b/cmd/telegraf/printer.go @@ -24,7 +24,7 @@ var ( inputDefaults = []string{"cpu", "mem", "swap", "system", "kernel", "processes", "disk", "diskio"} // Default output plugins - outputDefaults = []string{} + outputDefaults = make([]string, 0) ) var header = `# Telegraf Configuration @@ -126,7 +126,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) { printFilteredSecretstores(secretstoreFilters, false, outputBuffer) } else { fmt.Print(secretstoreHeader) - snames := []string{} + snames := make([]string, 0, len(secretstores.SecretStores)) for sname := range secretstores.SecretStores { snames = append(snames, sname) } @@ -165,7 +165,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) { printFilteredProcessors(processorFilters, false, outputBuffer) } else { outputBuffer.Write([]byte(processorHeader)) - pnames := []string{} + pnames := make([]string, 0, len(processors.Processors)) for pname := range processors.Processors { pnames = append(pnames, pname) } @@ -182,7 +182,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) { printFilteredAggregators(aggregatorFilters, false, outputBuffer) } else { outputBuffer.Write([]byte(aggregatorHeader)) - pnames := []string{} + pnames := make([]string, 0, len(aggregators.Aggregators)) for pname := range aggregators.Aggregators { pnames = append(pnames, pname) } @@ -261,7 +261,7 @@ func printFilteredInputs(inputFilters []string, commented bool, outputBuffer io. // cache service inputs to print them at the end servInputs := make(map[string]telegraf.ServiceInput) // for alphabetical looping: - servInputNames := []string{} + servInputNames := make([]string, 0, len(pnames)) // Print Inputs for _, pname := range pnames { diff --git a/config/config.go b/config/config.go index d390473218078..a0bc208c1cb26 100644 --- a/config/config.go +++ b/config/config.go @@ -434,7 +434,7 @@ func GetDefaultConfigPath() ([]string, error) { // At this point we need to check if the files under /etc/telegraf are // populated and return them all. - confFiles := []string{} + confFiles := make([]string, 0) if _, err := os.Stat(etcfile); err == nil { confFiles = append(confFiles, etcfile) } @@ -1803,7 +1803,7 @@ func (c *Config) getFieldTagFilter(tbl *ast.Table, fieldName string) []models.Ta } func keys(m map[string]bool) []string { - result := []string{} + result := make([]string, 0, len(m)) for k := range m { result = append(result, k) } diff --git a/config/config_test.go b/config/config_test.go index 9a50f2cabe348..11956d4d889a5 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -479,8 +479,6 @@ func TestConfig_InlineTables(t *testing.T) { } func TestConfig_SliceComment(t *testing.T) { - t.Skipf("Skipping until #3642 is resolved") - c := config.NewConfig() require.NoError(t, c.LoadConfig("./testdata/slice_comment.toml")) require.Len(t, c.Outputs, 1) @@ -1575,7 +1573,6 @@ func (m *MockupStatePlugin) Init() error { } m.state = MockupState{ Name: "mockup", - Bits: []int{}, Modified: t0, } diff --git a/config/secret_test.go b/config/secret_test.go index 90370e9323a10..6422c5a97d0e5 100644 --- a/config/secret_test.go +++ b/config/secret_test.go @@ -67,7 +67,7 @@ func TestGettingMissingResolver(t *testing.T) { mysecret := "a @{referenced:secret}" s := NewSecret([]byte(mysecret)) defer s.Destroy() - s.unlinked = []string{} + s.unlinked = make([]string, 0) s.resolvers = map[string]telegraf.ResolveFunc{ "@{a:dummy}": func() ([]byte, bool, error) { return nil, false, nil @@ -82,7 +82,7 @@ func TestGettingResolverError(t *testing.T) { mysecret := "a @{referenced:secret}" s := NewSecret([]byte(mysecret)) defer s.Destroy() - s.unlinked = []string{} + s.unlinked = make([]string, 0) s.resolvers = map[string]telegraf.ResolveFunc{ "@{referenced:secret}": func() ([]byte, bool, error) { return nil, false, errors.New("broken") @@ -111,7 +111,7 @@ func TestEnclaveOpenError(t *testing.T) { err := s.Link(map[string]telegraf.ResolveFunc{}) require.ErrorContains(t, err, "opening enclave failed") - s.unlinked = []string{} + s.unlinked = make([]string, 0) _, err = s.Get() require.ErrorContains(t, err, "opening enclave failed") } diff --git a/filter/filter_test.go b/filter/filter_test.go index 05a78bd4aa46e..8842d2a74a6e5 100644 --- a/filter/filter_test.go +++ b/filter/filter_test.go @@ -7,7 +7,7 @@ import ( ) func TestCompile(t *testing.T) { - f, err := Compile([]string{}) + f, err := Compile(nil) require.NoError(t, err) require.Nil(t, f) @@ -50,10 +50,10 @@ func TestCompile(t *testing.T) { } func TestIncludeExclude(t *testing.T) { - tags := []string{} labels := []string{"best", "com_influxdata", "timeseries", "com_influxdata_telegraf", "ever"} + tags := make([]string, 0, len(labels)) - filter, err := NewIncludeExcludeFilter([]string{}, []string{"com_influx*"}) + filter, err := NewIncludeExcludeFilter(nil, []string{"com_influx*"}) if err != nil { t.Fatalf("Failed to create include/exclude filter - %v", err) } diff --git a/internal/process/process.go b/internal/process/process.go index 784cf91f543b5..78f4dcab3d5a2 100644 --- a/internal/process/process.go +++ b/internal/process/process.go @@ -45,7 +45,7 @@ func New(command []string, envs []string) (*Process, error) { p := &Process{ RestartDelay: 5 * time.Second, name: command[0], - args: []string{}, + args: make([]string, 0), envs: envs, } diff --git a/internal/snmp/field_test.go b/internal/snmp/field_test.go index c9cdf020974ec..53d080c21aba3 100644 --- a/internal/snmp/field_test.go +++ b/internal/snmp/field_test.go @@ -181,7 +181,7 @@ func TestConvertHextoint(t *testing.T) { { name: "big endian invalid", conversion: "hextoint:BigEndian:invalid", - ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []uint8{}}, + ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]uint8, 0)}, errmsg: "invalid bit value", }, { @@ -214,13 +214,13 @@ func TestConvertHextoint(t *testing.T) { { name: "little endian invalid", conversion: "hextoint:LittleEndian:invalid", - ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []byte{}}, + ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]byte, 0)}, errmsg: "invalid bit value", }, { name: "invalid", conversion: "hextoint:invalid:uint64", - ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []byte{}}, + ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]byte, 0)}, errmsg: "invalid Endian value", }, } diff --git a/internal/snmp/mib_loader.go b/internal/snmp/mib_loader.go index de7cede858060..d6641767d5791 100644 --- a/internal/snmp/mib_loader.go +++ b/internal/snmp/mib_loader.go @@ -92,8 +92,8 @@ func LoadMibsFromPath(paths []string, log telegraf.Logger, loader MibLoader) err // should walk the paths given and find all folders func walkPaths(paths []string, log telegraf.Logger) ([]string, error) { once.Do(gosmi.Init) - folders := []string{} + folders := make([]string, 0) for _, mibPath := range paths { // Check if we loaded that path already and skip it if so m.Lock() diff --git a/internal/snmp/translator_netsnmp_mocks_test.go b/internal/snmp/translator_netsnmp_mocks_test.go index d74540cfa2da0..72a00faed1da5 100644 --- a/internal/snmp/translator_netsnmp_mocks_test.go +++ b/internal/snmp/translator_netsnmp_mocks_test.go @@ -28,7 +28,7 @@ func TestMockExecCommand(_ *testing.T) { var cmd []string //nolint:prealloc // Pre-allocated this slice would break the algorithm for _, arg := range os.Args { if arg == "--" { - cmd = []string{} + cmd = make([]string, 0) continue } if cmd == nil { diff --git a/metric/series_grouper.go b/metric/series_grouper.go index d20470de50c7e..15f0cc5f16d67 100644 --- a/metric/series_grouper.go +++ b/metric/series_grouper.go @@ -23,7 +23,7 @@ import ( func NewSeriesGrouper() *SeriesGrouper { return &SeriesGrouper{ metrics: make(map[uint64]telegraf.Metric), - ordered: []telegraf.Metric{}, + ordered: make([]telegraf.Metric, 0), hashSeed: maphash.MakeSeed(), } } diff --git a/models/buffer_disk.go b/models/buffer_disk.go index 09e338224762f..57836dbab9070 100644 --- a/models/buffer_disk.go +++ b/models/buffer_disk.go @@ -127,7 +127,7 @@ func (b *DiskBuffer) Batch(batchSize int) []telegraf.Metric { if b.length() == 0 { // no metrics in the wal file, so return an empty array - return []telegraf.Metric{} + return make([]telegraf.Metric, 0) } b.batchFirst = b.readIndex() var metrics []telegraf.Metric diff --git a/models/filter.go b/models/filter.go index 92b409556c6d2..2fcf4bbf7e692 100644 --- a/models/filter.go +++ b/models/filter.go @@ -206,7 +206,7 @@ func (f *Filter) shouldTagsPass(tags []*telegraf.Tag) bool { // filterFields removes fields according to fieldinclude/fieldexclude. func (f *Filter) filterFields(metric telegraf.Metric) { - filterKeys := []string{} + filterKeys := make([]string, 0, len(metric.FieldList())) for _, field := range metric.FieldList() { if !ShouldPassFilters(f.fieldIncludeFilter, f.fieldExcludeFilter, field.Key) { filterKeys = append(filterKeys, field.Key) @@ -220,7 +220,7 @@ func (f *Filter) filterFields(metric telegraf.Metric) { // filterTags removes tags according to taginclude/tagexclude. func (f *Filter) filterTags(metric telegraf.Metric) { - filterKeys := []string{} + filterKeys := make([]string, 0, len(metric.TagList())) for _, tag := range metric.TagList() { if !ShouldPassFilters(f.tagIncludeFilter, f.tagExcludeFilter, tag.Key) { filterKeys = append(filterKeys, tag.Key) diff --git a/models/running_output_test.go b/models/running_output_test.go index 6054cf359a5fb..c045dcf0140f2 100644 --- a/models/running_output_test.go +++ b/models/running_output_test.go @@ -777,10 +777,6 @@ func (m *mockOutput) Write(metrics []telegraf.Metric) error { return errors.New("failed write") } - if m.metrics == nil { - m.metrics = []telegraf.Metric{} - } - m.metrics = append(m.metrics, metrics...) return nil } diff --git a/plugins/aggregators/basicstats/basicstats_test.go b/plugins/aggregators/basicstats/basicstats_test.go index 1aa81e050cf23..28e77ab80fb36 100644 --- a/plugins/aggregators/basicstats/basicstats_test.go +++ b/plugins/aggregators/basicstats/basicstats_test.go @@ -699,7 +699,7 @@ func TestBasicStatsWithAllStats(t *testing.T) { // Test that if an empty array is passed, no points are pushed func TestBasicStatsWithNoStats(t *testing.T) { aggregator := NewBasicStats() - aggregator.Stats = []string{} + aggregator.Stats = make([]string, 0) aggregator.Log = testutil.Logger{} aggregator.initConfiguredStats() diff --git a/plugins/aggregators/histogram/histogram.go b/plugins/aggregators/histogram/histogram.go index 01370d808d13b..b85d9c7d52fce 100644 --- a/plugins/aggregators/histogram/histogram.go +++ b/plugins/aggregators/histogram/histogram.go @@ -139,9 +139,8 @@ func (h *HistogramAggregator) Add(in telegraf.Metric) { // Push returns histogram values for metrics func (h *HistogramAggregator) Push(acc telegraf.Accumulator) { - metricsWithGroupedFields := []groupedByCountFields{} now := timeNow() - + metricsWithGroupedFields := make([]groupedByCountFields, 0) for id, aggregate := range h.cache { if h.ExpirationInterval != 0 && now.After(aggregate.expireTime) { delete(h.cache, id) diff --git a/plugins/inputs/dmcache/dmcache_notlinux.go b/plugins/inputs/dmcache/dmcache_notlinux.go index 6d9d01e623771..9039dbc5c7491 100644 --- a/plugins/inputs/dmcache/dmcache_notlinux.go +++ b/plugins/inputs/dmcache/dmcache_notlinux.go @@ -11,5 +11,5 @@ func (*DMCache) Gather(_ telegraf.Accumulator) error { } func dmSetupStatus() ([]string, error) { - return []string{}, nil + return make([]string, 0), nil } diff --git a/plugins/inputs/win_perf_counters/win_perf_counters_test.go b/plugins/inputs/win_perf_counters/win_perf_counters_test.go index 78ab8e25b6976..cb7d43c26678f 100644 --- a/plugins/inputs/win_perf_counters/win_perf_counters_test.go +++ b/plugins/inputs/win_perf_counters/win_perf_counters_test.go @@ -99,7 +99,7 @@ func (m *FakePerformanceQuery) ExpandWildCardPath(counterPath string) ([]string, if e, ok := m.expandPaths[counterPath]; ok { return e, nil } - return []string{}, fmt.Errorf("in ExpandWildCardPath: invalid counter path: %q", counterPath) + return nil, fmt.Errorf("in ExpandWildCardPath: invalid counter path: %q", counterPath) } func (m *FakePerformanceQuery) GetFormattedCounterValueDouble(counterHandle pdhCounterHandle) (float64, error) { diff --git a/plugins/inputs/win_services/win_services_integration_test.go b/plugins/inputs/win_services/win_services_integration_test.go index 4edb0dfbb65ae..725756ae233d8 100644 --- a/plugins/inputs/win_services/win_services_integration_test.go +++ b/plugins/inputs/win_services/win_services_integration_test.go @@ -50,7 +50,7 @@ func TestEmptyListIntegration(t *testing.T) { }() winServices := &WinServices{ - ServiceNames: []string{}, + ServiceNames: make([]string, 0), } require.NoError(t, winServices.Init()) diff --git a/testutil/container.go b/testutil/container.go index eeecdd620ce0e..48131d1d26d2f 100644 --- a/testutil/container.go +++ b/testutil/container.go @@ -78,9 +78,7 @@ func (c *Container) Start() error { } c.container = cntnr - c.Logs = TestLogConsumer{ - Msgs: []string{}, - } + c.Logs = TestLogConsumer{} c.container.FollowOutput(&c.Logs) err = c.container.StartLogProducer(c.ctx) if err != nil { diff --git a/tools/readme_linter/main.go b/tools/readme_linter/main.go index 5c6f6af24b0a0..63e24662fa485 100644 --- a/tools/readme_linter/main.go +++ b/tools/readme_linter/main.go @@ -97,7 +97,7 @@ func checkFile(filename string, pluginType plugin, sourceFlag bool) (bool, error scanner := bufio.NewScanner(bytes.NewReader(md)) scanner.Split(bufio.ScanRunes) offset := 0 - newlineOffsets := []int{} + newlineOffsets := make([]int, 0) for scanner.Scan() { if scanner.Text() == "\n" { newlineOffsets = append(newlineOffsets, offset) diff --git a/tools/readme_linter/rules.go b/tools/readme_linter/rules.go index 421def5645a85..b883601f4b60f 100644 --- a/tools/readme_linter/rules.go +++ b/tools/readme_linter/rules.go @@ -92,7 +92,7 @@ func noLongLinesInParagraphs(threshold int) func(*T, ast.Node) error { return func(t *T, root ast.Node) error { // We're looking for long lines in paragraphs. Find paragraphs // first, then which lines are in paragraphs - paraLines := []int{} + paraLines := make([]int, 0) for n := root.FirstChild(); n != nil; n = n.NextSibling() { var p *ast.Paragraph var ok bool @@ -108,7 +108,7 @@ func noLongLinesInParagraphs(threshold int) func(*T, ast.Node) error { } // Find long lines in the whole file - longLines := []int{} + longLines := make([]int, 0, len(t.newlineOffsets)) last := 0 for i, cur := range t.newlineOffsets { length := cur - last - 1 // -1 to exclude the newline @@ -121,7 +121,7 @@ func noLongLinesInParagraphs(threshold int) func(*T, ast.Node) error { // Merge both lists p := 0 l := 0 - bads := []int{} + bads := make([]int, 0, max(len(paraLines), len(longLines))) for p < len(paraLines) && l < len(longLines) { long := longLines[l] para := paraLines[p]