chore: Resolve linter issues for plugins/common package (#11964)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2022-10-11 18:31:44 +02:00 committed by GitHub
parent 8ca3b9262a
commit 9ff5cda6e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 99 additions and 156 deletions

View File

@ -69,7 +69,7 @@ linters-settings:
- name: unconditional-recursion
- name: unexported-naming
- name: unhandled-error
arguments: ["outputBuffer.Write", "fmt.Printf", "fmt.Println", "fmt.Print"]
arguments: ["outputBuffer.Write", "fmt.Printf", "fmt.Println", "fmt.Print", "fmt.Fprintf", "fmt.Fprint", "fmt.Fprintln"]
- name: unnecessary-stmt
- name: unreachable-code
# - name: unused-parameter

View File

@ -273,7 +273,7 @@ func (t *Telegraf) runAgent(ctx context.Context) error {
if err != nil {
log.Printf("E! Unable to create pidfile: %s", err)
} else {
_, _ = fmt.Fprintf(f, "%d\n", os.Getpid())
fmt.Fprintf(f, "%d\n", os.Getpid())
err = f.Close()
if err != nil {

View File

@ -15,7 +15,7 @@ import (
var sampleConfig string
type Starlark struct {
common.StarlarkCommon
common.Common
}
func (*Starlark) SampleConfig() string {
@ -24,7 +24,7 @@ func (*Starlark) SampleConfig() string {
func (s *Starlark) Init() error {
// Execute source
err := s.StarlarkCommon.Init()
err := s.Common.Init()
if err != nil {
return err
}
@ -106,7 +106,7 @@ func (s *Starlark) Reset() {
func init() {
aggregators.Add("starlark", func() telegraf.Aggregator {
return &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: common.LoadFunc,
},
}

View File

@ -403,7 +403,7 @@ def reset():
func newStarlarkFromSource(source string) (*Starlark, error) {
plugin := &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: common.LoadFunc,
Log: testutil.Logger{},
Source: source,
@ -418,7 +418,7 @@ func newStarlarkFromSource(source string) (*Starlark, error) {
func newStarlarkFromScript(script string) (*Starlark, error) {
plugin := &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: common.LoadFunc,
Log: testutil.Logger{},
Script: script,

View File

@ -17,7 +17,7 @@ var pollIntervalDisabled = flag.Bool("poll_interval_disabled", false, "set to tr
var configFile = flag.String("config", "", "path to the config file for this plugin")
var err error
// This is designed to be simple; Just change the import above and you're good.
// This is designed to be simple; Just change the import above, and you're good.
//
// However, if you want to do all your config in code, you can like so:
//
@ -46,14 +46,13 @@ func main() {
// otherwise, follow what the config asks for.
// Check for settings from a config toml file,
// (or just use whatever plugins were imported above)
err = shimLayer.LoadConfig(configFile)
if err != nil {
if err = shimLayer.LoadConfig(configFile); err != nil {
fmt.Fprintf(os.Stderr, "Err loading input: %s\n", err)
os.Exit(1)
}
// run a single plugin until stdin closes or we receive a termination signal
if err := shimLayer.Run(*pollInterval); err != nil {
// run a single plugin until stdin closes, or we receive a termination signal
if err = shimLayer.Run(*pollInterval); err != nil {
fmt.Fprintf(os.Stderr, "Err: %s\n", err)
os.Exit(1)
}

View File

@ -26,7 +26,7 @@ func (s *Shim) RunOutput() error {
parser := influx.Parser{}
err := parser.Init()
if err != nil {
return fmt.Errorf("Failed to create new parser: %w", err)
return fmt.Errorf("failed to create new parser: %w", err)
}
err = s.Output.Connect()

View File

@ -66,6 +66,7 @@ func catch(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kw
return nil, err
}
if _, err := starlark.Call(thread, fn, nil, nil); err != nil {
//nolint:nilerr // nil returned on purpose, error put inside starlark.Value
return starlark.String(err.Error()), nil
}
return starlark.None, nil
@ -206,22 +207,27 @@ func dictUpdate(b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tupl
defer iter.Done()
var pair starlark.Value
for i := 0; iter.Next(&pair); i++ {
iter2 := starlark.Iterate(pair)
if iter2 == nil {
return nil, fmt.Errorf("dictionary update sequence element #%d is not iterable (%s)", i, pair.Type())
}
defer iter2.Done()
length := starlark.Len(pair)
if length < 0 {
return nil, fmt.Errorf("dictionary update sequence element #%d has unknown length (%s)", i, pair.Type())
} else if length != 2 {
return nil, fmt.Errorf("dictionary update sequence element #%d has length %d, want 2", i, length)
}
var k, v starlark.Value
iter2.Next(&k)
iter2.Next(&v)
if err := dict.SetKey(k, v); err != nil {
return nil, err
iterErr := func() error {
iter2 := starlark.Iterate(pair)
if iter2 == nil {
return fmt.Errorf("dictionary update sequence element #%d is not iterable (%s)", i, pair.Type())
}
defer iter2.Done()
length := starlark.Len(pair)
if length < 0 {
return fmt.Errorf("dictionary update sequence element #%d has unknown length (%s)", i, pair.Type())
} else if length != 2 {
return fmt.Errorf("dictionary update sequence element #%d has length %d, want 2", i, length)
}
var k, v starlark.Value
iter2.Next(&k)
iter2.Next(&v)
return dict.SetKey(k, v)
}()
if iterErr != nil {
return nil, iterErr
}
}
}

View File

@ -141,27 +141,28 @@ func (d FieldDict) Clear() error {
return nil
}
func (d FieldDict) PopItem() (v starlark.Value, err error) {
func (d FieldDict) PopItem() (starlark.Value, error) {
if d.fieldIterCount > 0 {
return nil, fmt.Errorf("cannot delete during iteration")
}
for _, field := range d.metric.FieldList() {
k := field.Key
v := field.Value
d.metric.RemoveField(k)
sk := starlark.String(k)
sv, err := asStarlarkValue(v)
if err != nil {
return nil, fmt.Errorf("could not convert to starlark value")
}
return starlark.Tuple{sk, sv}, nil
if len(d.metric.FieldList()) == 0 {
return nil, errors.New("popitem(): field dictionary is empty")
}
return nil, errors.New("popitem(): field dictionary is empty")
field := d.metric.FieldList()[0]
k := field.Key
v := field.Value
d.metric.RemoveField(k)
sk := starlark.String(k)
sv, err := asStarlarkValue(v)
if err != nil {
return nil, fmt.Errorf("could not convert to starlark value")
}
return starlark.Tuple{sk, sv}, nil
}
func (d FieldDict) Delete(k starlark.Value) (v starlark.Value, found bool, err error) {

View File

@ -1,4 +1,4 @@
package starlark //nolint - Needed to avoid getting import-shadowing: The name 'starlark' shadows an import name (revive)
package starlark
import (
"errors"
@ -6,14 +6,14 @@ import (
"strings"
"github.com/influxdata/telegraf"
"go.starlark.net/lib/json"
"go.starlark.net/lib/math"
"go.starlark.net/lib/time"
"go.starlark.net/resolve"
"go.starlark.net/starlark"
"go.starlark.net/starlarkjson"
)
type StarlarkCommon struct {
type Common struct {
Source string `toml:"source"`
Script string `toml:"script"`
Constants map[string]interface{} `toml:"constants"`
@ -27,7 +27,7 @@ type StarlarkCommon struct {
parameters map[string]starlark.Tuple
}
func (s *StarlarkCommon) Init() error {
func (s *Common) Init() error {
if s.Source == "" && s.Script == "" {
return errors.New("one of source or script must be set")
}
@ -51,7 +51,7 @@ func (s *StarlarkCommon) Init() error {
return err
}
program, err := s.sourceProgram(builtins, "")
program, err := s.sourceProgram(builtins)
if err != nil {
return err
}
@ -76,12 +76,12 @@ func (s *StarlarkCommon) Init() error {
return nil
}
func (s *StarlarkCommon) GetParameters(name string) (starlark.Tuple, bool) {
func (s *Common) GetParameters(name string) (starlark.Tuple, bool) {
parameters, found := s.parameters[name]
return parameters, found
}
func (s *StarlarkCommon) AddFunction(name string, params ...starlark.Value) error {
func (s *Common) AddFunction(name string, params ...starlark.Value) error {
globalFn, found := s.globals[name]
if !found {
return fmt.Errorf("%s is not defined", name)
@ -96,16 +96,15 @@ func (s *StarlarkCommon) AddFunction(name string, params ...starlark.Value) erro
return fmt.Errorf("%s function must take %d parameter(s)", name, len(params))
}
p := make(starlark.Tuple, len(params))
for i, param := range params {
p[i] = param
}
copy(p, params)
s.functions[name] = fn
s.parameters[name] = params
return nil
}
// Add all the constants defined in the plugin as constants of the script
func (s *StarlarkCommon) addConstants(builtins *starlark.StringDict) error {
func (s *Common) addConstants(builtins *starlark.StringDict) error {
for key, val := range s.Constants {
sVal, err := asStarlarkValue(val)
if err != nil {
@ -116,7 +115,7 @@ func (s *StarlarkCommon) addConstants(builtins *starlark.StringDict) error {
return nil
}
func (s *StarlarkCommon) sourceProgram(builtins starlark.StringDict, filename string) (*starlark.Program, error) {
func (s *Common) sourceProgram(builtins starlark.StringDict) (*starlark.Program, error) {
var src interface{}
if s.Source != "" {
src = s.Source
@ -126,7 +125,7 @@ func (s *StarlarkCommon) sourceProgram(builtins starlark.StringDict, filename st
}
// Call calls the function corresponding to the given name.
func (s *StarlarkCommon) Call(name string) (starlark.Value, error) {
func (s *Common) Call(name string) (starlark.Value, error) {
fn, ok := s.functions[name]
if !ok {
return nil, fmt.Errorf("function %q does not exist", name)
@ -138,13 +137,13 @@ func (s *StarlarkCommon) Call(name string) (starlark.Value, error) {
return starlark.Call(s.thread, fn, args, nil)
}
func (s *StarlarkCommon) LogError(err error) {
if err, ok := err.(*starlark.EvalError); ok {
for _, line := range strings.Split(err.Backtrace(), "\n") {
func (s *Common) LogError(err error) {
if evalErr, ok := err.(*starlark.EvalError); ok {
for _, line := range strings.Split(evalErr.Backtrace(), "\n") {
s.Log.Error(line)
}
} else {
s.Log.Error(err.Msg)
s.Log.Error(err)
}
}
@ -152,7 +151,7 @@ func LoadFunc(module string, logger telegraf.Logger) (starlark.StringDict, error
switch module {
case "json.star":
return starlark.StringDict{
"json": starlarkjson.Module,
"json": json.Module,
}, nil
case "logging.star":
return starlark.StringDict{

View File

@ -94,14 +94,11 @@ Leap status : Not synchronized
if cmd == "chronyc" {
if args[0] == "tracking" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, lookup+mockData)
} else {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, noLookup+mockData)
}
} else {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)

View File

@ -209,7 +209,6 @@ func runCounterProgram() error {
i := 0
serializer, err := serializers.NewInfluxSerializer()
if err != nil {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintln(os.Stderr, "ERR InfluxSerializer failed to load")
return err
}
@ -227,7 +226,6 @@ func runCounterProgram() error {
b, err := serializer.Serialize(m)
if err != nil {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err)
return err
}

View File

@ -56,7 +56,7 @@ var (
// New creates a new shim interface
func New() *Shim {
_, _ = fmt.Fprintf(os.Stderr, "%s is deprecated; please change your import to %s\n", oldpkg, newpkg)
fmt.Fprintf(os.Stderr, "%s is deprecated; please change your import to %s\n", oldpkg, newpkg)
return &Shim{
stdin: os.Stdin,
stdout: os.Stdout,

View File

@ -102,30 +102,25 @@ func TestHelperProcess(_ *testing.T) {
cmd, args := args[3], args[4:]
if !strings.HasSuffix(cmd, "fail2ban-client") {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // os.Exit called intentionally
os.Exit(1)
}
if len(args) == 1 && args[0] == "status" {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0)
} else if len(args) == 2 && args[0] == "status" {
if args[1] == "sshd" {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusSshdOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0)
} else if args[1] == "postfix" {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusPostfixOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0)
} else if args[1] == "dovecot" {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusDovecotOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0)

View File

@ -95,7 +95,6 @@ func setUpTestMux() http.Handler {
mux.HandleFunc("/good", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Server", "MyTestServer")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
//nolint:errcheck,revive
fmt.Fprintf(w, "hit the good page!")
})
mux.HandleFunc("/invalidUTF8", func(w http.ResponseWriter, req *http.Request) {
@ -103,11 +102,9 @@ func setUpTestMux() http.Handler {
w.Write([]byte{0xff, 0xfe, 0xfd})
})
mux.HandleFunc("/noheader", func(w http.ResponseWriter, req *http.Request) {
//nolint:errcheck,revive
fmt.Fprintf(w, "hit the good page!")
})
mux.HandleFunc("/jsonresponse", func(w http.ResponseWriter, req *http.Request) {
//nolint:errcheck,revive
fmt.Fprintf(w, "\"service_status\": \"up\", \"healthy\" : \"true\"")
})
mux.HandleFunc("/badredirect", func(w http.ResponseWriter, req *http.Request) {
@ -118,7 +115,6 @@ func setUpTestMux() http.Handler {
http.Error(w, "method wasn't post", http.StatusMethodNotAllowed)
return
}
//nolint:errcheck,revive
fmt.Fprintf(w, "used post correctly!")
})
mux.HandleFunc("/musthaveabody", func(w http.ResponseWriter, req *http.Request) {
@ -133,7 +129,6 @@ func setUpTestMux() http.Handler {
http.Error(w, "body was empty", http.StatusBadRequest)
return
}
//nolint:errcheck,revive
fmt.Fprintf(w, "sent a body!")
})
mux.HandleFunc("/twosecondnap", func(w http.ResponseWriter, req *http.Request) {

View File

@ -376,10 +376,8 @@ OS RealTime Mod | 0x00 | ok
// Ignore the returned errors for the mocked interface as tests will fail anyway
if cmd == "ipmitool" {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, mockData)
} else {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)
@ -576,10 +574,8 @@ Power Supply 1 | 03h | ok | 10.1 | 110 Watts, Presence detected
// Ignore the returned errors for the mocked interface as tests will fail anyway
if cmd == "ipmitool" {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, mockData)
} else {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)

View File

@ -747,7 +747,7 @@ func TestFillFields(t *testing.T) {
func setupServer(resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintln(w, resp)
fmt.Fprintln(w, resp)
}))
}

View File

@ -146,7 +146,6 @@ func setupServer(resp string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the tests will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, resp)
}))
}

View File

@ -110,16 +110,12 @@ func TestHelperProcess(_ *testing.T) {
args := os.Args
cmd := args[3]
if cmd == "/usr/sbin/pvs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockPVSData)
} else if cmd == "/usr/sbin/vgs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockVGSData)
} else if cmd == "/usr/sbin/lvs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockLVSData)
} else {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)
@ -194,16 +190,12 @@ func TestHelperProcessNoLVM(_ *testing.T) {
args := os.Args
cmd := args[3]
if cmd == "/usr/sbin/pvs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockPVSData)
} else if cmd == "/usr/sbin/vgs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockVGSData)
} else if cmd == "/usr/sbin/lvs" {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, mockLVSData)
} else {
//nolint:errcheck,revive // test will fail anyway
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)

View File

@ -111,7 +111,7 @@ func (r *response) WriteHeader(code int) {
r.header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
_, _ = fmt.Fprintf(r.w, "Status: %d %s\r\n", code, http.StatusText(code))
fmt.Fprintf(r.w, "Status: %d %s\r\n", code, http.StatusText(code))
_ = r.header.Write(r.w)
_, _ = r.w.WriteString("\r\n")
}

View File

@ -27,7 +27,6 @@ func (s statServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Content-Length", fmt.Sprint(len(outputSample)))
// Ignore the returned error as the tests will fail anyway
//nolint:errcheck,revive
fmt.Fprint(w, outputSample)
}

View File

@ -371,10 +371,8 @@ Vcore Voltage:
cmd, _ := args[3], args[4:]
if cmd == "sensors" {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, mockData)
} else {
//nolint:errcheck,revive
fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1)

View File

@ -44,14 +44,11 @@ func TestMockExecCommand(_ *testing.T) {
mcr, ok := mockedCommandResults[cmd0]
if !ok {
cv := fmt.Sprintf("%#v", cmd)[8:] // trim `[]string` prefix
//nolint:errcheck,revive
fmt.Fprintf(os.Stderr, "Unmocked command. Please add the following to `mockedCommands` in snmp_mocks_generate.go, and then run `go generate`:\n\t%s,\n", cv)
//nolint:revive // error code is important for this "test"
os.Exit(1)
}
//nolint:errcheck,revive
fmt.Printf("%s", mcr.stdout)
//nolint:errcheck,revive
fmt.Fprintf(os.Stderr, "%s", mcr.stderr)
if mcr.exitError {
//nolint:revive // error code is important for this "test"

View File

@ -111,22 +111,18 @@ func createMockServer() *httptest.Server {
if strings.Contains(r.URL.Path, "/solr/admin/cores") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, statusResponse)
} else if strings.Contains(r.URL.Path, "solr/main/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, mBeansMainResponse)
} else if strings.Contains(r.URL.Path, "solr/core1/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, mBeansCore1Response)
} else {
w.WriteHeader(http.StatusNotFound)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, "nope")
}
}))
@ -138,22 +134,18 @@ func createMockNoCoreDataServer() *httptest.Server {
if strings.Contains(r.URL.Path, "/solr/admin/cores") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, statusResponse)
} else if strings.Contains(r.URL.Path, "solr/main/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, nodata)
} else if strings.Contains(r.URL.Path, "solr/core1/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, nodata)
} else {
w.WriteHeader(http.StatusNotFound)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, "nope")
}
}))
@ -164,22 +156,18 @@ func createMockSolr3Server() *httptest.Server {
if strings.Contains(r.URL.Path, "/solr/admin/cores") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, statusResponse)
} else if strings.Contains(r.URL.Path, "solr/main/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, mBeansSolr3MainResponse)
} else if strings.Contains(r.URL.Path, "solr/core1/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, mBeansSolr3MainResponse)
} else {
w.WriteHeader(http.StatusNotFound)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, "nope")
}
}))
@ -190,17 +178,14 @@ func createMockSolr7Server() *httptest.Server {
if strings.Contains(r.URL.Path, "/solr/admin/cores") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, statusResponse)
} else if strings.Contains(r.URL.Path, "solr/main/admin") {
w.WriteHeader(http.StatusOK)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, mBeansSolr7Response)
} else {
w.WriteHeader(http.StatusNotFound)
// Ignore the returned error as the test will fail anyway
//nolint:errcheck,revive
fmt.Fprintln(w, "nope")
}
}))

View File

@ -154,7 +154,6 @@ func BenchmarkUDP(b *testing.B) {
func sendRequests(conn net.Conn, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 25000; i++ {
//nolint:errcheck,revive
fmt.Fprint(conn, testMsg)
}
}

View File

@ -86,7 +86,6 @@ func formatUptime(uptime uint64) string {
s = "s"
}
// This will always succeed, so skip checking the error
//nolint:errcheck,revive
fmt.Fprintf(w, "%d day%s, ", days, s)
}
@ -96,7 +95,6 @@ func formatUptime(uptime uint64) string {
minutes %= 60
// This will always succeed, so skip checking the error
//nolint:errcheck,revive
fmt.Fprintf(w, "%2d:%02d", hours, minutes)
// This will always succeed, so skip checking the error

View File

@ -187,7 +187,6 @@ func (t *TCPListener) tcpListen() {
// refuser refuses a TCP connection
func (t *TCPListener) refuser(conn *net.TCPConn) {
// Tell the connection why we are closing.
//nolint:errcheck,revive
fmt.Fprintf(conn, "Telegraf maximum concurrent TCP connections (%d)"+
" reached, closing.\nYou may want to increase max_tcp_connections in"+
" the Telegraf tcp listener configuration.\n", t.MaxTCPConnections)

View File

@ -241,7 +241,7 @@ func TestInit(t *testing.T) {
func TestConnect(t *testing.T) {
//mock cloudwatch logs endpoint that is used only in plugin.Connect
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w,
fmt.Fprintln(w,
`{
"logGroups": [
{
@ -281,7 +281,7 @@ func TestConnect(t *testing.T) {
func TestWrite(t *testing.T) {
//mock cloudwatch logs endpoint that is used only in plugin.Connect
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintln(w,
fmt.Fprintln(w,
`{
"logGroups": [
{

View File

@ -169,12 +169,10 @@ func runOutputConsumerProgram() {
return // stream ended
}
if parseErr, isParseError := err.(*influx.ParseError); isParseError {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr)
//nolint:revive // error code is important for this "test"
os.Exit(1)
}
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err)
//nolint:revive // error code is important for this "test"
os.Exit(1)
@ -187,7 +185,6 @@ func runOutputConsumerProgram() {
)
if !testutil.MetricEqual(expected, m) {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "metric doesn't match expected\n")
//nolint:revive // error code is important for this "test"
os.Exit(1)

View File

@ -391,7 +391,7 @@ func validStatus(status string) bool {
func adaptLog(fields interface{}, format string, a ...interface{}) string {
buf := &bytes.Buffer{}
if format != "" {
_, _ = fmt.Fprintf(buf, format, a...)
fmt.Fprintf(buf, format, a...)
}
fmtField := func(k string, v interface{}) {
format := " %s:"
@ -403,7 +403,7 @@ func adaptLog(fields interface{}, format string, a ...interface{}) string {
} else {
format += "%q"
}
_, _ = fmt.Fprintf(buf, format, k, v)
fmt.Fprintf(buf, format, k, v)
}
if ff, ok := fields.(interface {
LogFields() (map[string]interface{}, map[string][]byte)

View File

@ -135,7 +135,7 @@ func BenchmarkHttpSend(b *testing.B) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintln(w, "{}")
fmt.Fprintln(w, "{}")
}))
defer ts.Close()

View File

@ -160,12 +160,10 @@ func runCountMultiplierProgram() {
return // stream ended
}
if parseErr, isParseError := err.(*influx.ParseError); isParseError {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr)
//nolint:revive // os.Exit called intentionally
os.Exit(1)
}
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err)
//nolint:revive // os.Exit called intentionally
os.Exit(1)
@ -173,7 +171,6 @@ func runCountMultiplierProgram() {
c, found := m.GetField(fieldName)
if !found {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "metric has no %s field\n", fieldName)
//nolint:revive // os.Exit called intentionally
os.Exit(1)
@ -186,19 +183,16 @@ func runCountMultiplierProgram() {
t *= 2
m.AddField(fieldName, t)
default:
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "%s is not an unknown type, it's a %T\n", fieldName, c)
//nolint:revive // os.Exit called intentionally
os.Exit(1)
}
b, err := serializer.Serialize(m)
if err != nil {
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprintf(os.Stderr, "ERR %v\n", err)
//nolint:revive // os.Exit called intentionally
os.Exit(1)
}
//nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, string(b))
}
}

View File

@ -15,7 +15,7 @@ import (
var sampleConfig string
type Starlark struct {
common.StarlarkCommon
common.Common
results []telegraf.Metric
}
@ -25,7 +25,7 @@ func (*Starlark) SampleConfig() string {
}
func (s *Starlark) Init() error {
err := s.StarlarkCommon.Init()
err := s.Common.Init()
if err != nil {
return err
}
@ -49,7 +49,7 @@ func (s *Starlark) Start(_ telegraf.Accumulator) error {
func (s *Starlark) Add(metric telegraf.Metric, acc telegraf.Accumulator) error {
parameters, found := s.GetParameters("apply")
if !found {
return fmt.Errorf("The parameters of the apply function could not be found")
return fmt.Errorf("the parameters of the apply function could not be found")
}
parameters[0].(*common.Metric).Wrap(metric)
@ -103,7 +103,7 @@ func (s *Starlark) Add(metric telegraf.Metric, acc telegraf.Accumulator) error {
case starlark.NoneType:
metric.Drop()
default:
return fmt.Errorf("Invalid type returned: %T", rv)
return fmt.Errorf("invalid type returned: %T", rv)
}
return nil
}
@ -124,7 +124,7 @@ func containsMetric(metrics []telegraf.Metric, metric telegraf.Metric) bool {
func init() {
processors.AddStreaming("starlark", func() telegraf.StreamingProcessor {
return &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: common.LoadFunc,
},
}

View File

@ -3388,7 +3388,7 @@ func testNow(_ *starlark.Thread, _ *starlark.Builtin, _ starlark.Tuple, _ []star
func newStarlarkFromSource(source string) *Starlark {
return &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: testLoadFunc,
Log: testutil.Logger{},
Source: source,
@ -3398,7 +3398,7 @@ func newStarlarkFromSource(source string) *Starlark {
func newStarlarkFromScript(script string) *Starlark {
return &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: testLoadFunc,
Log: testutil.Logger{},
Script: script,
@ -3408,7 +3408,7 @@ func newStarlarkFromScript(script string) *Starlark {
func newStarlarkNoScript() *Starlark {
return &Starlark{
StarlarkCommon: common.StarlarkCommon{
Common: common.Common{
StarlarkLoadFunc: testLoadFunc,
Log: testutil.Logger{},
},

View File

@ -47,17 +47,17 @@ possible.
`
func usage() {
_, _ = fmt.Fprint(flag.CommandLine.Output(), description)
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "")
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "Usage:")
_, _ = fmt.Fprintln(flag.CommandLine.Output(), " custom_builder [flags]")
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "")
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "Flags:")
fmt.Fprint(flag.CommandLine.Output(), description)
fmt.Fprintln(flag.CommandLine.Output(), "")
fmt.Fprintln(flag.CommandLine.Output(), "Usage:")
fmt.Fprintln(flag.CommandLine.Output(), " custom_builder [flags]")
fmt.Fprintln(flag.CommandLine.Output(), "")
fmt.Fprintln(flag.CommandLine.Output(), "Flags:")
flag.PrintDefaults()
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "")
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "Examples:")
_, _ = fmt.Fprint(flag.CommandLine.Output(), examples)
_, _ = fmt.Fprintln(flag.CommandLine.Output(), "")
fmt.Fprintln(flag.CommandLine.Output(), "")
fmt.Fprintln(flag.CommandLine.Output(), "Examples:")
fmt.Fprint(flag.CommandLine.Output(), examples)
fmt.Fprintln(flag.CommandLine.Output(), "")
}
func main() {

View File

@ -46,13 +46,13 @@ func main() {
if help || flag.NArg() > 1 {
//nolint:revive // We cannot do anything about possible failures here
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s [options] [telegraf root dir]\n", os.Args[0])
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Options:\n")
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s [options] [telegraf root dir]\n", os.Args[0])
fmt.Fprintf(flag.CommandLine.Output(), "Options:\n")
flag.PrintDefaults()
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "\n")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), "Arguments:\n")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), " telegraf root dir (optional)\n")
_, _ = fmt.Fprintf(flag.CommandLine.Output(), " path to the root directory of telegraf (default: .)\n")
fmt.Fprintf(flag.CommandLine.Output(), "\n")
fmt.Fprintf(flag.CommandLine.Output(), "Arguments:\n")
fmt.Fprintf(flag.CommandLine.Output(), " telegraf root dir (optional)\n")
fmt.Fprintf(flag.CommandLine.Output(), " path to the root directory of telegraf (default: .)\n")
os.Exit(1)
}