Skip to content

Commit

Permalink
Update golangci-lint configuration and fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Danielius1922 committed Apr 4, 2024
1 parent 48efa09 commit c0ec960
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 32 deletions.
25 changes: 14 additions & 11 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ linters-settings:
# STxxxx checks in https://staticcheck.io/docs/configuration/options/#checks
# Default: ["*"]
checks: ["all", "-ST1000", "-ST1003"]
testifylint:
disable:
- go-require

linters:
enable:
Expand All @@ -31,12 +28,13 @@ linters:
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # Checks whether HTTP response body is closed successfully
# - copyloopvar # Detects places where loop variables are copied
- decorder # check declaration order and count of types, constants, variables and functions
- decorder # Check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- dupword # A linter that checks for duplicate words in the source code (usually miswritten)
- durationcheck # Check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- 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.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- 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.
- execinquery # Execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds.
Expand Down Expand Up @@ -68,12 +66,15 @@ linters:
- loggercheck # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).
- mirror # Reports wrong mirror patterns of bytes/strings usage
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- nolintlint # Reports ill-formed or insufficient nolint directives
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL
- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative.
- prealloc # Finds slice declarations that could potentially be preallocated
- predeclared # find code that shadows one of Go's predeclared identifiers
- protogetter # Reports direct reads from proto message fields when getters should be used.
- revive # golint replacement, finds style mistakes
Expand Down Expand Up @@ -114,18 +115,15 @@ linters:
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nonamedreturns # Reports all named returns
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- structcheck # Finds unused struct fields
- tagalign # Check that struct tags are well aligned.
- tagliatelle # Checks the struct tags.
- testableexamples # linter checks if examples are testable (have an expected output)
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
Expand All @@ -138,9 +136,10 @@ issues:
# Allow complex tests, better to be self contained
- path: _test\.go
linters:
- dupword
- forcetypeassert
- gocognit
- gocyclo
- gocyclo

# Allow complex main function and lower security in examples
- path: cmd/ocfclient/main\.go
Expand All @@ -149,6 +148,7 @@ issues:
- goconst
- gocyclo
- gosec
- nestif

- path: pkg/error
text: "package name error has same name as predeclared identifier"
Expand All @@ -161,3 +161,6 @@ issues:

# Fix found issues (if it's supported by the linter).
# fix: true

run:
go: "1.20"
2 changes: 1 addition & 1 deletion bridge/resources/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ func (r *Resource) observerHandler(req *net.Request, createSubscription bool) (*
}

