Skip to content

Commit 6e852b3

Browse files
Danielius1922Daniel Adam
authored andcommitted
Update golangci-lint configuration and fix issues
1 parent 0870d2c commit 6e852b3

Some content is hidden

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

43 files changed

+294
-184
lines changed

.golangci.yml

Lines changed: 55 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,46 @@
11
linters-settings:
2-
govet:
3-
check-shadowing: true
42
exhaustive:
53
default-signifies-exhaustive: true
64
gocyclo:
75
min-complexity: 15
86
gomoddirectives:
97
replace-allow-list:
108
- github.com/pion/dtls/v2
9+
govet:
10+
enable:
11+
- nilness
12+
- shadow
1113
gomodguard:
1214
blocked:
1315
modules:
1416
- github.com/pkg/errors:
1517
recommendations:
1618
- errors
1719
stylecheck:
18-
go: "1.18"
1920
checks: ["all", "-ST1000" , "-ST1003"]
2021

22+
2123
linters:
2224
enable:
25+
- asasalint # Check for pass []any as any in variadic func(...any)
2326
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
2427
- bidichk # Checks for dangerous unicode character sequences
25-
# - bodyclose # checks whether HTTP response body is closed successfully
26-
# - contextcheck # check the function whether use a non-inherited context
27-
- decorder # check declaration order and count of types, constants, variables and functions
28-
# - depguard # Go linter that checks if package imports are in a list of acceptable packages
28+
- bodyclose # Checks whether HTTP response body is closed successfully
29+
# - copyloopvar # Detects places where loop variables are copied
30+
- decorder # Check declaration order and count of types, constants, variables and functions
2931
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
3032
- dupl # Tool for code clone detection
31-
- durationcheck # check for two durations multiplied together
33+
- dupword # A linter that checks for duplicate words in the source code (usually miswritten)
34+
- durationcheck # Check for two durations multiplied together
3235
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
3336
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted.
3437
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
3538
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
36-
- exhaustive # check exhaustiveness of enum switch statements
39+
- execinquery # Execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds.
3740
- exportloopref # checks for pointers to enclosing loop variables
38-
# - forbidigo # Forbids identifiers
3941
- forcetypeassert # finds forced type assertions
4042
- gci # Gci control golang package import order and make it always deterministic.
41-
# - gochecknoglobals # Checks that no globals are present in Go code
42-
# - gochecknoinits # Checks that no init functions are present in Go code
43+
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid.
4344
- gocognit # Computes and checks the cognitive complexity of functions
4445
- goconst # Finds repeated strings that could be replaced by a constant
4546
- gocritic # The most opinionated Go source code linter
@@ -54,51 +55,75 @@ linters:
5455
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
5556
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
5657
- gosec # Inspects source code for security problems
58+
- gosmopolitan # Report certain i18n/l10n anti-patterns in your Go codebase
5759
- gosimple # Linter for Go source code that specializes in simplifying a code
5860
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
59-
- grouper # An analyzer to analyze expression groups.
61+
- grouper # An analyzer to analyze expression groups
6062
- importas # Enforces consistent import aliases
6163
- ineffassign # Detects when assignments to existing variables are not used
64+
# - intrange # Intrange is a linter to find places where for loops could make use of an integer range
65+
- loggercheck # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).
66+
- makezero # Finds slice declarations with non-zero initial length
67+
- mirror # Reports wrong mirror patterns of bytes/strings usage
6268
- misspell # Finds commonly misspelled English words in comments
6369
- nakedret # Finds naked returns in functions greater than a specified function length
70+
- nestif # Reports deeply nested if statements
6471
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
6572
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
66-
# - noctx # noctx finds sending http request without context.Context
73+
- noctx # noctx finds sending http request without context.Context
6774
- nolintlint # Reports ill-formed or insufficient nolint directives
68-
# - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
75+
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL
76+
- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative.
77+
- prealloc # Finds slice declarations that could potentially be preallocated
6978
- predeclared # find code that shadows one of Go's predeclared identifiers
70-
# - revive # golint replacement, finds style mistakes
79+
- protogetter # Reports direct reads from proto message fields when getters should be used.
80+
- revive # golint replacement, finds style mistakes
81+
- reassign # Checks that package variables are not reassigned
82+
- sloglint # Ensure consistent code style when using log/slog
83+
- spancheck # Checks for mistakes with OpenTelemetry/Census spans
7184
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
7285
- stylecheck # Stylecheck is a replacement for golint
86+
- tagliatelle # Checks the struct tags.
7387
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
74-
# - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
88+
- testableexamples # linter checks if examples are testable (have an expected output)
89+
- testifylint # Checks usage of github.com/stretchr/testify.
90+
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
7591
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
7692
- unconvert # Remove unnecessary type conversions
7793
- unparam # Reports unused function parameters
7894
- unused # Checks Go code for unused constants, variables, functions and types
79-
# - wastedassign # wastedassign finds wasted assignment statements
95+
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library.
96+
- wastedassign # wastedassign finds wasted assignment statements
8097
- whitespace # Tool for detection of leading and trailing whitespace
81-
- makezero # Finds slice declarations with non-zero initial length
82-
- nestif # Reports deeply nested if statements
83-
- prealloc # Finds slice declarations that could potentially be preallocated
84-
- tagliatelle # Checks the struct tags.
85-
- testpackage # linter that makes you use a separate _test package
8698
disable:
87-
- structcheck # Finds unused struct fields
8899
- containedctx # containedctx is a linter that detects struct contained context.Context field
100+
- contextcheck # check the function whether use a non-inherited context
89101
- cyclop # checks function and package cyclomatic complexity
102+
- depguard # Go linter that checks if package imports are in a list of acceptable packages
103+
- exhaustive # Check exhaustiveness of enum switch statements
90104
- exhaustivestruct # Checks if all struct's fields are initialized
105+
- exhaustruct # Checks if all structure fields are initialized.
106+
- forbidigo # Forbids identifiers
91107
- funlen # Tool for detection of long functions
108+
- gochecknoglobals # Checks that no globals are present in Go code
109+
- gochecknoinits # Checks that no init functions are present in Go code
92110
- godot # Check if comments end in a period
93111
- gomnd # An analyzer to detect magic numbers.
112+
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
113+
- inamedparam # Reports interfaces with unnamed method parameters.
114+
- interfacebloat # A linter that checks the number of methods inside an interface
94115
- ireturn # Accept Interfaces, Return Concrete Types
95116
- lll # Reports long lines
96117
- maintidx # maintidx measures the maintainability index of each function.
97118
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
98119
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
120+
- nonamedreturns # Reports all named returns
121+
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
99122
- promlinter # Check Prometheus metrics naming via promlint
100123
- rowserrcheck # checks whether Err of rows is checked successfully
101124
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
125+
- tagalign # Check that struct tags are well aligned.
126+
- testpackage # linter that makes you use a separate _test package
102127
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
103128
- varnamelen # checks that the length of a variable's name matches its scope
104129
- wrapcheck # Checks that errors returned from external packages are wrapped
@@ -110,11 +135,16 @@ linters:
110135

