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 2, 2024
1 parent 157148d commit 22afe59
Show file tree
Hide file tree
Showing 37 changed files with 170 additions and 139 deletions.
69 changes: 53 additions & 16 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,41 @@ linters-settings:
gocyclo:
min-complexity: 15
govet:
check-shadowing: true
enable:
- nilness
- shadow
gomoddirectives:
replace-allow-list:
- github.com/pion/dtls/v2
testifylint:
disable:
- go-require

linters:
enable:
- asasalint # Check for pass []any as any in variadic func(...any)
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
# - bodyclose # checks whether HTTP response body is closed successfully
# - contextcheck # check the function whether use a non-inherited context
- 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
# - depguard # Go linter that checks if package imports are in a list of acceptable packages
- 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
- 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.
- 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.
# - exhaustive # check exhaustiveness of enum switch statements
- execinquery # Execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds.
- exportloopref # checks for pointers to enclosing loop variables
# - forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
# - gochecknoglobals # Checks that no globals are present in Go code
# - gochecknoinits # Checks that no init functions are present in Go code
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid.
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- gocyclo # Computes and checks the cyclomatic complexity of functions
# - godox # Tool for detection of FIXME, TODO and other comment keywords
- godox # Tool for detection of FIXME, TODO and other comment keywords
# - goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
Expand All @@ -43,45 +46,68 @@ linters:
- 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.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosmopolitan # Report certain i18n/l10n anti-patterns in your Go codebase
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- grouper # An analyzer to analyze expression groups
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
# - intrange # Intrange is a linter to find places where for loops could make use of an integer range
- 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
- 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
- noctx # noctx finds sending http request without context.Context
- nolintlint # Reports ill-formed or insufficient nolint directives
# - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- 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.
- 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
- reassign # Checks that package variables are not reassigned
- sloglint # Ensure consistent code style when using log/slog
- 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
# - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
# - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- tagalign # Check that struct tags are well aligned.
- 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
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
# - wastedassign # wastedassign finds wasted assignment statements
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library.
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- contextcheck # check the function whether use a non-inherited context
- cyclop # checks function and package cyclomatic complexity
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- exhaustive # Check exhaustiveness of enum switch statements
- exhaustivestruct # Checks if all struct's fields are initialized
- exhaustruct # Checks if all structure fields are initialized.
- forbidigo # Forbids identifiers
- funlen # Tool for detection of long functions
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- inamedparam # Reports interfaces with unnamed method parameters.
- interfacebloat # A linter that checks the number of methods inside an interface
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- 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
Expand All @@ -105,6 +131,7 @@ issues:
- gosec
- gocyclo
- gocognit
- perfsprint

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

- path: example_test\.go
text: "exitAfterDefer"
Expand All @@ -124,5 +152,14 @@ issues:
linters:
- gosec

- path: .*/client/conn.go
linters:
- godox

- path: .*.go
text: "replace with standard maps package"
linters:
- godox

# # Fix found issues (if it's supported by the linter).
# fix: true
2 changes: 1 addition & 1 deletion dtls/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func TestConnGetSeparateMessage(t *testing.T) {
}()

