feat: make golangci-lint config stricter (#2874)

This commit is contained in:
leonklingele 2024-03-17 13:46:20 +01:00 committed by GitHub
parent e25a31b731
commit 5449b04101
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 225 additions and 79 deletions

View File

@ -1,18 +1,35 @@
# Created based on v1.51.0 # v1.2.0. Created based on golangci-lint v1.56.2
# NOTE: Keep this in sync with the version in .github/workflows/linter.yml
run: run:
modules-download-mode: readonly timeout: 5m
skip-dirs-use-default: false skip-dirs-use-default: false
modules-download-mode: readonly
allow-serial-runners: true
skip-dirs: skip-dirs:
- internal - internal # TODO: Do not ignore interal
output: output:
sort-results: true sort-results: true
uniq-by-line: false
linters-settings: linters-settings:
testifylint: depguard:
enable-all: true rules:
all:
list-mode: lax
deny:
- pkg: "flag"
desc: '`flag` package is only allowed in main.go'
- pkg: "log"
desc: 'logging is provided by `pkg/log`'
- pkg: "io/ioutil"
desc: '`io/ioutil` package is deprecated, use the `io` and `os` package instead'
# TODO: Prevent using these without a reason
# - pkg: "reflect"
# desc: '`reflect` package is dangerous to use'
# - pkg: "unsafe"
# desc: '`unsafe` package is dangerous to use'
errcheck: errcheck:
check-type-assertions: true check-type-assertions: true
check-blank: true check-blank: true
@ -27,19 +44,55 @@ linters-settings:
report-no-exported: true report-no-exported: true
exhaustive: exhaustive:
check-generated: true
default-signifies-exhaustive: true default-signifies-exhaustive: true
forbidigo: forbidigo:
forbid: forbid:
- ^(fmt\.Print(|f|ln)|print|println)$ - ^print(ln)?$
- 'http\.Default(Client|Transport)' - ^fmt\.Print(f|ln)?$
- ^http\.Default(Client|ServeMux|Transport)$
# TODO: Eventually enable these patterns # TODO: Eventually enable these patterns
# - 'time\.Sleep' # - ^panic$
# - 'panic' # - ^time\.Sleep$
analyze-types: true
gci:
sections:
- standard
- prefix(github.com/gofiber/fiber)
- default
- blank
- dot
# - alias
custom-order: true
goconst:
numbers: true
gocritic: gocritic:
# TODO: Uncomment the following lines
# enabled-tags:
# - diagnostic
# - style
# - performance
# - experimental
# - opinionated
disabled-checks: disabled-checks:
- ifElseChain - ifElseChain # TODO: Do not disable
# - hugeParam
# - rangeExprCopy
# - rangeValCopy
settings:
captLocal:
paramsOnly: false
elseif:
skipBalanced: false
underef:
skipRecvDeref: false
# NOTE: Set this option to false if other projects rely on this project's code
# unnamedResult:
# checkExported: false
gofumpt: gofumpt:
module-path: github.com/gofiber/fiber module-path: github.com/gofiber/fiber
@ -47,31 +100,27 @@ linters-settings:
gosec: gosec:
excludes: excludes:
- G104 # Provided by errcheck - G104 # TODO: Enable this again. Mostly provided by errcheck
config: config:
global: global:
# show-ignored: true # TODO: Enable this
audit: true audit: true
depguard:
rules:
main:
deny:
- pkg: flag
desc: '`flag` package is only allowed in main.go'
- pkg: io/ioutil
desc: '`io/ioutil` package is deprecated, use the `io` and `os` package instead'
govet: govet:
check-shadowing: true
enable-all: true enable-all: true
disable: disable:
- shadow
- fieldalignment - fieldalignment
- loopclosure - shadow
grouper: grouper:
# const-require-grouping: true # TODO: Enable this
import-require-single-import: true import-require-single-import: true
import-require-grouping: true import-require-grouping: true
# var-require-grouping: true # TODO: Conflicts with gofumpt
loggercheck:
require-string-key: true
no-printf-like: true
misspell: misspell:
locale: US locale: US
@ -83,12 +132,20 @@ linters-settings:
nonamedreturns: nonamedreturns:
report-error-in-defer: true report-error-in-defer: true
perfsprint:
err-error: true
predeclared: predeclared:
q: true q: true
promlinter: promlinter:
strict: true strict: true
# TODO: Enable this
# reassign:
# patterns:
# - '.*'
revive: revive:
enable-all-rules: true enable-all-rules: true
rules: rules:
@ -103,18 +160,25 @@ linters-settings:
- name: cognitive-complexity - name: cognitive-complexity
disabled: true disabled: true
- name: comment-spacings - name: comment-spacings
disabled: true # TODO https://github.com/gofiber/fiber/issues/2816 arguments:
- nolint
disabled: true # TODO: Do not disable
- name: cyclomatic - name: cyclomatic
disabled: true disabled: true
- name: early-return # TODO: Enable this check. Currently disabled due to upstream bug.
severity: warning # - name: enforce-repeated-arg-type-style
disabled: true # arguments:
# - short
- name: enforce-slice-style
arguments:
- make
disabled: true # TODO: Do not disable
- name: exported - name: exported
disabled: true disabled: true
- name: file-header - name: file-header
disabled: true disabled: true
- name: function-result-limit - name: function-result-limit
disabled: true arguments: [3]
- name: function-length - name: function-length
disabled: true disabled: true
- name: line-length-limit - name: line-length-limit
@ -124,14 +188,13 @@ linters-settings:
- name: modifies-parameter - name: modifies-parameter
disabled: true disabled: true
- name: nested-structs - name: nested-structs
disabled: true disabled: true # TODO: Do not disable
- name: package-comments - name: package-comments
disabled: true disabled: true
- name: unchecked-type-assertion - name: optimize-operands-order
disabled: true # TODO https://github.com/gofiber/fiber/issues/2816
# Provided by errcheck
- name: unhandled-error
disabled: true disabled: true
- name: unchecked-type-assertion
disabled: true # TODO: Do not disable
stylecheck: stylecheck:
checks: checks:
@ -141,6 +204,9 @@ linters-settings:
- -ST1021 - -ST1021
- -ST1022 - -ST1022
tagalign:
strict: true
tagliatelle: tagliatelle:
case: case:
rules: rules:
@ -149,8 +215,41 @@ linters-settings:
tenv: tenv:
all: true all: true
#unparam: testifylint:
# check-exported: true enable-all: true
# TODO: Do not disable any options
disable:
- go-require
testpackage:
skip-regexp: "^$"
unparam:
# NOTE: Set this option to false if other projects rely on this project's code
check-exported: false
unused:
# TODO: Uncomment these two lines
# parameters-are-used: false
# local-variables-are-used: false
# NOTE: Set these options to true if other projects rely on this project's code
field-writes-are-uses: true
# exported-is-used: true # TODO: Fix issues with this option (upstream)
exported-fields-are-used: true
usestdlibvars:
http-method: true
http-status-code: true
time-weekday: false # TODO: Set to true
time-month: false # TODO: Set to true
time-layout: false # TODO: Set to true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
wrapcheck: wrapcheck:
ignorePackageGlobs: ignorePackageGlobs:
@ -159,17 +258,23 @@ linters-settings:
issues: issues:
exclude-use-default: false exclude-use-default: false
exclude-case-sensitive: true
max-issues-per-linter: 0
max-same-issues: 0
exclude-rules: exclude-rules:
- linters:
- goerr113
text: 'do not define dynamic errors, use wrapped static errors instead*'
- path: log/.*\.go
linters:
- depguard
# Exclude some linters from running on tests files. # Exclude some linters from running on tests files.
- path: _test\.go - path: _test\.go
linters: linters:
- bodyclose - bodyclose
# fix: true
linters: linters:
disable:
- spancheck # opentelemetry, irrelevant
- tagalign # requires awkward manual formatting of struct tags
enable: enable:
- asasalint - asasalint
- asciicheck - asciicheck
@ -177,8 +282,12 @@ linters:
- bodyclose - bodyclose
- containedctx - containedctx
- contextcheck - contextcheck
# - cyclop
- decorder
- depguard - depguard
- dogsled - dogsled
# - dupl
# - dupword # TODO: Enable
- durationcheck - durationcheck
- errcheck - errcheck
- errchkjson - errchkjson
@ -186,45 +295,84 @@ linters:
- errorlint - errorlint
- execinquery - execinquery
- exhaustive - exhaustive
# - exhaustivestruct
# - exhaustruct
- exportloopref - exportloopref
- forbidigo - forbidigo
- forcetypeassert - forcetypeassert
# - gochecksumtype # TODO https://github.com/gofiber/fiber/issues/2816 # - funlen
# - goconst # TODO https://github.com/gofiber/fiber/issues/2816 # - gci # TODO: Enable
- ginkgolinter
# - gocheckcompilerdirectives # TODO: Enable
# - gochecknoglobals # TODO: Enable
# - gochecknoinits # TODO: Enable
- gochecksumtype
# - gocognit
# - goconst # TODO: Enable
- gocritic - gocritic
# - gocyclo
# - godot
# - godox
- goerr113
- gofmt - gofmt
- gofumpt - gofumpt
- goimports # - goheader
# - goimports
# - golint
# - gomnd # TODO: Enable
- gomoddirectives - gomoddirectives
# - gomodguard
- goprintffuncname - goprintffuncname
- gosec - gosec
- gosimple - gosimple
# - gosmopolitan # TODO https://github.com/gofiber/fiber/issues/2816 # - gosmopolitan # TODO: Enable
- govet - govet
- grouper - grouper
- inamedparam # - ifshort # TODO: Enable
# - importas
# - inamedparam
- ineffassign
# - interfacebloat
# - interfacer
# - ireturn
# - lll
- loggercheck - loggercheck
# - maintidx
- makezero
# - maligned
- mirror - mirror
- misspell - misspell
- musttag
- nakedret - nakedret
# - nestif
- nilerr - nilerr
- nilnil - nilnil
# - nlreturn
- noctx - noctx
- nolintlint - nolintlint
- nonamedreturns - nonamedreturns
- nosprintfhostport - nosprintfhostport
# - paralleltest # TODO: Enable
- perfsprint - perfsprint
# - prealloc
- predeclared - predeclared
- promlinter - promlinter
- protogetter
- reassign - reassign
- revive - revive
- rowserrcheck - rowserrcheck
# - scopelint # TODO: Enable
- sloglint
- spancheck
- sqlclosecheck - sqlclosecheck
- staticcheck - staticcheck
- stylecheck - stylecheck
# - tagalign # TODO: Enable
- tagliatelle - tagliatelle
- tenv
- testableexamples
- testifylint - testifylint
# - testpackage # TODO: Enable once https://github.com/gofiber/fiber/issues/2252 is implemented # - testpackage # TODO: Enable
- thelper - thelper
- tparallel - tparallel
- typecheck - typecheck
@ -232,7 +380,9 @@ linters:
- unparam - unparam
- unused - unused
- usestdlibvars - usestdlibvars
# - wastedassign # TODO https://github.com/gofiber/fiber/issues/2816 # - varnamelen
# - wastedassign # TODO: Enable
- whitespace - whitespace
- wrapcheck - wrapcheck
- tenv # - wsl
- zerologlint

View File

@ -8,7 +8,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log" "log" //nolint:depguard // TODO: Required to capture output, use internal log package instead
"net" "net"
"os" "os"
"strings" "strings"

View File

@ -126,11 +126,10 @@ func New(config ...Config) fiber.Handler {
trimmedOrigin := strings.TrimSpace(origin) trimmedOrigin := strings.TrimSpace(origin)
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin) isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)
if isValid { if !isValid {
allowOrigins[i] = normalizedOrigin
} else {
log.Panicf("[CORS] Invalid origin format in configuration: %s", trimmedOrigin) //nolint:revive // we want to exit the program log.Panicf("[CORS] Invalid origin format in configuration: %s", trimmedOrigin) //nolint:revive // we want to exit the program
} }
allowOrigins[i] = normalizedOrigin
} }
} else { } else {
// If AllowOrigins is set to a wildcard or not set, // If AllowOrigins is set to a wildcard or not set,

View File

@ -42,13 +42,10 @@ func Test_Idempotency(t *testing.T) {
if !isIdempotent { if !isIdempotent {
return errors.New("request with unsafe HTTP method should be idempotent if X-Idempotency-Key request header is set") return errors.New("request with unsafe HTTP method should be idempotent if X-Idempotency-Key request header is set")
} }
} else { } else if isIdempotent {
// No request header
if isIdempotent {
return errors.New("request with unsafe HTTP method should not be idempotent if X-Idempotency-Key request header is not set") return errors.New("request with unsafe HTTP method should not be idempotent if X-Idempotency-Key request header is not set")
} }
} }
}
return nil return nil
}) })

