chore: Enable dynamicFmtString and sprintfQuotedString checkers for gocritic (#13279)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2023-06-09 10:11:52 +02:00 committed by GitHub
parent 16786d2977
commit 02f0b15033
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 46 additions and 39 deletions

View File

@ -102,6 +102,7 @@ linters-settings:
- dupBranchBody
- dupCase
- dupSubExpr
- dynamicFmtString
- emptyDecl
- evalOrder
- exitAfterDefer
@ -110,6 +111,7 @@ linters-settings:
- regexpPattern
- sloppyTypeAssert
- sortSlice
- sprintfQuotedString
- sqlQuery
- uncheckedInlineErr
- unnecessaryDefer

View File

@ -238,7 +238,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) {
t.Run("when 2 ethdev commands are enabled, then 2*numberOfIds new commands should be appended", func(t *testing.T) {
mockConn, dpdk, mockAcc := prepareEnvironment()
defer mockConn.AssertExpectations(t)
response := fmt.Sprintf(`{"%s": [1, 123]}`, ethdevListCommand)
response := fmt.Sprintf(`{%q: [1, 123]}`, ethdevListCommand)
simulateResponse(mockConn, response, nil)
expectedCommands := []string{"/ethdev/stats,1", "/ethdev/stats,123", "/ethdev/xstats,1", "/ethdev/xstats,123"}
@ -255,7 +255,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) {
t.Run("when 1 rawdev command is enabled, then 2*numberOfIds new commands should be appended", func(t *testing.T) {
mockConn, dpdk, mockAcc := prepareEnvironment()
defer mockConn.AssertExpectations(t)
response := fmt.Sprintf(`{"%s": [1, 123]}`, rawdevListCommand)
response := fmt.Sprintf(`{%q: [1, 123]}`, rawdevListCommand)
simulateResponse(mockConn, response, nil)
expectedCommands := []string{"/rawdev/xstats,1", "/rawdev/xstats,123"}
@ -271,7 +271,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) {
t.Run("when 2 ethdev commands are enabled but one command is disabled, then numberOfIds new commands should be appended", func(t *testing.T) {
mockConn, dpdk, mockAcc := prepareEnvironment()
defer mockConn.AssertExpectations(t)
response := fmt.Sprintf(`{"%s": [1, 123]}`, ethdevListCommand)
response := fmt.Sprintf(`{%q: [1, 123]}`, ethdevListCommand)
simulateResponse(mockConn, response, nil)
expectedCommands := []string{"/ethdev/stats,1", "/ethdev/stats,123"}

View File

@ -95,7 +95,7 @@ func Test_jsonToArray(t *testing.T) {
t.Run("when got numeric array then string array should be returned", func(t *testing.T) {
firstValue := int64(0)
secondValue := int64(1)
jsonString := fmt.Sprintf(`{"%s": [%d, %d]}`, key, firstValue, secondValue)
jsonString := fmt.Sprintf(`{%q: [%d, %d]}`, key, firstValue, secondValue)
arr, err := jsonToArray([]byte(jsonString), key)
@ -120,7 +120,7 @@ func Test_jsonToArray(t *testing.T) {
})
t.Run("when valid json with json-object is supplied as input then error should be returned", func(t *testing.T) {
jsonString := fmt.Sprintf(`{"%s": {"testKey": "testValue"}}`, key)
jsonString := fmt.Sprintf(`{%q: {"testKey": "testValue"}}`, key)
_, err := jsonToArray([]byte(jsonString), key)

View File

@ -4,6 +4,7 @@ package elasticsearch
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -204,14 +205,14 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error {
// Gather node ID
if info.nodeID, err = e.gatherNodeID(s + "/_nodes/_local/name"); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
// get cat/master information here so NodeStats can determine
// whether this node is the Master
if info.masterID, err = e.getCatMaster(s + "/_cat/master"); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
@ -233,7 +234,7 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error {
// Always gather node stats
if err := e.gatherNodeStats(url, acc); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
@ -243,14 +244,14 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error {
url = url + "?level=" + e.ClusterHealthLevel
}
if err := e.gatherClusterHealth(url, acc); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
}
if e.ClusterStats && (e.serverInfo[s].isMaster() || !e.ClusterStatsOnlyFromMaster || !e.Local) {
if err := e.gatherClusterStats(s+"/_cluster/stats", acc); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
}
@ -258,12 +259,12 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error {
if len(e.IndicesInclude) > 0 && (e.serverInfo[s].isMaster() || !e.ClusterStatsOnlyFromMaster || !e.Local) {
if e.IndicesLevel != "shards" {
if err := e.gatherIndicesStats(s+"/"+strings.Join(e.IndicesInclude, ",")+"/_stats", acc); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
} else {
if err := e.gatherIndicesStats(s+"/"+strings.Join(e.IndicesInclude, ",")+"/_stats?level=shards", acc); err != nil {
acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@")))
return
}
}

View File

@ -11,11 +11,12 @@ import (
"testing"
"time"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs/dpdk/mocks"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestDLB_Init(t *testing.T) {
@ -310,7 +311,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) {
maxInitMessageLength: 1024,
EventdevCommands: []string{"/eventdev/dev_xstats"},
}
response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListCommand)
response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListCommand)
simulateResponse(mockConn, response, nil)
expectedCommands := []string{"/eventdev/dev_xstats,0", "/eventdev/dev_xstats,1"}
@ -330,7 +331,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) {
maxInitMessageLength: 1024,
EventdevCommands: []string{"/eventdev/queue_links"},
}
responseDevList := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand)
responseDevList := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand)
simulateResponse(mockConn, responseDevList, nil)
responseQueueLinks := `{"0": [0]}`
simulateResponse(mockConn, responseQueueLinks, nil)
@ -352,7 +353,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) {
maxInitMessageLength: 1024,
EventdevCommands: []string{"/eventdev/dev_xstats", "/eventdev/wrong"},
}
response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListCommand)
response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListCommand)
mockConn.On("Write", mock.Anything).Return(0, nil).Once()
mockConn.On("Read", mock.Anything).Run(func(arg mock.Arguments) {
elem := arg.Get(0).([]byte)
@ -443,7 +444,7 @@ func TestDLB_gatherSecondDeviceIndex(t *testing.T) {
EventdevCommands: []string{"/eventdev/port_xstats"},
}
eventdevListWithSecondIndex := []string{"/eventdev/port_list", "/eventdev/queue_list"}
response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListWithSecondIndex[0])
response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListWithSecondIndex[0])
simulateResponse(mockConn, response, nil)
expectedCommands := []string{"/eventdev/port_xstats,0,0", "/eventdev/port_xstats,0,1"}
@ -468,7 +469,7 @@ func TestDLB_processCommandResult(t *testing.T) {
maxInitMessageLength: 1024,
EventdevCommands: []string{"/eventdev/dev_xstats"},
}
response := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand)
response := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand)
simulateResponse(mockConn, response, nil)
response = `{"/eventdev/dev_xstats": {"dev_rx_ok": 0}}`
@ -506,7 +507,7 @@ func TestDLB_processCommandResult(t *testing.T) {
rasReader: fileMock,
maxInitMessageLength: 1024,
}
responseGather := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand)
responseGather := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand)
mockConn.On("Write", mock.Anything).Return(0, nil).Twice()
mockConn.On("Read", mock.Anything).Run(func(arg mock.Arguments) {
elem := arg.Get(0).([]byte)
@ -537,7 +538,7 @@ func TestDLB_processCommandResult(t *testing.T) {
Log: testutil.Logger{},
EventdevCommands: []string{"/eventdev/dev_xstats"},
}
response := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand)
response := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand)
simulateResponse(mockConn, response, nil)
simulateResponse(mockConn, "/wrong/json", nil)
@ -622,7 +623,7 @@ func TestDLB_processCommandResult(t *testing.T) {
}
mockConn.On("Close").Return(nil)
responseGather := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand)
responseGather := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand)
mockConn.On("Write", mock.Anything).Return(0, nil).Once().
On("Read", mock.Anything).Run(func(arg mock.Arguments) {
elem := arg.Get(0).([]byte)
@ -949,7 +950,7 @@ func simulateSocketResponseForGather(socket net.Listener, t *testing.T) {
require.NoError(t, err)
eventdevListWithSecondIndex := []string{"/eventdev/port_list", "/eventdev/queue_list"}
_, err = conn.Write([]byte(fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListWithSecondIndex[0])))
_, err = conn.Write([]byte(fmt.Sprintf(`{%q: [0, 1]}`, eventdevListWithSecondIndex[0])))
require.NoError(t, err)
}

View File

@ -497,7 +497,7 @@ func validateInterval(interval int32) error {
func splitMeasurementLine(line string) ([]string, error) {
values := strings.Split(line, ",")
if len(values) < 8 {
return nil, fmt.Errorf(fmt.Sprintf("not valid line format from pqos: %s", values))
return nil, fmt.Errorf("not valid line format from pqos: %s", values)
}
return values, nil
}

View File

@ -265,7 +265,7 @@ func (s *Stackdriver) newListTimeSeriesFilter(metricType string) string {
"has_substring",
"one_of",
}
filterString := fmt.Sprintf(`metric.type = "%s"`, metricType)
filterString := fmt.Sprintf(`metric.type = %q`, metricType)
if s.Filter == nil {
return filterString
}

View File

@ -590,7 +590,7 @@ func TestOAuthAuthorizationCodeGrant(t *testing.T) {
},
tokenHandler: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
authHeader := fmt.Sprintf(`{"id_token":"%s"}`, token)
authHeader := fmt.Sprintf(`{"id_token":%q}`, token)
_, err = w.Write([]byte(authHeader))
require.NoError(t, err)
},

View File

@ -208,6 +208,7 @@ func (c *httpClient) Database() string {
// Note that some names are not allowed by the server, notably those with
// non-printable characters or slashes.
func (c *httpClient) CreateDatabase(ctx context.Context, database string) error {
//nolint:gocritic // sprintfQuotedString - "%s" used by purpose, string escaping is done by special function
query := fmt.Sprintf(`CREATE DATABASE "%s"`, escapeIdentifier.Replace(database))
req, err := c.makeQueryRequest(query)

View File

@ -4,6 +4,7 @@ package warp10
import (
"bytes"
_ "embed"
"errors"
"fmt"
"io"
"math"
@ -142,14 +143,14 @@ func (w *Warp10) Write(metrics []telegraf.Metric) error {
if resp.StatusCode != http.StatusOK {
if w.PrintErrorBody {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf(w.WarpURL + ": " + w.HandleError(string(body), w.MaxStringErrorSize))
return errors.New(w.WarpURL + ": " + w.HandleError(string(body), w.MaxStringErrorSize))
}
if len(resp.Status) < w.MaxStringErrorSize {
return fmt.Errorf(w.WarpURL + ": " + resp.Status)
return errors.New(w.WarpURL + ": " + resp.Status)
}
return fmt.Errorf(w.WarpURL + ": " + resp.Status[0:w.MaxStringErrorSize])
return errors.New(w.WarpURL + ": " + resp.Status[0:w.MaxStringErrorSize])
}
return nil

View File

@ -190,7 +190,7 @@ func (c *Container) configureYum() error {
err := c.client.Exec(
c.Name,
"bash", "-c", "--",
fmt.Sprintf("echo \"%s\" > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo),
fmt.Sprintf("echo %q > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo),
)
if err != nil {
return err
@ -205,7 +205,7 @@ func (c *Container) configureDnf() error {
err := c.client.Exec(
c.Name,
"bash", "-c", "--",
fmt.Sprintf("echo \"%s\" > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo),
fmt.Sprintf("echo %q > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo),
)
if err != nil {
return err
@ -219,7 +219,7 @@ func (c *Container) configureDnf() error {
func (c *Container) configureZypper() error {
err := c.client.Exec(
c.Name,
"echo", fmt.Sprintf("\"%s\"", influxDataRPMRepo), ">", "/etc/zypp/repos.d/influxdata.repo",
"echo", fmt.Sprintf("%q", influxDataRPMRepo), ">", "/etc/zypp/repos.d/influxdata.repo",
)
if err != nil {
return err

View File

@ -2,6 +2,7 @@ package main
import (
"bytes"
"errors"
"fmt"
"os"
"strconv"
@ -140,7 +141,7 @@ func (c *LXDClient) Exec(name string, command ...string) error {
rc := int(opAPI.Metadata["return"].(float64))
if rc != 0 {
return fmt.Errorf(output.String())
return errors.New(output.String())
}
fmt.Println(output.String())

View File

@ -190,32 +190,32 @@ func main() {
{
FileName: "scripts/installgo_linux.sh",
Regex: `(GO_VERSION)=("\d.\d*.\d")`,
Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion),
Replace: fmt.Sprintf("$1=%q", zeroPatchVersion),
},
{
FileName: "scripts/installgo_mac.sh",
Regex: `(GO_VERSION)=("\d.\d*.\d")`,
Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion),
Replace: fmt.Sprintf("$1=%q", zeroPatchVersion),
},
{
FileName: "scripts/installgo_windows.sh",
Regex: `(GO_VERSION)=("\d.\d*.\d")`,
Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion),
Replace: fmt.Sprintf("$1=%q", zeroPatchVersion),
},
{
FileName: "scripts/installgo_linux.sh",
Regex: `(GO_VERSION_SHA)=".*"`,
Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.linux-amd64.tar.gz", zeroPatchVersion)]),
Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.linux-amd64.tar.gz", zeroPatchVersion)]),
},
{
FileName: "scripts/installgo_mac.sh",
Regex: `(GO_VERSION_SHA_arm64)=".*"`,
Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.darwin-arm64.tar.gz", zeroPatchVersion)]),
Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.darwin-arm64.tar.gz", zeroPatchVersion)]),
},
{
FileName: "scripts/installgo_mac.sh",
Regex: `(GO_VERSION_SHA_amd64)=".*"`,
Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.darwin-amd64.tar.gz", zeroPatchVersion)]),
Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.darwin-amd64.tar.gz", zeroPatchVersion)]),
},
}