cc, err := dtls.Dial(l.Addr().String(), dtlsCfg, options.WithHandlerFunc(func(_ *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) {
assert.NoError(t, fmt.Errorf("none msg expected comes: %+v", r))
require.Failf(t, "Unexpected msg", "Received unexpected message: %+v", r)
}))
require.NoError(t, err)
defer func() {
Expand Down
4 changes: 2 additions & 2 deletions dtls/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (s *Server) checkAndSetListener(l Listener) error {
s.listenMutex.Lock()
defer s.listenMutex.Unlock()
if s.listen != nil {
return fmt.Errorf("server already serve listener")
return errors.New("server already serve listener")
}
s.listen = l
return nil
Expand Down Expand Up @@ -127,7 +127,7 @@ func (s *Server) serveConnection(connections *connections.Connections, cc *udpCl

func (s *Server) Serve(l Listener) error {
if s.cfg.BlockwiseSZX > blockwise.SZX1024 {
return fmt.Errorf("invalid blockwiseSZX")
return errors.New("invalid blockwiseSZX")
}
err := s.checkAndSetListener(l)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions dtls/server/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type EventFunc = func()
type Session struct {
onClose []EventFunc

ctx atomic.Value // TODO: change to atomic.Pointer[context.Context] for go1.19
ctx atomic.Pointer[context.Context]

cancel context.CancelFunc
connection *coapNet.Conn
Expand Down Expand Up @@ -90,7 +90,7 @@ func (s *Session) Close() error {
}

func (s *Session) Context() context.Context {
return *s.ctx.Load().(*context.Context) //nolint:forcetypeassert
return *s.ctx.Load()
}

// SetContextValue stores the value associated with key to context of connection.
Expand Down
4 changes: 2 additions & 2 deletions message/codes/code_string.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package codes

import (
"fmt"
"errors"
"strconv"
)

Expand Down Expand Up @@ -54,5 +54,5 @@ func ToCode(v string) (Code, error) {
return key, nil
}
}
return 0, fmt.Errorf("not found")
return 0, errors.New("not found")
}
3 changes: 2 additions & 1 deletion message/codes/codes.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package codes

import (
"errors"
"fmt"
"strconv"
)
Expand Down Expand Up @@ -116,7 +117,7 @@ func (c *Code) UnmarshalJSON(b []byte) error {
return nil
}
if c == nil {
return fmt.Errorf("nil receiver passed to UnmarshalJSON")
return errors.New("nil receiver passed to UnmarshalJSON")
}

if len(b) > _maxCodeLen {
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 @@ -52,7 +52,7 @@ func TestUnmarshalJSONUnknownInput(t *testing.T) {

var got Code
longStr := "This is a very long string that is longer than the max code length"
require.True(t, len(longStr) > getMaxCodeLen())
require.Greater(t, len(longStr), getMaxCodeLen())
err := got.UnmarshalJSON([]byte(longStr))
require.Error(t, err)
}
Expand Down
5 changes: 2 additions & 3 deletions message/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package message
import (
"encoding/binary"
"errors"
"fmt"
"strconv"
)

Expand Down Expand Up @@ -113,7 +112,7 @@ func ToOptionID(v string) (OptionID, error) {
return key, nil
}
}
return 0, fmt.Errorf("not found")
return 0, errors.New("not found")
}

// Option value format (RFC7252 section 3.2)
Expand Down Expand Up @@ -234,7 +233,7 @@ func ToMediaType(v string) (MediaType, error) {
return key, nil
}
}
return 0, fmt.Errorf("not found")
return 0, errors.New("not found")
}

func extendOpt(opt int) (int, int) {
Expand Down
4 changes: 2 additions & 2 deletions message/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ func TestSetBytesOption(t *testing.T) {

v := make([]string, 2)
n, err := options.GetStrings(1, v)
require.Equal(t, nil, err)
require.NoError(t, err)
require.Equal(t, 1, n)
require.Equal(t, []string{"11"}, v[:n])

Expand All @@ -288,7 +288,7 @@ func TestAddBytesOption(t *testing.T) {
options = testAddBytesOption(t, options, Option{ID: 1, Value: []byte("4")}, 2)
v := make([][]byte, 2)
n, err := options.GetBytess(0, v)
require.Equal(t, nil, err)
require.NoError(t, err)
require.Equal(t, 2, n)
require.Equal(t, [][]byte{{0x30}, {0x31}}, v)
}
Expand Down
4 changes: 2 additions & 2 deletions message/pool/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ func TestMessageClone(t *testing.T) {
original.SetBody(malFuncSeeker{})
err = original.Clone(cloned)
require.Error(t, err)
require.Equal(t, err.Error(), "seek error")
require.Equal(t, "seek error", err.Error())

original.SetBody(malFuncReader{})
err = original.Clone(cloned)
Expand Down Expand Up @@ -386,7 +386,7 @@ func TestUnmarshalMessageWithMultipleOptions(t *testing.T) {
msg := pool.NewMessage(context.Background())
n, err := msg.UnmarshalWithDecoder(coder.DefaultCoder, data)
require.NoError(t, err)
require.Equal(t, n, len(data))
require.Len(t, data, n)
require.Equal(t, req.Options(), msg.Options())
})
}
Expand Down
5 changes: 2 additions & 3 deletions message/status/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package status

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

Expand All @@ -25,7 +24,7 @@ func TestStatus(t *testing.T) {
s, ok = FromError(err)
require.True(t, ok)
require.Equal(t, codes.NotFound, s.Code())
require.True(t, errors.Is(err, context.Canceled))
require.ErrorIs(t, err, context.Canceled)

s = Convert(err)
require.Equal(t, codes.NotFound, s.Code())
Expand All @@ -34,7 +33,7 @@ func TestStatus(t *testing.T) {
require.Equal(t, OK, Code(nil))

err = FromContextError(context.Canceled)
require.True(t, errors.Is(err, context.Canceled))
require.ErrorIs(t, err, context.Canceled)
require.Equal(t, Canceled, Code(err))

err = FromContextError(nil)
Expand Down
Loading

0 comments on commit 22afe59

Please sign in to comment.