111136
issues:
112137
exclude-use-default: false
138+
exclude-dirs:
139+
- dependency
113140
exclude-rules:
114141
# Allow complex tests, better to be self contained
115142
- path: _test\.go
116143
linters:
117144
- goconst
145+
- text: "var-naming:|exported:|package-comments:"
146+
linters:
147+
- revive
118148

119149
run:
120-
skip-dirs-use-default: false
150+
go: "1.20"

pb/get_configuration.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func (c *UserAgent) Clone() *UserAgent {
3535
return nil
3636
}
3737
return &UserAgent{
38-
CsrChallengeStateExpiration: c.CsrChallengeStateExpiration,
38+
CsrChallengeStateExpiration: c.GetCsrChallengeStateExpiration(),
3939
}
4040
}
4141

@@ -102,7 +102,7 @@ func (r *GetConfigurationResponse) Clone() *GetConfigurationResponse {
102102
CommitHash: r.GetBuildInfo().GetCommitHash(),
103103
CommitDate: r.GetBuildInfo().GetCommitDate(),
104104
ReleaseUrl: r.GetBuildInfo().GetReleaseUrl(),
105-
RemoteProvisioning: r.RemoteProvisioning.Clone(),
105+
RemoteProvisioning: r.GetRemoteProvisioning().Clone(),
106106
BuildInfo: r.GetBuildInfo().Clone(),
107107
Ui: r.GetUi().Clone(),
108108
}

service/config/config.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package config
1818

