Skip to content

Commit 5ec6b12

Browse files
committed
lint: fix issues of errorlint
1 parent aee8143 commit 5ec6b12

File tree

338 files changed

+2814
-2377
lines changed

Some content is hidden

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

338 files changed

+2814
-2377
lines changed

.golangci.yml

+35-20
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,11 @@ run:
3434
linters:
3535
# currently active linters:
3636
#
37-
#INFO [lintersdb] Active 49 linters: [asasalint asciicheck bidichk contextcheck decorder depguard dupword durationcheck errcheck exportloopref
38-
# gocheckcompilerdirectives gochecknoinits gochecksumtype gofmt gofumpt goimports gomoddirectives gomodguard goprintffuncname gosec gosimple govet grouper
39-
# inamedparam ineffassign makezero mirror misspell musttag nilerr nilnil nolintlint nosprintfhostport perfsprint prealloc protogetter reassign revive
40-
# sloglint staticcheck tagalign tenv testableexamples testifylint tparallel unconvert unparam unused wastedassign]
37+
# INFO [lintersdb] Active 64 linters: [asasalint asciicheck bidichk bodyclose containedctx contextcheck decorder depguard dogsled dupword durationcheck
38+
# errcheck errchkjson errorlint exportloopref forcetypeassert gci gocheckcompilerdirectives gochecknoinits gochecksumtype gocritic gofmt gofumpt goimports
39+
# gomoddirectives gomodguard goprintffuncname gosec gosimple govet grouper inamedparam ineffassign lll makezero mirror misspell musttag nakedret nilerr nilnil
40+
# noctx nolintlint nonamedreturns nosprintfhostport perfsprint prealloc predeclared protogetter reassign revive sloglint staticcheck tagalign tenv
41+
# testableexamples testifylint thelper tparallel unconvert unparam unused usestdlibvars wastedassign]
4142

4243
enable-all: true
4344

@@ -75,39 +76,23 @@ linters:
7576
- testpackage # not needed, we use the same name for test package to have access to unexposed items
7677
- wrapcheck # not needed (we allow errors from interface methods)
7778
- zerologlint # not needed (related to zerolog package)
78-
# important to have
79-
- errorlint # useful (reduce bugs), but suppress the "Use `%w` to format errors" check
80-
- forcetypeassert # useful (reduce bugs)
81-
- nakedret # very useful together with "nonamedreturns" (reduce bugs)
82-
- nonamedreturns # very useful (reduce bugs)
8379
# useful for the future
84-
- bodyclose # maybe useful (reduce bugs), exclusions for tests needed
85-
- containedctx # useful (structs are not for context wrapping)
8680
- cyclop # useful with some tweeks (better understandable code), see also gocyclo
87-
- dogsled # useful with some tweeks (e.g. exclude tests)
8881
- dupl # useful with some tweeks (reduce bugs and lines of code)
89-
- errchkjson # useful (reduce bugs)
9082
- errname # useful for common style
9183
- exhaustruct # useful with some exclusions for existing code (e.g. mavlink/common/common.go)
9284
- funlen # useful with some tweeks (reduce bugs, simplify code, better understandable code)
93-
- gci # useful (improve readability)
9485
- gocognit # useful with some tweeks (better understandable code)
9586
- goconst # useful (reduce bugs)
96-
- gocritic # useful with some exclusions for existing code (e.g. mavlink/common/common.go)
9787
- gocyclo # useful with some tweeks (better understandable code)
9888
- goheader # useful, if we introduce a common header (e.g. for copyright)
9989
- gomnd # useful with some exclusions for existing code (e.g. mavlink.go)
10090
- interfacebloat # useful with some exclusions at usage of external packages
101-
- lll # useful with some exclusions for existing code (e.g. mavlink/common/common.go)
10291
- maintidx # useful with some tweeks (better understandable code), maybe use instead "gocyclo", "gocognit" , "cyclop"
10392
- nestif # useful (reduce bugs, simplify code, better understandable code)
10493
- nlreturn # more common style, but could become annoying
105-
- noctx # maybe good (show used context explicit)
106-
- predeclared # useful (reduce bugs)
10794
- stylecheck # useful with some tweaking (e.g. underscores in names should be allowed - we use it for constants retrieved from C/C++)
10895
- tagliatelle # maybe useful with some tweaking or excluding
109-
- thelper # useful
110-
- usestdlibvars # useful
11196
- varnamelen # maybe useful with some tweaking, but many findings
11297
- whitespace # more common style, but could become annoying
11398
- wsl # more common style, but could become annoying
@@ -145,6 +130,36 @@ linters-settings:
145130
- "and"
146131
- "a"
147132