View File

@ -75,7 +75,7 @@ func (s *Store) Get(c fiber.Ctx) (*Session, error) {
if raw != nil && err == nil { if raw != nil && err == nil {
mux.Lock() mux.Lock()
defer mux.Unlock() defer mux.Unlock()
sess.byteBuffer.Write(raw) _, _ = sess.byteBuffer.Write(raw) // Ignore error, this will never fail
encCache := gob.NewDecoder(sess.byteBuffer) encCache := gob.NewDecoder(sess.byteBuffer)
err := encCache.Decode(&sess.data.Data) err := encCache.Decode(&sess.data.Data)
if err != nil { if err != nil {

View File

@ -591,11 +591,12 @@ func findGreedyParamLen(s string, searchCount int, segment *routeSegment) int {
// check all from right to left segments // check all from right to left segments
for i := segment.PartCount; i > 0 && searchCount > 0; i-- { for i := segment.PartCount; i > 0 && searchCount > 0; i-- {
searchCount-- searchCount--
if constPosition := strings.LastIndex(s, segment.ComparePart); constPosition != -1 {
s = s[:constPosition] constPosition := strings.LastIndex(s, segment.ComparePart)
} else { if constPosition == -1 {
break break
} }
s = s[:constPosition]
} }
return len(s) return len(s)

View File

@ -278,13 +278,12 @@ func (r *Redirect) setFlash() {
var commaPos int var commaPos int
for { for {
commaPos = findNextNonEscapedCharsetPosition(cookieValue, []byte(CookieDataSeparator)) commaPos = findNextNonEscapedCharsetPosition(cookieValue, []byte(CookieDataSeparator))
if commaPos != -1 { if commaPos == -1 {
r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue[:commaPos], " "))
cookieValue = cookieValue[commaPos+1:]
} else {
r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue, " ")) r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue, " "))
break break
} }
r.c.redirectionMessages = append(r.c.redirectionMessages, strings.Trim(cookieValue[:commaPos], " "))
cookieValue = cookieValue[commaPos+1:]
} }
r.c.ClearCookie(FlashCookieName) r.c.ClearCookie(FlashCookieName)