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 authored and Daniel Adam committed Apr 4, 2024
1 parent 6ed2ef2 commit af06ff2
Show file tree
Hide file tree
Showing 21 changed files with 155 additions and 146 deletions.
27 changes: 14 additions & 13 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ linters-settings:
gomoddirectives:
replace-allow-list:
- github.com/pion/dtls/v2
testifylint:
disable:
- go-require

linters:
enable:
Expand All @@ -19,12 +16,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 @@ -56,12 +54,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 All @@ -70,6 +71,7 @@ linters:
- spancheck # Checks for mistakes with OpenTelemetry/Census spans
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- testifylint # Checks usage of github.com/stretchr/testify.
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
Expand Down Expand Up @@ -102,18 +104,14 @@ 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 @@ -127,11 +125,12 @@ issues:
- path: _test\.go
linters:
- dupl
- dupword
- forcetypeassert
- gosec
- gocyclo
- gocognit
- perfsprint
- nakedret

- path: ^test/.*\.go
linters:
Expand All @@ -140,7 +139,6 @@ issues:
- gosec
- gocyclo
- gocognit
- perfsprint

- path: example_test\.go
text: "exitAfterDefer"
Expand All @@ -163,3 +161,6 @@ issues:

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

run:
go: "1.20"
18 changes: 9 additions & 9 deletions dtls/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func TestConnGet(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -204,7 +204,7 @@ func TestConnGetSeparateMessage(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg, options.WithHandlerFunc(func(_ *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) {
Expand Down Expand Up @@ -330,7 +330,7 @@ func TestConnPost(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -465,7 +465,7 @@ func TestConnPut(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -577,7 +577,7 @@ func TestConnDelete(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -637,7 +637,7 @@ func TestConnPing(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -682,7 +682,7 @@ func TestConnHandeShakeFailure(t *testing.T) {
go func() {
defer wg.Done()
errS := s.Serve(l)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

dtlsCfgClient := &piondtls.Config{
Expand Down Expand Up @@ -738,7 +738,7 @@ func TestClientInactiveMonitor(t *testing.T) {
go func() {
defer serverWg.Done()
errS := sd.Serve(ld)
require.NoError(t, errS)
assert.NoError(t, errS)
}()
defer func() {
sd.Stop()
Expand Down Expand Up @@ -798,7 +798,7 @@ func TestClientKeepAliveMonitor(t *testing.T) {
}
}
defer c.Close()
require.NoError(t, errA)
assert.NoError(t, errA)
}
}()
defer func() {
Expand Down
2 changes: 1 addition & 1 deletion dtls/server/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (s *Session) WriteMessage(req *pool.Message) error {
}

// WriteMulticastMessage sends multicast to the remote multicast address.
// Currently it is not implemented - is is just satisfy golang udp/client/Session interface.
// Currently it is not implemented - is just satisfy golang udp/client/Session interface.
func (s *Session) WriteMulticastMessage(*pool.Message, *net.UDPAddr, ...coapNet.MulticastOption) error {
return errors.New("multicast messages not implemented for DTLS")
}
Expand Down
9 changes: 5 additions & 4 deletions dtls/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/plgd-dev/go-coap/v3/pkg/runner/periodic"
"github.com/plgd-dev/go-coap/v3/udp/client"
"github.com/plgd-dev/go-coap/v3/udp/coder"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"golang.org/x/sync/semaphore"
Expand Down Expand Up @@ -67,7 +68,7 @@ func TestServerCleanUpConns(t *testing.T) {
go func() {
defer wg.Done()
errS := sd.Serve(ld)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(ld.Addr().String(), dtlsCfg)
Expand Down Expand Up @@ -174,7 +175,7 @@ func TestServerSetContextValueWithPKI(t *testing.T) {
defer sd.Stop()
go func() {
errS := sd.Serve(ld)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(ld.Addr().String(), clientCgf)
Expand Down Expand Up @@ -233,7 +234,7 @@ func TestServerInactiveMonitor(t *testing.T) {
go func() {
defer serverWg.Done()
errS := sd.Serve(ld)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := dtls.Dial(ld.Addr().String(), clientCgf)
Expand Down Expand Up @@ -305,7 +306,7 @@ func TestServerKeepAliveMonitor(t *testing.T) {
go func() {
defer serverWg.Done()
errS := sd.Serve(ld)
require.NoError(t, errS)
assert.NoError(t, errS)
}()

cc, err := piondtls.Dial("udp4", &net.UDPAddr{IP: []byte{127, 0, 0, 1}, Port: ld.Addr().(*net.UDPAddr).Port}, clientCgf)
Expand Down
2 changes: 1 addition & 1 deletion message/codes/codes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestUnmarshalJSONMarshalUnmarshal(t *testing.T) {
}

func TestCodeToString(t *testing.T) {
var strCodes []string
strCodes := make([]string, 0, len(codeToString))
for _, val := range codeToString {
strCodes = append(strCodes, val)
}
Expand Down
2 changes: 1 addition & 1 deletion message/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ func (options Options) SetBytes(buf []byte, id OptionID, data []byte) (Options,
return options.Set(Option{ID: id, Value: buf[:len(data)]}), len(data), nil
}

// AddBytes appends bytes of a option option to options.
// AddBytes appends bytes of a option to options.
//
// Returns modified options, number of used buf bytes and error if occurs.
func (options Options) AddBytes(buf []byte, id OptionID, data []byte) (Options, int, error) {
Expand Down
51 changes: 26 additions & 25 deletions message/pool/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,33 +603,34 @@ func (r *Message) Clone(msg *Message) error {
msg.SetMessageID(r.MessageID())
msg.SetControlMessage(r.ControlMessage())

if r.Body() != nil {
buf := bytes.NewBuffer(nil)
n, err := r.Body().Seek(0, io.SeekCurrent)
if err != nil {
return err
}
_, err = r.body.Seek(0, io.SeekStart)
if err != nil {
return err
}
_, err = io.Copy(buf, r.Body())
if err != nil {
var errs *multierror.Error
errs = multierror.Append(errs, err)
_, errS := r.Body().Seek(n, io.SeekStart)
if errS != nil {
errs = multierror.Append(errs, errS)
}
return errs.ErrorOrNil()
}
_, err = r.Body().Seek(n, io.SeekStart)
if err != nil {
return err
if r.Body() == nil {
return nil
}
buf := bytes.NewBuffer(nil)
n, err := r.Body().Seek(0, io.SeekCurrent)
if err != nil {
return err
}
_, err = r.body.Seek(0, io.SeekStart)
if err != nil {
return err
}
_, err = io.Copy(buf, r.Body())
if err != nil {
var errs *multierror.Error
errs = multierror.Append(errs, err)
_, errS := r.Body().Seek(n, io.SeekStart)
if errS != nil {
errs = multierror.Append(errs, errS)
}
r := bytes.NewReader(buf.Bytes())
msg.SetBody(r)
return errs.ErrorOrNil()
}
_, err = r.Body().Seek(n, io.SeekStart)
if err != nil {
return err
}
body := bytes.NewReader(buf.Bytes())
msg.SetBody(body)
return nil
}

Expand Down
8 changes: 4 additions & 4 deletions message/status/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package status

import (
"context"
"fmt"
"errors"
"testing"

"github.com/plgd-dev/go-coap/v3/message/codes"
Expand All @@ -15,7 +15,7 @@ func TestStatus(t *testing.T) {
require.True(t, ok)
require.Equal(t, OK, s.Code())

_, ok = FromError(fmt.Errorf("test"))
_, ok = FromError(errors.New("test"))
require.False(t, ok)

msg := pool.NewMessage(context.TODO())
Expand All @@ -42,7 +42,7 @@ func TestStatus(t *testing.T) {
err = FromContextError(context.DeadlineExceeded)
require.Equal(t, Timeout, Code(err))

err = FromContextError(fmt.Errorf("test"))
err = FromContextError(errors.New("test"))
require.Equal(t, Unknown, Code(err))
require.Equal(t, Unknown, Code(fmt.Errorf("test")))
require.Equal(t, Unknown, Code(errors.New("test")))
}
2 changes: 1 addition & 1 deletion net/blockwise/blockwise.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ func (b *BlockWise[C]) processReceivedMessage(w *responsewriter.ResponseWriter[C
return fmt.Errorf("cannot get payload: %w", err)
}
off := num * szx.Size()
if off == payloadSize {
if off == payloadSize { //nolint:nestif
payloadSize, err = copyToPayloadFromOffset(r, payloadFile, off)
if err != nil {
return fmt.Errorf("cannot copy data to payload: %w", err)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/plgd-dev/go-coap/v3/message/codes"
"github.com/plgd-dev/go-coap/v3/message/pool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
)
Expand Down Expand Up @@ -146,7 +147,7 @@ func TestLimitParallelRequestsDo(t *testing.T) {
go func(r *pool.Message) {
defer wg.Done()
_, err := c.Do(r)
require.Error(t, err)
assert.Error(t, err)
}(req)
}
wg.Wait()
Expand Down Expand Up @@ -269,7 +270,7 @@ func TestLimitParallelRequestsDoObserve(t *testing.T) {
_, err := c.DoObserve(r, func(*pool.Message) {
// do nothing
})
require.Error(t, err)
assert.Error(t, err)
}(req)
}
wg.Wait()
Expand Down
2 changes: 1 addition & 1 deletion net/connUDP_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func TestUDPConnwriteMulticastWithContext(t *testing.T) {
go func() {
b := make([]byte, 1024)
n, _, errR := c2.ReadWithContext(ctx, b)
require.NoError(t, errR)
assert.NoError(t, errR)
if n > 0 {
b = b[:n]
assert.Equal(t, payload, b)
Expand Down
Loading

0 comments on commit af06ff2

Please sign in to comment.