133+
errorlint:
134+
# Default: true
135+
# %v should be used by default over %w, see https://github.com/uber-go/guide/blob/master/style.md#error-wrapping
136+
errorf: false
137+
# Permit more than 1 %w verb, valid per Go 1.20 (Requires errorf:true)
138+
# Default: true
139+
errorf-multi: false
140+
141+
gci:
142+
# Section configuration to compare against.
143+
# Section names are case-insensitive and may contain parameters in ().
144+
# The default order of sections is `standard > default > custom > blank > dot`,
145+
# If `custom-order` is `true`, it follows the order of `sections` option.
146+
# Default: ["standard", "default"]
147+
sections:
148+
- standard # Standard section: captures all standard packages.
149+
- default # Default section: contains all imports that could not be matched to another section type.
150+
- prefix(gobot.io/x/gobot/) # Custom section: groups all imports with the specified Prefix.
151+
#- blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled.
152+
#- dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled.
153+
# Enable custom order of sections.
154+
# If `true`, make the section order the same as the order of `sections`.
155+
# Default: false
156+
custom-order: true
157+
158+
gocritic:
159+
disabled-checks:
160+
- assignOp # very opinionated
161+
- appendAssign # mostly used by intention
162+
148163
nolintlint:
149164
# Enable to require an explanation of nonzero length after each nolint directive.
150165
# Default: false

api/api.go

+25-21
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package api
22