func (r *Resource) HandleRequest(req *net.Request) (*pool.Message, error) {
if req.Code() == codes.GET && r.getHandler != nil {
if req.Code() == codes.GET && r.getHandler != nil { //nolint:nestif
var resp *pool.Message
var err error
if obs, errObs := req.Observe(); errObs == nil && r.createSubscription != nil && r.PolicyBitMask&schema.Observable != 0 {
Expand Down
3 changes: 2 additions & 1 deletion client/core/discover.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ func DialDiscoveryAddresses(ctx context.Context, cfg DiscoveryConfiguration, err
return nil, errors.New("context has not set deadline")
}
timeout := time.Until(v)
var out []*DiscoveryClient

out := make([]*DiscoveryClient, 0, len(cfg.MulticastAddressUDP4)+len(cfg.MulticastAddressUDP6))

// We need to separate messageIDs for upd4 and udp6, because if any docker container has isolated network
// iotivity-lite gets error EINVAL(22) for sendmsg with UDP6 for some interfaces. If it happens, the device is
Expand Down
11 changes: 6 additions & 5 deletions client/core/getDevice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"github.com/plgd-dev/device/v2/client/core/otm"
"github.com/plgd-dev/device/v2/schema/platform"
"github.com/plgd-dev/device/v2/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -75,15 +76,15 @@ func TestClientGetDeviceParallel(t *testing.T) {
go func() {
defer wg.Done()
got, err := c.GetDeviceByIP(ctx, ip)
require.NoError(t, err)
require.NotEmpty(t, got)
assert.NoError(t, err)
assert.NotEmpty(t, got)
links, err := got.GetResourceLinks(ctx, got.GetEndpoints())
require.NoError(t, err)
assert.NoError(t, err)
link, ok := links.GetResourceLink(platform.ResourceURI)
require.True(t, ok)
assert.True(t, ok)
var v interface{}
err = got.GetResource(ctx, link, &v)
require.NoError(t, err)
assert.NoError(t, err)
}()
}
wg.Wait()
Expand Down
2 changes: 1 addition & 1 deletion client/getDevice.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func (c *Client) getDeviceByIPWithUpdateCache(ctx context.Context, ip string, ex
if err != nil {
return nil, err
}
var devs []*core.Device
devs := make([]*core.Device, 0, len(newDevices))
oldDevs := make(map[string]*core.Device)
if expectedDeviceID != "" {
d, ok := c.deviceCache.GetDevice(expectedDeviceID)
Expand Down
9 changes: 5 additions & 4 deletions pkg/eventloop/eventloop_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"sync"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -67,7 +68,7 @@ func TestEventLoopAddThreadSafety(t *testing.T) {
startedCh := make(chan struct{})
wg.Add(1)
loop.Add(NewReadHandler(reflect.ValueOf(startedCh), func(_ reflect.Value, closed bool) {
require.True(t, closed, "Channel should be closed")
assert.True(t, closed, "Channel should be closed")
wg.Done()
}))
close(startedCh)
Expand All @@ -79,7 +80,7 @@ func TestEventLoopAddThreadSafety(t *testing.T) {
ch := make(chan struct{})
loop.Add(NewReadHandler(reflect.ValueOf(ch), func(_ reflect.Value, closed bool) {
// Simulate task processing
require.True(t, closed, "Channel should be closed")
assert.True(t, closed, "Channel should be closed")
wg.Done()
}))
close(ch)
Expand All @@ -105,7 +106,7 @@ func TestEventLoopRemoveThreadSafety(t *testing.T) {
startedCh := make(chan struct{})
wg.Add(1)
loop.Add(NewReadHandler(reflect.ValueOf(startedCh), func(_ reflect.Value, closed bool) {
require.True(t, closed, "Channel should be closed")
assert.True(t, closed, "Channel should be closed")
wg.Done()
}))
close(startedCh)
Expand All @@ -118,7 +119,7 @@ func TestEventLoopRemoveThreadSafety(t *testing.T) {
// Simulate adding a task
ch := make(chan struct{})
loop.Add(NewReadHandler(reflect.ValueOf(ch), func(reflect.Value, bool) {
require.Fail(t, "Task should not be processed")
assert.Fail(t, "Task should not be processed")
}))
go func() {
defer wg.Done()
Expand Down
2 changes: 1 addition & 1 deletion pkg/security/generateCertificate/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ func (cfg Configuration) AsnExtensionKeyUsages() ([]asn1.ObjectIdentifier, error
}

func (cfg Configuration) ToIPAddresses() ([]net.IP, error) {
var ips []net.IP
ips := make([]net.IP, 0, len(cfg.SubjectAlternativeName.IPAddresses))
for _, ip := range cfg.SubjectAlternativeName.IPAddresses {
v := net.ParseIP(ip)
if v == nil {
Expand Down
15 changes: 7 additions & 8 deletions pkg/security/signer/signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func NewOCFIdentityCertificate(caCert []*x509.Certificate, caKey crypto.PrivateK
return &OCFIdentityCertificate{caCert: caCert, caKey: caKey, validNotBefore: validNotBefore, validNotAfter: validNotAfter}
}

func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr []byte, err error) {
func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) ([]byte, error) {
now := time.Now()
notBefore := s.validNotBefore
notAfter := s.validNotAfter
Expand All @@ -67,24 +67,23 @@ func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr

csrBlock, _ := pem.Decode(csr)
if csrBlock == nil {
err = errors.New("pem not found")
return
return nil, errors.New("pem not found")
}

certificateRequest, err := x509.ParseCertificateRequest(csrBlock.Bytes)
if err != nil {
return
return nil, err
}

err = certificateRequest.CheckSignature()
if err != nil {
return
return nil, err
}

serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return
return nil, err
}

template := x509.Certificate{
Expand All @@ -102,9 +101,9 @@ func (s *OCFIdentityCertificate) Sign(_ context.Context, csr []byte) (signedCsr
if len(s.caCert) == 0 {
return nil, errors.New("cannot sign with empty signer CA certificates")
}
signedCsr, err = x509.CreateCertificate(rand.Reader, &template, s.caCert[0], certificateRequest.PublicKey, s.caKey)
signedCsr, err := x509.CreateCertificate(rand.Reader, &template, s.caCert[0], certificateRequest.PublicKey, s.caKey)
if err != nil {
return
return nil, err
}
return pkgX509.CreatePemChain(s.caCert, signedCsr)
}

0 comments on commit c0ec960

Please sign in to comment.