1919
import (
20+
"errors"
2021
"fmt"
2122

2223
"github.com/plgd-dev/client-application/service/config/device"
@@ -38,7 +39,7 @@ type Config struct {
3839

3940
func New(configPath string) (Config, error) {
4041
if configPath == "" {
41-
return Config{}, fmt.Errorf("path to config is empty")
42+
return Config{}, errors.New("path to config is empty")
4243
}
4344
var cfg Config
4445
if err := config.LoadAndValidateConfig(&cfg); err != nil {
@@ -85,7 +86,7 @@ type APIsConfig struct {
8586

8687
func (c *APIsConfig) Validate() error {
8788
if !c.HTTP.Enabled && !c.GRPC.Enabled {
88-
return fmt.Errorf("http or grpc must be enabled")
89+
return errors.New("http or grpc must be enabled")
8990
}
9091
if c.HTTP.Enabled {
9192
if err := c.HTTP.Validate(); err != nil {

service/device/authenticationPreSharedKey.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func (s *authenticationPreSharedKey) DialDTLS(ctx context.Context, addr string,
6868
idBin, _ := subjectUUID.MarshalBinary()
6969
dtlsCfg := &dtls.Config{
7070
PSKIdentityHint: idBin,
71-
PSK: func(b []byte) ([]byte, error) {
71+
PSK: func([]byte) ([]byte, error) {
7272
// iotivity-lite supports only 16-byte PSK
7373
return toKeyBin(key), nil
7474
},
@@ -77,7 +77,7 @@ func (s *authenticationPreSharedKey) DialDTLS(ctx context.Context, addr string,
7777
return coap.DialUDPSecure(ctx, addr, dtlsCfg, opts...)
7878
}
7979

80-
func (s *authenticationPreSharedKey) DialTLS(ctx context.Context, addr string, tlsCfg *tls.Config, opts ...tcp.Option) (*coap.ClientCloseHandler, error) {
80+
func (s *authenticationPreSharedKey) DialTLS(_ context.Context, _ string, _ *tls.Config, _ ...tcp.Option) (*coap.ClientCloseHandler, error) {
8181
return nil, errPreSharedKeyAuthentication
8282
}
8383

@@ -94,11 +94,11 @@ func (s *authenticationPreSharedKey) GetOwnOptions() ([]core.OwnOption, error) {
9494
return []core.OwnOption{core.WithPresharedKey(toKeyBin(key))}, nil
9595
}
9696

97-
func (s *authenticationPreSharedKey) GetIdentityCSR(id string) ([]byte, error) {
97+
func (s *authenticationPreSharedKey) GetIdentityCSR(_ string) ([]byte, error) {
9898
return nil, errPreSharedKeyAuthentication
9999
}
100100

101-
func (s *authenticationPreSharedKey) SetIdentityCertificate(owner string, chainPem []byte) error {
101+
func (s *authenticationPreSharedKey) SetIdentityCertificate(_ string, _ []byte) error {
102102
return errPreSharedKeyAuthentication
103103
}
104104

service/device/authenticationX509.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"crypto/tls"
2525
"crypto/x509"
2626
"encoding/pem"
27+
"errors"
2728
"fmt"
2829
"time"
2930

@@ -53,7 +54,7 @@ func newAuthenticationX509(config configDevice.Config) *authenticationX509 {
5354
func (s *authenticationX509) getTLSCertificate() (*tls.Certificate, error) {
5455
crt := s.certificate.Load()
5556
if crt == nil || crt.Leaf == nil {
56-
return nil, fmt.Errorf("certificate hasn't been set")
57+
return nil, errors.New("certificate hasn't been set")
5758
}
5859
if crt.Leaf.NotAfter.Before(time.Now()) {
5960
return nil, fmt.Errorf("certificate is not valid after %v", crt.Leaf.NotAfter)
@@ -70,7 +71,7 @@ func getRootCAFromChain(chain [][]byte) (*x509.Certificate, error) {
7071
return nil, err
7172
}
7273
if !rootCA.IsCA || rootCA.Issuer.CommonName != rootCA.Subject.CommonName {
73-
return nil, fmt.Errorf("invalid root certificate")
74+
return nil, errors.New("invalid root certificate")
7475
}
7576
return rootCA, nil
7677
}
@@ -187,7 +188,7 @@ func (s *authenticationX509) updateCertificate(crt tls.Certificate) error {
187188
func (s *authenticationX509) SetIdentityCertificate(owner string, chainPem []byte) error {
188189
privateKey := s.privateKey.Load()
189190
if privateKey == nil {
190-
return fmt.Errorf("private key is not set")
191+
return errors.New("private key is not set")
191192
}
192193
keyPem, err := encodePrivateKeyToPem(privateKey)
193194
if err != nil {

service/device/service.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"context"
2121
"crypto/tls"
2222
"crypto/x509"
23+
"errors"
2324
"fmt"
2425
"net"
2526
"sync"
@@ -86,7 +87,7 @@ func New(ctx context.Context, getConfig func() configDevice.Config, logger log.L
8687
case configDevice.AuthenticationX509:
8788
authenticationClient = newAuthenticationX509(config)
8889
case configDevice.AuthenticationUninitialized:
89-
return nil, fmt.Errorf("device is not initialized")
90+
return nil, errors.New("device is not initialized")
9091
}
9192

9293
opts := []udpServer.Option{
@@ -182,7 +183,7 @@ func (c *UDPClientConn) Context() context.Context {
182183
return cc.Context()
183184
}
184185

185-
func (s *Service) DialUDP(ctx context.Context, addr string, opts ...udp.Option) (*coap.ClientCloseHandler, error) {
186+
func (s *Service) DialUDP(_ context.Context, addr string, _ ...udp.Option) (*coap.ClientCloseHandler, error) {
186187
udpAddr, err := net.ResolveUDPAddr("udp", addr)
187188
if err != nil {
188189
return nil, err
@@ -199,12 +200,12 @@ func (s *Service) DialUDP(ctx context.Context, addr string, opts ...udp.Option)
199200
closeHandler := cc.Context().Value(&closeHandlerKey)
200201
if closeHandler == nil {
201202
_ = cc.Close()
202-
return nil, fmt.Errorf("failed to create client connection: close handler is nil")
203+
return nil, errors.New("failed to create client connection: close handler is nil")
203204
}
204205
h, ok := closeHandler.(*coap.OnCloseHandler)
205206
if !ok {
206207
_ = cc.Close()
207-
return nil, fmt.Errorf("failed to create client connection: close handler is not *coap.OnCloseHandler")
208+
return nil, errors.New("failed to create client connection: close handler is not *coap.OnCloseHandler")
208209
}
209210
return coap.NewClientCloseHandler(&UDPClientConn{Conn: cc}, h), nil
210211
}

service/grpc/clearCache.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func closeDevices(devices map[uuid.UUID]*device) error {
5353
}
5454
}
5555

56-
func (s *ClientApplicationServer) ClearCache(ctx context.Context, _ *pb.ClearCacheRequest) (*pb.ClearCacheResponse, error) {
56+
func (s *ClientApplicationServer) ClearCache(_ context.Context, _ *pb.ClearCacheRequest) (*pb.ClearCacheResponse, error) {
5757
devices := s.devices.LoadAndDeleteAll()
5858
go func(devices map[uuid.UUID]*device) {
5959
err := closeDevices(devices)

service/grpc/clearCache_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,21 +49,21 @@ func TestClientApplicationServerClearCache(t *testing.T) {
4949

5050
// get device
5151
d1, err := s.GetDevice(ctx, &pb.GetDeviceRequest{
52-
DeviceId: dev.Id,
52+
DeviceId: dev.GetId(),
5353
})
5454
require.NoError(t, err)
5555
require.Equal(t, dev, d1)
5656

5757
// own device
5858
_, err = s.OwnDevice(ctx, &pb.OwnDeviceRequest{
59-
DeviceId: dev.Id,
59+
DeviceId: dev.GetId(),
6060
})
6161
require.NoError(t, err)
6262

6363
// update resource - dtls connection will be created
6464
newName := test.DevsimName + "_new"
6565
_, err = s.UpdateResource(ctx, &pb.UpdateResourceRequest{
66-
ResourceId: commands.NewResourceID(dev.Id, configuration.ResourceURI),
66+
ResourceId: commands.NewResourceID(dev.GetId(), configuration.ResourceURI),
6767
Content: &grpcgwPb.Content{
6868
ContentType: serviceHttp.ApplicationJsonContentType,
6969
Data: []byte(`{"n":"` + newName + `"}`),
@@ -73,7 +73,7 @@ func TestClientApplicationServerClearCache(t *testing.T) {
7373

7474
// get device - udp connection will be created
7575
d1, err = s.GetDevice(ctx, &pb.GetDeviceRequest{
76-
DeviceId: dev.Id,
76+
DeviceId: dev.GetId(),
7777
})
7878
require.NoError(t, err)
7979
var v plgdDevice.Device
@@ -87,7 +87,7 @@ func TestClientApplicationServerClearCache(t *testing.T) {
8787

8888
// get device - cache is empty so expected error
8989
_, err = s.GetDevice(ctx, &pb.GetDeviceRequest{
90-
DeviceId: dev.Id,
90+
DeviceId: dev.GetId(),
9191
})
9292
require.Error(t, err)
9393

@@ -99,7 +99,7 @@ func TestClientApplicationServerClearCache(t *testing.T) {
9999

100100
// revert resource update
101101
_, err = s.UpdateResource(ctx, &pb.UpdateResourceRequest{
102-
ResourceId: commands.NewResourceID(dev.Id, configuration.ResourceURI),
102+
ResourceId: commands.NewResourceID(dev.GetId(), configuration.ResourceURI),
103103
Content: &grpcgwPb.Content{
104104
ContentType: serviceHttp.ApplicationJsonContentType,
105105
Data: []byte(`{"n":"` + test.DevsimName + `"}`),
@@ -109,7 +109,7 @@ func TestClientApplicationServerClearCache(t *testing.T) {
109109

110110
// disown device
111111
_, err = s.DisownDevice(ctx, &pb.DisownDeviceRequest{
112-
DeviceId: dev.Id,
112+
DeviceId: dev.GetId(),
113113
})
114114
require.NoError(t, err)
115115
}

0 commit comments

Comments
 (0)