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

chore: Enable revive:enforce-slice-style rule #16173

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion agent/accumulator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 4 additions & 6 deletions agent/tick_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion cmd/telegraf/cmd_win_service_notwindows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func cliFlags() []cli.Flag {
return []cli.Flag{}
return make([]cli.Flag, 0)
}

func getServiceCommands(io.Writer) []*cli.Command {
Expand Down
10 changes: 5 additions & 5 deletions cmd/telegraf/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -1805,7 +1805,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)
}
Expand Down
3 changes: 0 additions & 3 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -1575,7 +1573,6 @@ func (m *MockupStatePlugin) Init() error {
}
m.state = MockupState{
Name: "mockup",
Bits: []int{},
Modified: t0,
}

Expand Down
6 changes: 3 additions & 3 deletions config/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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")
}
Expand Down
6 changes: 3 additions & 3 deletions filter/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}

Expand Down
6 changes: 3 additions & 3 deletions internal/snmp/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
{
Expand Down Expand Up @@ -223,13 +223,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",
},
}
Expand Down
2 changes: 1 addition & 1 deletion internal/snmp/mib_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion internal/snmp/translator_netsnmp_mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion metric/series_grouper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}
Expand Down
2 changes: 1 addition & 1 deletion models/buffer_disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions models/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
4 changes: 0 additions & 4 deletions models/running_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/aggregators/basicstats/basicstats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,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()

Expand Down
3 changes: 1 addition & 2 deletions plugins/aggregators/histogram/histogram.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/dmcache/dmcache_notlinux.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ func (*DMCache) Gather(_ telegraf.Accumulator) error {
}

func dmSetupStatus() ([]string, error) {
return []string{}, nil
return make([]string, 0), nil
}
2 changes: 1 addition & 1 deletion plugins/inputs/win_perf_counters/win_perf_counters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestEmptyListIntegration(t *testing.T) {
}()

winServices := &WinServices{
ServiceNames: []string{},
ServiceNames: make([]string, 0),
}

require.NoError(t, winServices.Init())
Expand Down
4 changes: 1 addition & 3 deletions testutil/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion tools/readme_linter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions tools/readme_linter/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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]
Expand Down
Loading