diff --git a/.golangci-prod.toml b/.golangci-prod.toml index b26d6ab..dd2f4ce 100644 --- a/.golangci-prod.toml +++ b/.golangci-prod.toml @@ -1,7 +1,29 @@ -# Configuration for golangci-lint +# Configuration for golangci-lint@v1.52.2 # See https://golangci-lint.run/usage/configuration/#config-file -# Configuration updated for golangci-lint v1.35.2 +# Options for analysis running +[run] + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout = "10m" + + # If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + # + # Allowed values: readonly|vendor|mod + # By default, it isn't set. + modules-download-mode = "readonly" + +# output configuration options +[output] + # Make issues output unique by line. + # Default: true + uniq-by-line = false # See https://golangci-lint.run/usage/linters/ [linters] @@ -9,183 +31,544 @@ disable-all = true enable = [ - # https://golang.org/cmd/vet/ - # Examines Go source code and reports suspicious constructs. - "govet", - # https://github.com/kisielk/errcheck - # Checks for unchecked errors in go programs. + # errcheck is a program for checking for unchecked errors in Go code. These + # unchecked errors can be critical bugs in some cases. "errcheck", + # https://github.com/dominikh/go-tools/tree/master/simple + # Linter for Go source code that specializes in simplifying code. + "gosimple", + + # https://pkg.go.dev/cmd/vet + # Vet examines Go source code and reports suspicious constructs, such as + # Printf calls whose arguments do not align with the format string. + "govet", + + # https://github.com/gordonklaus/ineffassign + # Detects when assignments to existing variables are not used. + "ineffassign", + # https://staticcheck.io/ - # Staticcheck is a go vet on steroids, applying a ton of static analysis checks. + # It's a set of rules from staticcheck. It's not the same thing as the + # staticcheck binary. The author of staticcheck doesn't support or approve + # the use of staticcheck as a library inside golangci-lint. "staticcheck", # https://github.com/dominikh/go-tools/tree/master/unused # Checks Go code for unused constants, variables, functions and types. - "unused", # prod only - - # https://github.com/dominikh/go-tools/tree/master/unused - # Suggests simplifications for code. - "gosimple", + "unused", # PROD only - # https://github.com/gordonklaus/ineffassign - # Detects when assignments to existing variables are not used. - "ineffassign", + # https://github.com/mibk/dupl + # Tool for code clone detection. + "dupl", - # https://github.com/opennota/check - # Finds unused struct fields. - "structcheck", # prod only + # https://github.com/Antonboom/errname + # Checks that sentinel errors are prefixed with the Err and error types are + # suffixed with the Error. + "errname", - # https://github.com/dominikh/go-tools/tree/master/stylecheck - # Similar to and replacement for golint - prints out style mistakes. - "stylecheck", + # https://github.com/daixiang0/gci + # Gci controls Go package import order and makes it always deterministic. + "gci", - # https://github.com/securego/gosec - # Inspects source code for security problems. - "gosec", # prod only + # https://github.com/leighmcculloch/gocheckcompilerdirectives + # Checks that go compiler directive comments (//go:) are valid. + "gocheckcompilerdirectives", - # https://github.com/mdempsky/unconvert - # Removes unnecessary type conversions. - "unconvert", + # https://github.com/leighmcculloch/gochecknoinits + # Checks that no init functions are present in Go code. + "gochecknoinits", - # https://github.com/mibk/dupl - # Detects duplication in code blocks. - "dupl", + # https://github.com/uudashr/gocognit + # Computes and checks the cognitive complexity of functions. + "gocognit", # PROD only # https://github.com/jgautheron/goconst # Finds repeated strings that could be replaced by a constant. "goconst", - # https://github.com/daixiang0/gci - # Gci control golang package import order and make it always deterministic. - "gci", - - # https://github.com/golang/lint - # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - "golint", + # https://github.com/go-critic/go-critic + # Provides diagnostics that check for bugs, performance and style issues. + # Extensible without recompilation through dynamic rules. Dynamic rules are + # written declaratively with AST patterns, filters, report message and + # optional suggestion. + "gocritic", # PROD only # https://github.com/mvdan/gofumpt # Gofumpt checks whether code was gofumpt-ed. "gofumpt", + # https://github.com/securego/gosec + # Inspects source code for security problems. + "gosec", # PROD only + + # https://github.com/walle/lll + # Reports long lines. + "lll", + # https://github.com/client9/misspell # Finds commonly misspelled English words in comments. "misspell", - # https://github.com/mvdan/unparam - # Reports unused function parameters. - "unparam", # prod only + # https://github.com/junk1tm/musttag + # enforce field tags in (un)marshaled structs. + "musttag", # https://github.com/alexkohler/nakedret # Finds naked returns in functions greater than a specified function length. "nakedret", - # https://github.com/uudashr/gocognit - # Computes and checks the cognitive complexity of functions - "gocognit", # prod only + # https://github.com/gostaticanalysis/nilerr + # Finds the code that returns nil even if it checks that the error is not + # nil. + "nilerr", + + # https://github.com/sonatard/noctx + # noctx finds sending http request without context.Context. + "noctx", # https://github.com/golangci/golangci-lint/blob/master/pkg/golinters/nolintlint/README.md - # Reports ill-formed or insufficient nolint directives - "nolintlint", # prod only - ] + # Reports ill-formed or insufficient nolint directives. + "nolintlint", # PROD only -# Options for analysis running -[run] - # timeout for analysis, e.g. 30s, 5m, default is 1m - timeout = "10m" + # https://github.com/mgechev/revive + # Fast, configurable, extensible, flexible, and beautiful linter for Go. + # Drop-in replacement of golint. + "revive", - # Which dirs to skip: issues from them won't be reported; - # can use regexp here: generated.*, regexp is applied on full path; - # By default, directories such as `vendor/` are skipped independently from this - # option's value. - skip-dirs = [ - "bin", - ] + # https://github.com/jingyugao/rowserrcheck + # checks whether Err of rows is checked successfully. + "rowserrcheck", - skip-files = [ - ".*mock.*\\.go$" - ] + # https://github.com/ryanrolds/sqlclosecheck + # Checks that sql.Rows and sql.Stmt are closed. + "sqlclosecheck", - # golangci-lint passes it to "go list -mod={option}". From "go help modules": - # If invoked with -mod=readonly, the go command is disallowed from the implicit - # automatic updating of go.mod described above. Instead, it fails when any - # changes to go.mod are needed. This setting is most useful to check that - # go.mod does not need updates, such as in a continuous integration and testing - # system. If invoked with -mod=vendor, the go command assumes that the vendor - # directory holds the correct copies of dependencies and ignores the dependency - # descriptions in go.mod. - modules-download-mode = "readonly" + # https://github.com/dominikh/go-tools/tree/master/stylecheck + # Stylecheck is a replacement for golint. + "stylecheck", + + # https://github.com/sivchari/tenv + # tenv is analyzer that detects using os.Setenv instead of t.Setenv since + # Go1.17. + "tenv", + + # https://github.com/kulti/thelper + # thelper detects Go test helpers without t.Helper() call and checks the + # consistency of test helpers. + "thelper", + + # https://github.com/mdempsky/unconvert + # Remove unnecessary type conversions. + "unconvert", + + # https://github.com/sashamelentyev/usestdlibvars + # A linter that detect the possibility to use variables/constants from the + # Go standard library. + "usestdlibvars", + ] # All available settings of specific linters [linters-settings] + [linters-settings.errcheck] + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions = true + [linters-settings.govet] - # Report about shadowed variables + # Report about shadowed variables. + # Default: false check-shadowing = true + # Enable all analyzers. + # Default: false enable-all = true + # Disable analyzers by name - # See https://golang.org/cmd/vet/ + # See https://pkg.go.dev/golang.org/x/tools/go/analysis/passes#section-directories disable = [ - # (not needed) report mismatches between assembly files and Go declarations + # (not needed) reports mismatches between assembly files and Go + # declarations. "asmdecl", - # (dupl staticcheck) check for useless assignments + # (dupl staticcheck) detects useless assignments. "assign", - # detect structs that would take less memory if their fields were sorted - "fieldalignment", + # (not needed) detects some violations of the cgo pointer passing rules. + "cgocall", + # (not needed) detects structs that would use less memory if their fields + # were sorted. + "fieldalignment", + # (not needed) serves as a trivial example and test of the Analysis API. + "findcall", + # (not needed) reports assembly code that clobbers the frame pointer + # before saving it. + "framepointer", + # (dupl revive struct-tag) defines an Analyzer that checks struct field + # tags are well formed. + "structtag", ] - [linters-settings.errcheck] - # Report about not checking of errors in type assetions: `a := b.(MyStruct)`; - # default is false: such cases aren't reported by default. - check-type-assertions = true + [linters-settings.gci] + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections = [ + "standard", # Standard section: captures all standard packages. + "default", # Default section: contains all imports that could not be matched to another section type. + ] - [linters-settings.goimports] - # Put imports beginning with prefix after 3rd-party packages; - # it's a comma-separated list of prefixes - local-prefixes = "github.com/sudo-suhas/xgo" + [linters-settings.gocognit] + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity = 20 - [linters-settings.misspell] - # Correct spellings using locale preferences for US or UK. - # Default is to use a neutral variety of English. - # Setting locale to US will correct the British spelling of 'colour' to 'color'. - locale = "UK" - ignore-words = [ - "unauthorized" + [linters-settings.goconst] + # Ignore test files. + # Default: false + ignore-tests = true + + [linters-settings.gocritic] + # Which checks should be enabled; can't be combined with 'disabled-checks'. + # See https://go-critic.github.io/overview#checks-overview. + # To check which checks are enabled run `GL_DEBUG=gocritic golangci-lint run`. + # By default, list of stable checks is used. + enabled-checks = [ + # ============ Diagnostic ============ + # https://go-critic.com/overview.html#checkers-from-the-diagnostic-group + # Detects suspicious arguments order. + "argOrder", + # Detects suspicious function calls. + "badCall", + # Detects suspicious condition expressions. + "badCond", + # Detects suspicious mutex lock/unlock operations. + "badLock", + # Detects erroneous case order inside switch statements. + "caseOrder", + # Detects commented-out code inside function bodies. + "commentedOutCode", + # Detects loops inside functions that use defer. + "deferInLoop", + # Detects malformed ‘deprecated’ doc-comments. + "deprecatedComment", + # Detects suspicious duplicated arguments. + "dupArg", + # Detects duplicated case clauses inside switch or select statements. + "dupCase", + # Detects calls to exit/fatal inside functions that use defer. + "exitAfterDefer", + # Detects problems in filepath.Join() function calls. + "filepathJoin", + # Detects suspicious map literal keys. + "mapKey", + # Detects various off-by-one kind of errors. + "offBy1", + # Detects suspicious http.Error call without following return. + "returnAfterHttpError", + # Detects suspicious/confusing re-assignments. + "sloppyReassign", + # Detects unsupported test and benchmark funcs. + "sloppyTestFuncName", + # Detects redundant type assertions. + "sloppyTypeAssert", + # Detects “%s” formatting directives that can be replaced with %q. + "sprintfQuotedString", + # Detects potential truncation issues when comparing ints of different + # sizes. + "truncateCmp", + # Detects conditions that are unsafe due to not being exhaustive. + "weakCond", + + # ============ Style ============ + # https://go-critic.com/overview.html#checkers-from-the-style-group + # Detects assignments that can be simplified by using assignment + # operators. + "assignOp", + # Detects bool expressions that can be simplified. + "boolExprSimplify", + # Detects commented-out imports. + "commentedOutImport", + # Detects else with nested if statement that can be replaced with else-if. + "elseif", + # Detects fallthrough that can be avoided by using multi case values. + "emptyFallthrough", + # Detects empty string checks that can be written more idiomatically. + "emptyStringTest", + # Detects repeated if-else statements and suggests to replace them with + # switch statement. + "ifElseChain", + # Finds where nesting level could be reduced. + "nestingReduce", + # Detects concatenation with os.PathSeparator which can be replaced with + # filepath.Join. + "preferFilepathJoin", + # Detects input and output parameters that have a type of pointer to + # referential type. + "ptrToRefParam", + # Detects redundant fmt.Sprint calls. + "redundantSprint", + # Detects regexp patterns that can be simplified. + "regexpSimplify", + # Detects strings.Compare usage. + "stringsCompare", + # Detects TODO comments without detail/assignee. + "todoCommentWithoutDetail", + # Detects dereference expressions that can be omitted. + "underef", + # Detects unnamed results that may benefit from names. + "unnamedResult", + # Detects slice expressions that can be simplified to sliced expression + # itself. + "unslice", + # Detects function calls that can be replaced with convenience wrappers. + "wrapperFunc", + + # ============ Performance ============ + # https://go-critic.com/overview.html#checkers-from-the-performance-group + # Detects fmt.Sprint(f/ln) calls which can be replaced with + # fmt.Fprint(f/ln). + "preferFprint", + # Detects w.Write or io.WriteString calls which can be replaced with + # w.WriteString. + "preferStringWriter", + # Detects loops that copy big objects during each iteration. + "rangeValCopy", + # Detects redundant conversions between string and []byte. + "stringXbytes", ] + # Settings passed to gocritic. + # The settings key is the name of a supported gocritic checker. + # The list of supported checkers can be found in https://go-critic.github.io/overview. + [linters-settings.gocritic.settings] + [linters-settings.gocritic.settings.underef] + # Whether to skip (*x).method() calls where x is a pointer receiver. + # Default: true + skipRecvDeref = false + [linters-settings.gocritic.settings.unnamedResult] + # Whether to check exported functions. + # Default: false + checkExported = true + [linters-settings.gocritic.settings.rangeValCopy] + # Size in bytes that makes the warning trigger. + # Default: 128 + sizeThreshold = 512 + [linters-settings.gofumpt] - # Choose whether or not to use the extra rules that are disabled - # by default + # Choose whether to use the extra rules. + # Default: false extra-rules = true - [linters-settings.gocognit] - # minimal code complexity to report, 30 by default (but we recommend 10-20) - min-complexity = 20 + [linters-settings.gosec] + # To specify a set of rules to explicitly exclude. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] + excludes = [ + # Look for hard coded credentials + # too many false positives + "G101" + ] + + [linters-settings.lll] + # Max line length, lines longer will be reported. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option. + # Default: 120. + line-length = 160 + + [linters-settings.misspell] + # Correct spellings using locale preferences for US or UK. + # Default is to use a neutral variety of English. + # Setting locale to US will correct the British spelling of 'colour' to 'color'. + locale = "UK" + ignore-words = ["Unauthorized"] [linters-settings.nolintlint] - # Disable to ensure that nolint directives don't have a leading space. Default is true. - allow-leading-space = false - # Enable to require an explanation of nonzero length after each nolint directive. Default is false. - require-explanation = false - # Enable to require nolint directives to mention the specific linter being suppressed. Default is false. + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false require-specific = true + [linters-settings.revive] + # Sets the default severity. + # See https://github.com/mgechev/revive#configuration + # Default: warning + severity = "error" + + # Available rules - https://github.com/mgechev/revive/blob/v1.3.1/RULES_DESCRIPTIONS.md + [[linters-settings.revive.rules]] + # Reduces redundancies around variable declaration. + name = "var-declaration" + + [[linters-settings.revive.rules]] + # Warns when a public return is from unexported type. + name = "unexported-return" + + [[linters-settings.revive.rules]] + # Disallows blank imports. + name = "blank-imports" + + [[linters-settings.revive.rules]] + # context.Context should be the first argument of a function. + name = "context-as-argument" + + [[linters-settings.revive.rules]] + # Naming and commenting conventions on exported symbols. + name = "exported" + + [[linters-settings.revive.rules]] + # Redundant if when returning an error. + name = "if-return" + + [[linters-settings.revive.rules]] + # Use i++ and i-- instead of i += 1 and i -= 1. + name = "increment-decrement" + + [[linters-settings.revive.rules]] + # Prevents redundant else statements. + name = "indent-error-flow" + + [[linters-settings.revive.rules]] + # Specifies the maximum number of arguments a function can receive. + name = "argument-limit" + arguments = [5] + + [[linters-settings.revive.rules]] + # Prevents redundant else statements (extends indent-error-flow). + name = "superfluous-else" + + [[linters-settings.revive.rules]] + # Warns on methods with names that differ only by capitalization. + name = "confusing-naming" + + [[linters-settings.revive.rules]] + # Looks for program exits in funcs other than main() or init(). + name = "deep-exit" + + [[linters-settings.revive.rules]] + # Suggests to rename or remove unused function parameters. + name = "unused-parameter" + + [[linters-settings.revive.rules]] + # Checks common struct tags like json,xml,yaml. + name = "struct-tag" + + [[linters-settings.revive.rules]] + # Warns on assignments to value-passed method receivers. + name = "modifies-value-receiver" + + [[linters-settings.revive.rules]] + # Warns on constant logical expressions. + name = "constant-logical-expr" + + [[linters-settings.revive.rules]] + # Warns on redefinitions of builtin identifiers. + name = "redefines-builtin-id" + + [[linters-settings.revive.rules]] + # Specifies the maximum number of results a function can return. + name = "function-result-limit" + arguments = [3] + + [[linters-settings.revive.rules]] + # Warns if address of range value is used dangerously. + name = "range-val-address" + + [[linters-settings.revive.rules]] + # Warns on explicit call to the garbage collector. + name = "call-to-gc" + + [[linters-settings.revive.rules]] + # Spots identifiers that shadow an import. + name = "import-shadowing" + + [[linters-settings.revive.rules]] + # Warns on bare returns. + name = "bare-return" + + [[linters-settings.revive.rules]] + # Suggests to rename or remove unused method receivers. + name = "unused-receiver" + + [[linters-settings.revive.rules]] + # Spots if-then-else statements that can be refactored to simplify code + # reading. + name = "early-return" + + [[linters-settings.revive.rules]] + # Warns on function calls that will lead to (direct) infinite recursion. + name = "unconditional-recursion" + + [[linters-settings.revive.rules]] + # Spots if-then-else statements with identical then and else branches. + name = "identical-branches" + + [[linters-settings.revive.rules]] + # Warns on some defer gotchas. + name = "defer" + + [[linters-settings.revive.rules]] + # Warns on wrongly named un-exported symbols. + name = "unexported-naming" + + + [linters-settings.rowserrcheck] + # database/sql is always checked + # Default: [] + packages = [ + "github.com/jmoiron/sqlx", + ] + + [linters-settings.usestdlibvars] + # Suggest the use of http.StatusXX. + # covered by stylecheck ST1013. + # Default: true + http-status-code = false + # Suggest the use of time.Month.String(). + # Default: false + time-month = true + # Suggest the use of time.Layout. + # Default: false + time-layout = true + # Suggest the use of sql.LevelXX.String(). + # Default: false + sql-isolation-level = true + # Suggest the use of tls.SignatureScheme.String(). + # Default: false + tls-signature-scheme = true + [issues] - # List of regexps of issue texts to exclude, empty list by default. - # But independently from this option we use default exclude patterns, - # it can be disabled by `exclude-use-default: false`. To list all - # excluded by default patterns execute `golangci-lint run --help` - exclude=[ - 'declaration of "(err|ctx)" shadows declaration at', + # The list of ids of default excludes to include or disable. + # https://golangci-lint.run/usage/false-positives/#default-exclusions + # Default: [] + include = [ + # staticcheck SA4011: Break statement with no effect. + "EXC0005", ] # Excluding configuration per-path, per-linter, per-text and per-source + [[issues.exclude-rules]] + text = 'declaration of "(err|ctx)" shadows declaration at' + linters = ["govet"] + [[issues.exclude-rules]] # Exclude some linters from running on tests files. path = "_test\\.go" linters = [ "dupl", - "gosec" + "gosec", + "lll", + "gocognit", + "goconst", ] + + [[issues.exclude-rules]] + linters = ["lll"] + source = "^//go:generate " + + [[issues.exclude-rules]] + path = "_test\\.go" + text = "^Error return value is not checked$" + linters = ["errcheck"] diff --git a/.golangci.toml b/.golangci.toml index 6f4db52..e39aca1 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -1,154 +1,403 @@ -# Configuration for golangci-lint +# Configuration for golangci-lint@v1.52.2 # See https://golangci-lint.run/usage/configuration/#config-file +# Options for analysis running +[run] + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout = "10m" + + # If set we pass it to "go list -mod={option}". From "go help modules": + # If invoked with -mod=readonly, the go command is disallowed from the implicit + # automatic updating of go.mod described above. Instead, it fails when any changes + # to go.mod are needed. This setting is most useful to check that go.mod does + # not need updates, such as in a continuous integration and testing system. + # If invoked with -mod=vendor, the go command assumes that the vendor + # directory holds the correct copies of dependencies and ignores + # the dependency descriptions in go.mod. + # + # Allowed values: readonly|vendor|mod + # By default, it isn't set. + modules-download-mode = "readonly" + +# output configuration options +[output] + # Make issues output unique by line. + # Default: true + uniq-by-line = false + # See https://golangci-lint.run/usage/linters/ [linters] - # Disable-all, coupled with enable, scales well with updates to golangci-lint + # Disable-all coupled with enable scales well with updates to golangci-lint disable-all = true enable = [ - # https://golang.org/cmd/vet/ - # Examines Go source code and reports suspicious constructs. - "govet", - # https://github.com/kisielk/errcheck - # Checks for unchecked errors in go programs. + # errcheck is a program for checking for unchecked errors in Go code. These + # unchecked errors can be critical bugs in some cases. "errcheck", - # https://staticcheck.io/ - # Staticcheck is a go vet on steroids, applying a ton of static analysis checks. - "staticcheck", - - # https://github.com/dominikh/go-tools/tree/master/unused - # Suggests simplifications for code. + # https://github.com/dominikh/go-tools/tree/master/simple + # Linter for Go source code that specializes in simplifying code. "gosimple", + # https://pkg.go.dev/cmd/vet + # Vet examines Go source code and reports suspicious constructs, such as + # Printf calls whose arguments do not align with the format string. + "govet", + # https://github.com/gordonklaus/ineffassign # Detects when assignments to existing variables are not used. "ineffassign", - # https://github.com/dominikh/go-tools/tree/master/stylecheck - # Similar to and replacement for golint - prints out style mistakes. - "stylecheck", - - # https://github.com/mdempsky/unconvert - # Removes unnecessary type conversions. - "unconvert", + # https://staticcheck.io/ + # It's a set of rules from staticcheck. It's not the same thing as the + # staticcheck binary. The author of staticcheck doesn't support or approve + # the use of staticcheck as a library inside golangci-lint. + "staticcheck", # https://github.com/mibk/dupl - # Detects duplication in code blocks. + # Tool for code clone detection. "dupl", - # https://github.com/jgautheron/goconst - # Finds repeated strings that could be replaced by a constant. - "goconst", + # https://github.com/Antonboom/errname + # Checks that sentinel errors are prefixed with the Err and error types are + # suffixed with the Error. + "errname", # https://github.com/daixiang0/gci - # Gci control golang package import order and make it always deterministic. + # Gci controls Go package import order and makes it always deterministic. "gci", - # https://github.com/golang/lint - # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - "golint", + # https://github.com/leighmcculloch/gocheckcompilerdirectives + # Checks that go compiler directive comments (//go:) are valid. + "gocheckcompilerdirectives", + + # https://github.com/leighmcculloch/gochecknoinits + # Checks that no init functions are present in Go code. + "gochecknoinits", + + # https://github.com/jgautheron/goconst + # Finds repeated strings that could be replaced by a constant. + "goconst", # https://github.com/mvdan/gofumpt # Gofumpt checks whether code was gofumpt-ed. "gofumpt", + # https://github.com/walle/lll + # Reports long lines. + "lll", + # https://github.com/client9/misspell # Finds commonly misspelled English words in comments. "misspell", + # https://github.com/junk1tm/musttag + # enforce field tags in (un)marshaled structs. + "musttag", + # https://github.com/alexkohler/nakedret # Finds naked returns in functions greater than a specified function length. "nakedret", - ] -# Options for analysis running -[run] - # Which dirs to skip: issues from them won't be reported; - # can use regexp here: generated.*, regexp is applied on full path; - # By default, directories such as `vendor/` are skipped independently from this - # option's value. - skip-dirs = [ - "bin", - ] + # https://github.com/gostaticanalysis/nilerr + # Finds the code that returns nil even if it checks that the error is not + # nil. + "nilerr", - skip-files = [ - ".*mock.*\\.go$", - ] + # https://github.com/sonatard/noctx + # noctx finds sending http request without context.Context. + "noctx", - # golangci-lint passes it to "go list -mod={option}". From "go help modules": - # If invoked with -mod=readonly, the go command is disallowed from the implicit - # automatic updating of go.mod described above. Instead, it fails when any - # changes to go.mod are needed. This setting is most useful to check that - # go.mod does not need updates, such as in a continuous integration and testing - # system. If invoked with -mod=vendor, the go command assumes that the vendor - # directory holds the correct copies of dependencies and ignores the dependency - # descriptions in go.mod. - modules-download-mode = "readonly" + # https://github.com/mgechev/revive + # Fast, configurable, extensible, flexible, and beautiful linter for Go. + # Drop-in replacement of golint. + "revive", + + # https://github.com/jingyugao/rowserrcheck + # checks whether Err of rows is checked successfully. + "rowserrcheck", + + # https://github.com/ryanrolds/sqlclosecheck + # Checks that sql.Rows and sql.Stmt are closed. + "sqlclosecheck", + + # https://github.com/dominikh/go-tools/tree/master/stylecheck + # Stylecheck is a replacement for golint. + "stylecheck", + + # https://github.com/sivchari/tenv + # tenv is analyzer that detects using os.Setenv instead of t.Setenv since + # Go1.17. + "tenv", + + # https://github.com/kulti/thelper + # thelper detects Go test helpers without t.Helper() call and checks the + # consistency of test helpers. + "thelper", + + # https://github.com/mdempsky/unconvert + # Remove unnecessary type conversions. + "unconvert", + + # https://github.com/sashamelentyev/usestdlibvars + # A linter that detect the possibility to use variables/constants from the + # Go standard library. + "usestdlibvars", + ] # All available settings of specific linters [linters-settings] + [linters-settings.errcheck] + # Report about not checking of errors in type assertions: `a := b.(MyStruct)`. + # Such cases aren't reported by default. + # Default: false + check-type-assertions = true + [linters-settings.govet] - # Report about shadowed variables + # Report about shadowed variables. + # Default: false check-shadowing = true + # Enable all analyzers. + # Default: false enable-all = true + # Disable analyzers by name - # See https://golang.org/cmd/vet/ + # See https://pkg.go.dev/golang.org/x/tools/go/analysis/passes#section-directories disable = [ - # (not needed) report mismatches between assembly files and Go declarations + # (not needed) reports mismatches between assembly files and Go + # declarations. "asmdecl", - # (dupl staticcheck) check for useless assignments + # (dupl staticcheck) detects useless assignments. "assign", - # detect structs that would take less memory if their fields were sorted - "fieldalignment", + # (not needed) detects some violations of the cgo pointer passing rules. + "cgocall", + # (not needed) detects structs that would use less memory if their fields + # were sorted. + "fieldalignment", + # (not needed) serves as a trivial example and test of the Analysis API. + "findcall", + # (not needed) reports assembly code that clobbers the frame pointer + # before saving it. + "framepointer", + # (dupl revive struct-tag) defines an Analyzer that checks struct field + # tags are well formed. + "structtag", ] - [linters-settings.errcheck] - # Report about not checking of errors in type assetions: `a := b.(MyStruct)`; - # default is false: such cases aren't reported by default. - check-type-assertions = true + [linters-settings.gci] + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections = [ + "standard", # Standard section: captures all standard packages. + "default", # Default section: contains all imports that could not be matched to another section type. + ] + + [linters-settings.goconst] + # Ignore test files. + # Default: false + ignore-tests = true + + [linters-settings.gofumpt] + # Choose whether to use the extra rules. + # Default: false + extra-rules = true - [linters-settings.goimports] - # Put imports beginning with prefix after 3rd-party packages; - # it's a comma-separated list of prefixes - local-prefixes = "github.com/sudo-suhas/xgo" + [linters-settings.lll] + # Max line length, lines longer will be reported. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option. + # Default: 120. + line-length = 160 [linters-settings.misspell] # Correct spellings using locale preferences for US or UK. # Default is to use a neutral variety of English. # Setting locale to US will correct the British spelling of 'colour' to 'color'. locale = "UK" - ignore-words = [ - "unauthorized" + ignore-words = ["Unauthorized"] + + [linters-settings.revive] + # Sets the default severity. + # See https://github.com/mgechev/revive#configuration + # Default: warning + severity = "error" + + # Available rules - https://github.com/mgechev/revive/blob/v1.3.1/RULES_DESCRIPTIONS.md + [[linters-settings.revive.rules]] + # Reduces redundancies around variable declaration. + name = "var-declaration" + + [[linters-settings.revive.rules]] + # Warns when a public return is from unexported type. + name = "unexported-return" + + [[linters-settings.revive.rules]] + # Disallows blank imports. + name = "blank-imports" + + [[linters-settings.revive.rules]] + # context.Context should be the first argument of a function. + name = "context-as-argument" + + [[linters-settings.revive.rules]] + # Naming and commenting conventions on exported symbols. + name = "exported" + + [[linters-settings.revive.rules]] + # Redundant if when returning an error. + name = "if-return" + + [[linters-settings.revive.rules]] + # Use i++ and i-- instead of i += 1 and i -= 1. + name = "increment-decrement" + + [[linters-settings.revive.rules]] + # Prevents redundant else statements. + name = "indent-error-flow" + + [[linters-settings.revive.rules]] + # Specifies the maximum number of arguments a function can receive. + name = "argument-limit" + arguments = [5] + + [[linters-settings.revive.rules]] + # Prevents redundant else statements (extends indent-error-flow). + name = "superfluous-else" + + [[linters-settings.revive.rules]] + # Warns on methods with names that differ only by capitalization. + name = "confusing-naming" + + [[linters-settings.revive.rules]] + # Looks for program exits in funcs other than main() or init(). + name = "deep-exit" + + [[linters-settings.revive.rules]] + # Suggests to rename or remove unused function parameters. + name = "unused-parameter" + + [[linters-settings.revive.rules]] + # Checks common struct tags like json,xml,yaml. + name = "struct-tag" + + [[linters-settings.revive.rules]] + # Warns on assignments to value-passed method receivers. + name = "modifies-value-receiver" + + [[linters-settings.revive.rules]] + # Warns on constant logical expressions. + name = "constant-logical-expr" + + [[linters-settings.revive.rules]] + # Warns on redefinitions of builtin identifiers. + name = "redefines-builtin-id" + + [[linters-settings.revive.rules]] + # Specifies the maximum number of results a function can return. + name = "function-result-limit" + arguments = [3] + + [[linters-settings.revive.rules]] + # Warns if address of range value is used dangerously. + name = "range-val-address" + + [[linters-settings.revive.rules]] + # Warns on explicit call to the garbage collector. + name = "call-to-gc" + + [[linters-settings.revive.rules]] + # Spots identifiers that shadow an import. + name = "import-shadowing" + + [[linters-settings.revive.rules]] + # Warns on bare returns. + name = "bare-return" + + [[linters-settings.revive.rules]] + # Suggests to rename or remove unused method receivers. + name = "unused-receiver" + + [[linters-settings.revive.rules]] + # Spots if-then-else statements that can be refactored to simplify code + # reading. + name = "early-return" + + [[linters-settings.revive.rules]] + # Warns on function calls that will lead to (direct) infinite recursion. + name = "unconditional-recursion" + + [[linters-settings.revive.rules]] + # Spots if-then-else statements with identical then and else branches. + name = "identical-branches" + + [[linters-settings.revive.rules]] + # Warns on some defer gotchas. + name = "defer" + + [[linters-settings.revive.rules]] + # Warns on wrongly named un-exported symbols. + name = "unexported-naming" + + + [linters-settings.rowserrcheck] + # database/sql is always checked + # Default: [] + packages = [ + "github.com/jmoiron/sqlx", ] - [linters-settings.gofumpt] - # Choose whether or not to use the extra rules that are disabled - # by default - extra-rules = true + [linters-settings.usestdlibvars] + # Suggest the use of http.StatusXX. + # covered by stylecheck ST1013. + # Default: true + http-status-code = false + # Suggest the use of time.Month.String(). + # Default: false + time-month = true + # Suggest the use of time.Layout. + # Default: false + time-layout = true + # Suggest the use of sql.LevelXX.String(). + # Default: false + sql-isolation-level = true + # Suggest the use of tls.SignatureScheme.String(). + # Default: false + tls-signature-scheme = true [issues] - # List of regexps of issue texts to exclude, empty list by default. - # But independently from this option we use default exclude patterns, - # it can be disabled by `exclude-use-default: false`. To list all - # excluded by default patterns execute `golangci-lint run --help` - exclude=[ - 'declaration of "(err|ctx)" shadows declaration at', + # The list of ids of default excludes to include or disable. + # https://golangci-lint.run/usage/false-positives/#default-exclusions + # Default: [] + include = [ + # staticcheck SA4011: Break statement with no effect. + "EXC0005", ] # Excluding configuration per-path, per-linter, per-text and per-source + [[issues.exclude-rules]] + text = 'declaration of "(err|ctx)" shadows declaration at' + linters = ["govet"] + [[issues.exclude-rules]] # Exclude some linters from running on tests files. path = "_test\\.go" linters = [ "dupl", - "gosec" + "gosec", + "lll", + "gocognit", + "goconst", ] + [[issues.exclude-rules]] + linters = ["lll"] + source = "^//go:generate " + [[issues.exclude-rules]] path = "_test\\.go" text = "^Error return value is not checked$" diff --git a/errors/err_options_test.go b/errors/err_options_test.go index 1211ce3..5c76300 100644 --- a/errors/err_options_test.go +++ b/errors/err_options_test.go @@ -55,7 +55,7 @@ func TestOption(t *testing.T) { } func TestWithToJSON(t *testing.T) { - e := E(WithToJSON(nilJSON)).(*Error) //nolint:errcheck + e := E(WithToJSON(nilJSON)).(*Error) if e.ToJSON == nil { t.Errorf("Error.ToJSON=nil; want %s", funcName(nilJSON)) return @@ -65,6 +65,7 @@ func TestWithToJSON(t *testing.T) { } } +//nolint:misspell func TestWithResp(t *testing.T) { cases := []struct { name string diff --git a/httputil/json_decoder.go b/httputil/json_decoder.go index bd1893f..7ba8f20 100644 --- a/httputil/json_decoder.go +++ b/httputil/json_decoder.go @@ -126,7 +126,7 @@ func (j JSONDecoder) Decode(r *http.Request, v interface{}) error { // the destination. If the request body only contained a single JSON // object this will return an io.EOF error. So if we get anything else, // we know that there is additional data in the request body. - if err := dec.Decode(&struct{}{}); err != io.EOF { + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { msg := "Request body must only contain a single JSON object" return errors.E( errors.WithOp(op), errors.InvalidInput, errors.WithUserMsg(msg), errors.WithErr(err), diff --git a/httputil/json_decoder_test.go b/httputil/json_decoder_test.go index c78c42b..c0bdbb9 100644 --- a/httputil/json_decoder_test.go +++ b/httputil/json_decoder_test.go @@ -1,6 +1,7 @@ package httputil_test import ( + "context" "encoding/json" "net/http" "net/http/httptest" @@ -236,7 +237,7 @@ type request struct { } func (req request) build() (*http.Request, error) { - r, err := http.NewRequest(req.method, req.url, strings.NewReader(req.body)) + r, err := http.NewRequestWithContext(context.Background(), req.method, req.url, strings.NewReader(req.body)) if err != nil { return nil, err } diff --git a/httputil/url_builder.go b/httputil/url_builder.go index dbe302d..1f286b9 100644 --- a/httputil/url_builder.go +++ b/httputil/url_builder.go @@ -181,7 +181,7 @@ func (u *URLBuilder) URL() *url.URL { p := u.path for name, value := range u.pathParams { - p = strings.Replace(p, "{"+name+"}", url.PathEscape(value), -1) + p = strings.ReplaceAll(p, "{"+name+"}", url.PathEscape(value)) } urlv.Path = path.Join(urlv.Path, p)