33
import (
44
"encoding/json"
5-
"errors"
65
"fmt"
76
"log"
87
"net/http"
@@ -11,6 +10,7 @@ import (
1110
"time"
1211

1312
"github.com/bmizerany/pat"
13+
1414
"gobot.io/x/gobot/v2"
1515
"gobot.io/x/gobot/v2/api/robeaux"
1616
)
@@ -178,12 +178,14 @@ func (a *API) robeaux(res http.ResponseWriter, req *http.Request) {
178178
http.Error(res, err.Error(), http.StatusNotFound)
179179
return
180180
}
181-
t := strings.Split(path, ".")
182-
if t[len(t)-1] == "js" {
181+
split := strings.Split(path, ".")
182+
ext := split[len(split)-1]
183+
switch ext {
184+
case "js":
183185
res.Header().Set("Content-Type", "text/javascript; charset=utf-8")
184-
} else if t[len(t)-1] == "css" {
186+
case "css":
185187
res.Header().Set("Content-Type", "text/css; charset=utf-8")
186-
} else if t[len(t)-1] == "html" {
188+
case "html":
187189
res.Header().Set("Content-Type", "text/html; charset=utf-8")
188190
}
189191
if _, err := res.Write(buf); err != nil {
@@ -269,9 +271,11 @@ func (a *API) robotDeviceEvent(res http.ResponseWriter, req *http.Request) {
269271
device := a.master.Robot(req.URL.Query().Get(":robot")).
270272
Device(req.URL.Query().Get(":device"))
271273

274+
//nolint:forcetypeassert // no error return value, so there is no better way
272275
if event := a.master.Robot(req.URL.Query().Get(":robot")).
273276
Device(req.URL.Query().Get(":device")).(gobot.Eventer).
274277
Event(req.URL.Query().Get(":event")); len(event) > 0 {
278+
//nolint:forcetypeassert // no error return value, so there is no better way
275279
if err := device.(gobot.Eventer).On(event, func(data interface{}) {
276280
d, _ := json.Marshal(data)
277281
dataChan <- string(d)
@@ -345,6 +349,7 @@ func (a *API) executeRobotDeviceCommand(res http.ResponseWriter, req *http.Reque
345349
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
346350
} else {
347351
a.executeCommand(
352+
//nolint:forcetypeassert // no error return value, so there is no better way
348353
a.master.Robot(req.URL.Query().Get(":robot")).
349354
Device(req.URL.Query().Get(":device")).(gobot.Commander).
350355
Command(req.URL.Query().Get(":command")),
@@ -387,7 +392,10 @@ func (a *API) executeCommand(f func(map[string]interface{}) interface{},
387392

388393
// writeJSON writes `j` as JSON in response
389394
func (a *API) writeJSON(j interface{}, res http.ResponseWriter) {
390-
data, _ := json.Marshal(j)
395+
data, err := json.Marshal(j)
396+
if err != nil {
397+
panic(err)
398+
}
391399
res.Header().Set("Content-Type", "application/json; charset=utf-8")
392400
if _, err := res.Write(data); err != nil {
393401
panic(err)
@@ -401,29 +409,25 @@ func (a *API) Debug() {
401409
})
402410
}
403411

404-
func (a *API) jsonRobotFor(name string) (jrobot *gobot.JSONRobot, err error) {
412+
func (a *API) jsonRobotFor(name string) (*gobot.JSONRobot, error) {
405413
if robot := a.master.Robot(name); robot != nil {
406-
jrobot = gobot.NewJSONRobot(robot)
407-
} else {
408-
err = errors.New("No Robot found with the name " + name)
414+
return gobot.NewJSONRobot(robot), nil
409415
}
410-
return
416+
return nil, fmt.Errorf("No Robot found with the name %s", name)
411417
}
412418

413-
func (a *API) jsonDeviceFor(robot string, name string) (jdevice *gobot.JSONDevice, err error) {
419+
func (a *API) jsonDeviceFor(robot string, name string) (*gobot.JSONDevice, error) {
414420
if device := a.master.Robot(robot).Device(name); device != nil {
415-
jdevice = gobot.NewJSONDevice(device)
416-
} else {
417-
err = errors.New("No Device found with the name " + name)
421+
return gobot.NewJSONDevice(device), nil
418422
}
419-
return
423+
424+
return nil, fmt.Errorf("No Device found with the name %s", name)
420425
}
421426

422-
func (a *API) jsonConnectionFor(robot string, name string) (jconnection *gobot.JSONConnection, err error) {
427+
func (a *API) jsonConnectionFor(robot string, name string) (*gobot.JSONConnection, error) {
423428
if connection := a.master.Robot(robot).Connection(name); connection != nil {
424-
jconnection = gobot.NewJSONConnection(connection)
425-
} else {
426-
err = errors.New("No Connection found with the name " + name)
429+
return gobot.NewJSONConnection(connection), nil
427430
}
428-
return
431+
432+
return nil, fmt.Errorf("No Connection found with the name %s", name)
429433
}

api/api_test.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//nolint:forcetypeassert,usestdlibvars,bodyclose,noctx // ok here
12
package api
23

34
import (
@@ -12,6 +13,7 @@ import (
1213
"time"
1314

1415
"github.com/stretchr/testify/assert"
16+
1517
"gobot.io/x/gobot/v2"
1618
)
1719

@@ -413,7 +415,7 @@ func TestRobotDeviceEvent(t *testing.T) {
413415
data, _ := reader.ReadString('\n')
414416
assert.Equal(t, "data: \"event-data\"\n", data)
415417
done = true
416-
case <-time.After(100 * time.Millisecond):
418+
case <-time.After(200 * time.Millisecond):
417419
t.Error("Not receiving data")
418420
done = true
419421
}

api/basic_auth_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//nolint:usestdlibvars,noctx // ok here
12
package api
23

34
import (

api/cors.go

+6-7
Original file line numberDiff line numberDiff line change
@@ -38,23 +38,22 @@ func AllowRequestsFrom(allowedOrigins ...string) http.HandlerFunc {
3838
}
3939

4040
// isOriginAllowed returns true if origin matches an allowed origin pattern.
41-
func (c *CORS) isOriginAllowed(origin string) (allowed bool) {
41+
func (c *CORS) isOriginAllowed(origin string) bool {
4242
for _, allowedOriginPattern := range c.allowOriginPatterns {
43-
allowed, _ = regexp.MatchString(allowedOriginPattern, origin)
44-
if allowed {
45-
return
43+
if allowed, _ := regexp.MatchString(allowedOriginPattern, origin); allowed {
44+
return true
4645
}
4746
}
48-
return
47+
return false
4948
}
5049

5150
// generatePatterns generates regex expression for AllowOrigins
5251
func (c *CORS) generatePatterns() {
5352
if c.AllowOrigins != nil {
5453
for _, origin := range c.AllowOrigins {
5554
pattern := regexp.QuoteMeta(origin)
56-
pattern = strings.Replace(pattern, "\\*", ".*", -1)
57-
pattern = strings.Replace(pattern, "\\?", ".", -1)
55+
pattern = strings.ReplaceAll(pattern, "\\*", ".*")
56+
pattern = strings.ReplaceAll(pattern, "\\?", ".")
5857
c.allowOriginPatterns = append(c.allowOriginPatterns, "^"+pattern+"$")
5958
}
6059
}

api/cors_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//nolint:usestdlibvars,noctx // ok here
12
package api
23

34
import (

api/helpers_test.go

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//nolint:forcetypeassert // ok here
12
package api
23

34
import (
@@ -28,8 +29,8 @@ type testDriver struct {
2829
gobot.Eventer
2930
}
3031

31-
func (t *testDriver) Start() (err error) { return }
32-
func (t *testDriver) Halt() (err error) { return }
32+
func (t *testDriver) Start() error { return nil }
33+
func (t *testDriver) Halt() error { return nil }
3334
func (t *testDriver) Name() string { return t.name }
3435
func (t *testDriver) SetName(n string) { t.name = n }
3536
func (t *testDriver) Pin() string { return t.pin }
@@ -65,15 +66,15 @@ type testAdaptor struct {
6566
}
6667

6768
var (
68-
testAdaptorConnect = func() (err error) { return }
69-
testAdaptorFinalize = func() (err error) { return }
69+
testAdaptorConnect = func() error { return nil }
70+
testAdaptorFinalize = func() error { return nil }
7071
)
7172

72-
func (t *testAdaptor) Finalize() (err error) { return testAdaptorFinalize() }
73-
func (t *testAdaptor) Connect() (err error) { return testAdaptorConnect() }
74-
func (t *testAdaptor) Name() string { return t.name }
75-
func (t *testAdaptor) SetName(n string) { t.name = n }
76-
func (t *testAdaptor) Port() string { return t.port }
73+
func (t *testAdaptor) Finalize() error { return testAdaptorFinalize() }
74+
func (t *testAdaptor) Connect() error { return testAdaptorConnect() }
75+
func (t *testAdaptor) Name() string { return t.name }
76+
func (t *testAdaptor) SetName(n string) { t.name = n }
77+
func (t *testAdaptor) Port() string { return t.port }
7778

7879
func newTestAdaptor(name string, port string) *testAdaptor {
7980
return &testAdaptor{

connection.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@ func (c *Connections) Each(f func(Connection)) {
4040
}
4141

4242
// Start calls Connect on each Connection in c
43-
func (c *Connections) Start() (err error) {
43+
func (c *Connections) Start() error {
4444
log.Println("Starting connections...")
45+
var err error
4546
for _, connection := range *c {
4647
info := "Starting connection " + connection.Name()
4748

@@ -59,7 +60,8 @@ func (c *Connections) Start() (err error) {
5960
}
6061

6162
// Finalize calls Finalize on each Connection in c
62-
func (c *Connections) Finalize() (err error) {
63+
func (c *Connections) Finalize() error {
64+
var err error
6365
for _, connection := range *c {
6466
if cerr := connection.Finalize(); cerr != nil {
6567
err = multierror.Append(err, cerr)

device.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,9 @@ func (d *Devices) Each(f func(Device)) {
5353
}
5454

5555
// Start calls Start on each Device in d
56-
func (d *Devices) Start() (err error) {
56+
func (d *Devices) Start() error {
5757
log.Println("Starting devices...")
58+
var err error
5859
for _, device := range *d {
5960
info := "Starting device " + device.Name()
6061

@@ -71,7 +72,8 @@ func (d *Devices) Start() (err error) {
7172
}
7273

7374
// Halt calls Halt on each Device in d
74-
func (d *Devices) Halt() (err error) {
75+
func (d *Devices) Halt() error {
76+
var err error
7577
for _, device := range *d {
7678
if derr := device.Halt(); derr != nil {
7779
err = multierror.Append(err, derr)

doc.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
// Copyright 2014-2018 The Hybrid Group. All rights reserved.
22

33
/*
4-
Package gobot is the primary entrypoint for Gobot (http://gobot.io), a framework for robotics, physical computing, and the Internet of Things written using the Go programming language .
4+
Package gobot is the primary entrypoint for Gobot (http://gobot.io), a framework for robotics, physical computing, and
5+
the Internet of Things written using the Go programming language .
56
6-
It provides a simple, yet powerful way to create solutions that incorporate multiple, different hardware devices at the same time.
7+
It provides a simple, yet powerful way to create solutions that incorporate multiple, different hardware devices at the
8+
same time.
79
810
# Classic Gobot
911
@@ -40,7 +42,8 @@ Here is a "Classic Gobot" program that blinks an LED using an Arduino:
4042
4143
# Metal Gobot
4244
43-
You can also use Metal Gobot and pick and choose from the various Gobot packages to control hardware with nothing but pure idiomatic Golang code. For example:
45+
You can also use Metal Gobot and pick and choose from the various Gobot packages to control hardware with nothing but
46+
pure idiomatic Golang code. For example:
4447
4548
package main
4649

drivers/aio/aio.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,5 @@ type AnalogReader interface {
2828
// AnalogWriter interface represents an Adaptor which has AnalogWrite capabilities
2929
type AnalogWriter interface {
3030
// gobot.Adaptor
31-
AnalogWrite(pin string, val int) (err error)
31+
AnalogWrite(pin string, val int) error
3232
}

0 commit comments

Comments
 (0)