Skip to content

Commit 37a7715

Browse files
committed
Add stricter lint config and fix a number of issues
1 parent 3b6db7f commit 37a7715

File tree

9 files changed

+486
-112
lines changed

9 files changed

+486
-112
lines changed

.golangci.yaml

Lines changed: 349 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,349 @@
1+
# This code is licensed under the terms of the MIT license https://opensource.org/license/mit
2+
# Copyright (c) 2021 Marat Reymers
3+
4+
## Golden config for golangci-lint v1.58.2
5+
#
6+
# This is the best config for golangci-lint based on my experience and opinion.
7+
# It is very strict, but not extremely strict.
8+
# Feel free to adapt and change it for your needs.
9+
10+
run:
11+
# Timeout for analysis, e.g. 30s, 5m.
12+
# Default: 1m
13+
timeout: 3m
14+
15+
16+
# This file contains only configs which differ from defaults.
17+
# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
18+
linters-settings:
19+
cyclop:
20+
# The maximal code complexity to report.
21+
# Default: 10
22+
max-complexity: 30
23+
# The maximal average package complexity.
24+
# If it's higher than 0.0 (float) the check is enabled
25+
# Default: 0.0
26+
package-average: 10.0
27+
28+
errcheck:
29+
# Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
30+
# Such cases aren't reported by default.
31+
# Default: false
32+
check-type-assertions: true
33+
34+
exhaustive:
35+
# Program elements to check for exhaustiveness.
36+
# Default: [ switch ]
37+
check:
38+
- switch
39+
- map
40+
41+
exhaustruct:
42+
# List of regular expressions to exclude struct packages and their names from checks.
43+
# Regular expressions must match complete canonical struct package/name/structname.
44+
# Default: []
45+
exclude:
46+
# std libs
47+
- "^net/http.Client$"
48+
- "^net/http.Cookie$"
49+
- "^net/http.Request$"
50+
- "^net/http.Response$"
51+
- "^net/http.Server$"
52+
- "^net/http.Transport$"
53+
- "^net/url.URL$"
54+
- "^os/exec.Cmd$"
55+
- "^reflect.StructField$"
56+
# public libs
57+
- "^github.com/Shopify/sarama.Config$"
58+
- "^github.com/Shopify/sarama.ProducerMessage$"
59+
- "^github.com/mitchellh/mapstructure.DecoderConfig$"
60+
- "^github.com/prometheus/client_golang/.+Opts$"
61+
- "^github.com/spf13/cobra.Command$"
62+
- "^github.com/spf13/cobra.CompletionOptions$"
63+
- "^github.com/stretchr/testify/mock.Mock$"
64+
- "^github.com/testcontainers/testcontainers-go.+Request$"
65+
- "^github.com/testcontainers/testcontainers-go.FromDockerfile$"
66+
- "^golang.org/x/tools/go/analysis.Analyzer$"
67+
- "^google.golang.org/protobuf/.+Options$"
68+
- "^gopkg.in/yaml.v3.Node$"
69+
70+
funlen:
71+
# Checks the number of lines in a function.
72+
# If lower than 0, disable the check.
73+
# Default: 60
74+
lines: 100
75+
# Checks the number of statements in a function.
76+
# If lower than 0, disable the check.
77+
# Default: 40
78+
statements: 50
79+
# Ignore comments when counting lines.
80+
# Default false
81+
ignore-comments: true
82+
83+
gocognit:
84+
# Minimal code complexity to report.
85+
# Default: 30 (but we recommend 10-20)
86+
min-complexity: 45
87+
88+
gocritic:
89+
# Settings passed to gocritic.
90+
# The settings key is the name of a supported gocritic checker.
91+
# The list of supported checkers can be find in https://go-critic.github.io/overview.
92+
settings:
93+
captLocal:
94+
# Whether to restrict checker to params only.
95+
# Default: true
96+
paramsOnly: false
97+
underef:
98+
# Whether to skip (*x).method() calls where x is a pointer receiver.
99+
# Default: true
100+
skipRecvDeref: false
101+
102+
gomodguard:
103+
blocked:
104+
# List of blocked modules.
105+
# Default: []
106+
modules:
107+
- github.com/golang/protobuf:
108+
recommendations:
109+
- google.golang.org/protobuf
110+
reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules"
111+
- github.com/satori/go.uuid:
112+
recommendations:
113+
- github.com/google/uuid
114+
reason: "satori's package is not maintained"
115+
- github.com/gofrs/uuid:
116+
recommendations:
117+
- github.com/gofrs/uuid/v5
118+
reason: "gofrs' package was not go module before v5"
119+
120+
govet:
121+
# Enable all analyzers.
122+
# Default: false
123+
enable-all: true
124+
# Disable analyzers by name.
125+
# Run `go tool vet help` to see all analyzers.
126+
# Default: []
127+
disable:
128+
- fieldalignment # too strict
129+
# Settings per analyzer.
130+
settings:
131+
shadow:
132+
# Whether to be strict about shadowing; can be noisy.
133+
# Default: false
134+
strict: false
135+
136+
inamedparam:
137+
# Skips check for interface methods with only a single parameter.
138+
# Default: false
139+
skip-single-param: true
140+
141+
mnd:
142+
# List of function patterns to exclude from analysis.
143+
# Values always ignored: `time.Date`,
144+
# `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`,
145+
# `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`.
146+
# Default: []
147+
ignored-functions:
148+
- args.Error
149+
- flag.Arg
150+
- flag.Duration.*
151+
- flag.Float.*
152+
- flag.Int.*
153+
- flag.Uint.*
154+
- os.Chmod
155+
- os.Mkdir.*
156+
- os.OpenFile
157+
- os.WriteFile
158+
- prometheus.ExponentialBuckets.*
159+
- prometheus.LinearBuckets
160+
161+
nakedret:
162+
# Make an issue if func has more lines of code than this setting, and it has naked returns.
163+
# Default: 30
164+
max-func-lines: 0
165+
166+
nolintlint:
167+
# Exclude following linters from requiring an explanation.
168+
# Default: []
169+
allow-no-explanation: [funlen, gocognit, lll]
170+
# Enable to require an explanation of nonzero length after each nolint directive.
171+
# Default: false
172+
require-explanation: true
173+
# Enable to require nolint directives to mention the specific linter being suppressed.
174+
# Default: false
175+
require-specific: true
176+
177+
perfsprint:
178+
# Optimizes into strings concatenation.
179+
# Default: true
180+
strconcat: false
181+
182+
rowserrcheck:
183+
# database/sql is always checked
184+
# Default: []
185+
packages:
186+
- github.com/jmoiron/sqlx
187+
188+
sloglint:
189+
# Enforce not using global loggers.
190+
# Values:
191+
# - "": disabled
192+
# - "all": report all global loggers
193+
# - "default": report only the default slog logger
194+
# Default: ""
195+
no-global: "all"
196+
# Enforce using methods that accept a context.
197+
# Values:
198+
# - "": disabled
199+
# - "all": report all contextless calls
200+
# - "scope": report only if a context exists in the scope of the outermost function
201+
# Default: ""
202+
context: "scope"
203+
204+
tenv:
205+
# The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
206+
# Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
207+
# Default: false
208+
all: true
209+
210+
211+
linters:
212+
disable-all: true
213+
enable:
214+
## enabled by default
215+
- errcheck # checking for unchecked errors, these unchecked errors can be critical bugs in some cases
216+
- gosimple # specializes in simplifying a code
217+
- govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
218+
- ineffassign # detects when assignments to existing variables are not used
219+
- staticcheck # is a go vet on steroids, applying a ton of static analysis checks
220+
- typecheck # like the front-end of a Go compiler, parses and type-checks Go code
221+
- unused # checks for unused constants, variables, functions and types
222+
## disabled by default
223+
- asasalint # checks for pass []any as any in variadic func(...any)
224+
- asciicheck # checks that your code does not contain non-ASCII identifiers
225+
- bidichk # checks for dangerous unicode character sequences
226+
- bodyclose # checks whether HTTP response body is closed successfully
227+
- canonicalheader # checks whether net/http.Header uses canonical header
228+
- copyloopvar # detects places where loop variables are copied
229+
- cyclop # checks function and package cyclomatic complexity
230+
- dupl # tool for code clone detection
231+
- durationcheck # checks for two durations multiplied together
232+
- errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
233+
- errorlint # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13
234+
- exhaustive # checks exhaustiveness of enum switch statements
235+
- exportloopref # checks for pointers to enclosing loop variables
236+
- fatcontext # detects nested contexts in loops
237+
- forbidigo # forbids identifiers
238+
- funlen # tool for detection of long functions
239+
- gocheckcompilerdirectives # validates go compiler directive comments (//go:)
240+
- gochecknoglobals # checks that no global variables exist
241+
- gochecknoinits # checks that no init functions are present in Go code
242+
- gochecksumtype # checks exhaustiveness on Go "sum types"
243+
- gocognit # computes and checks the cognitive complexity of functions
244+
- goconst # finds repeated strings that could be replaced by a constant
245+
- gocritic # provides diagnostics that check for bugs, performance and style issues
246+
- gocyclo # computes and checks the cyclomatic complexity of functions
247+
- godot # checks if comments end in a period
248+
- goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt
249+
- gomoddirectives # manages the use of 'replace', 'retract', and 'excludes' directives in go.mod
250+
- gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations
251+
- goprintffuncname # checks that printf-like functions are named with f at the end
252+
- gosec # inspects source code for security problems
253+
- intrange # finds places where for loops could make use of an integer range
254+
- lll # reports long lines
255+
- loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap)
256+
- makezero # finds slice declarations with non-zero initial length
257+
- mirror # reports wrong mirror patterns of bytes/strings usage
258+
- mnd # detects magic numbers
259+
- musttag # enforces field tags in (un)marshaled structs
260+
- nakedret # finds naked returns in functions greater than a specified function length
261+
- nilerr # finds the code that returns nil even if it checks that the error is not nil
262+
- nilnil # checks that there is no simultaneous return of nil error and an invalid value
263+
- noctx # finds sending http request without context.Context
264+
- nolintlint # reports ill-formed or insufficient nolint directives
265+
- nonamedreturns # reports all named returns
266+
- nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
267+
- perfsprint # checks that fmt.Sprintf can be replaced with a faster alternative
268+
- predeclared # finds code that shadows one of Go's predeclared identifiers
269+
- promlinter # checks Prometheus metrics naming via promlint
270+
- reassign # checks that package variables are not reassigned
271+
- revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
272+
- rowserrcheck # checks whether Err of rows is checked successfully
273+
- sloglint # ensure consistent code style when using log/slog
274+
- spancheck # checks for mistakes with OpenTelemetry/Census spans
275+
- sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
276+
- stylecheck # is a replacement for golint
277+
- tenv # detects using os.Setenv instead of t.Setenv since Go1.17
278+
- testableexamples # checks if examples are testable (have an expected output)
279+
- testifylint # checks usage of github.com/stretchr/testify
280+
- testpackage # makes you use a separate _test package
281+
- tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes
282+
- unconvert # removes unnecessary type conversions
283+
- unparam # reports unused function parameters
284+
- usestdlibvars # detects the possibility to use variables/constants from the Go standard library
285+
- wastedassign # finds wasted assignment statements
286+
- whitespace # detects leading and trailing whitespace
287+
288+
## you may want to enable
289+
#- protogetter # reports direct reads from proto message fields when getters should be used
290+
#- nestif # reports deeply nested if statements
291+
#- decorder # checks declaration order and count of types, constants, variables and functions
292+
#- exhaustruct # [highly recommend to enable] checks if all structure fields are initialized
293+
#- gci # controls golang package import order and makes it always deterministic
294+
#- ginkgolinter # [if you use ginkgo/gomega] enforces standards of using ginkgo and gomega
295+
#- godox # detects FIXME, TODO and other comment keywords
296+
#- goheader # checks is file header matches to pattern
297+
#- inamedparam # [great idea, but too strict, need to ignore a lot of cases by default] reports interfaces with unnamed method parameters
298+
#- interfacebloat # checks the number of methods inside an interface
299+
#- ireturn # accept interfaces, return concrete types
300+
#- prealloc # [premature optimization, but can be used in some cases] finds slice declarations that could potentially be preallocated
301+
#- tagalign # checks that struct tags are well aligned
302+
#- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope
303+
#- wrapcheck # checks that errors returned from external packages are wrapped
304+
#- zerologlint # detects the wrong usage of zerolog that a user forgets to dispatch zerolog.Event
305+
306+
## disabled
307+
#- containedctx # detects struct contained context.Context field
308+
#- contextcheck # [too many false positives] checks the function whether use a non-inherited context
309+
#- depguard # [replaced by gomodguard] checks if package imports are in a list of acceptable packages
310+
#- dogsled # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
311+
#- dupword # [useless without config] checks for duplicate words in the source code
312+
#- err113 # [too strict] checks the errors handling expressions
313+
#- errchkjson # [don't see profit + I'm against of omitting errors like in the first example https://github.com/breml/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
314+
#- execinquery # [deprecated] checks query string in Query function which reads your Go src files and warning it finds
315+
#- forcetypeassert # [replaced by errcheck] finds forced type assertions
316+
#- gofmt # [replaced by goimports] checks whether code was gofmt-ed
317+
#- gofumpt # [replaced by goimports, gofumports is not available yet] checks whether code was gofumpt-ed
318+
#- gosmopolitan # reports certain i18n/l10n anti-patterns in your Go codebase
319+
#- grouper # analyzes expression groups
320+
#- importas # enforces consistent import aliases
321+
#- maintidx # measures the maintainability index of each function
322+
#- misspell # [useless] finds commonly misspelled English words in comments
323+
#- nlreturn # [too strict and mostly code is not more readable] checks for a new line before return and branch statements to increase code clarity
324+
#- paralleltest # [too many false positives] detects missing usage of t.Parallel() method in your Go test
325+
#- tagliatelle # checks the struct tags
326+
#- thelper # detects golang test helpers without t.Helper() call and checks the consistency of test helpers
327+
#- wsl # [too strict and mostly code is not more readable] whitespace linter forces you to use empty lines
328+
329+
330+
issues:
331+
# Maximum count of issues with the same text.
332+
# Set to 0 to disable.
333+
# Default: 3
334+
max-same-issues: 50
335+
336+
exclude-rules:
337+
- source: "(noinspection|TODO)"
338+
linters: [godot]
339+
- source: "//noinspection"
340+
linters: [gocritic]
341+
- path: "_test\\.go"
342+
linters:
343+
- bodyclose
344+
- dupl
345+
- funlen
346+
- goconst
347+
- gosec
348+
- noctx
349+
- wrapcheck

0 commit comments

Comments
 (0)