golangci / golangci-lint

Fast linters runner for Go
https://golangci-lint.run
GNU General Public License v3.0
15.38k stars 1.37k forks source link

Timeout configuration is ambiguous #3644

Closed stefan-ctrl closed 1 year ago

stefan-ctrl commented 1 year ago

Welcome

Description of the problem

As written in the rendered guide, the timeout config has two types of configurations.

Version 1 CMD: https://golangci-lint.run/usage/configuration/#command-line-options

 --timeout duration               Timeout for total work (default 1m0s)

Version 2 yaml: Timeout has two types of configurations

run:
  # The default concurrency value is the number of available CPU.
  concurrency: 4
  # Timeout for analysis, e.g. 30s, 5m.
  # Default: 1m
  timeout: 5m

The 2.Version doesn't seem to work as expected. Timeout is not passed if written as minutes without seconds

Version of golangci-lint

```console $ golangci-lint --version golangci-lint has version v1.51.2 built from (unknown, mod sum: "h1:yIcsT1X9ZYHdSpeWXRT1ORC/FPGSqDHbHsu9uk4FK7M=") on (unknown) ```

Configuration file

```console $ cat .golangci.yml run: timeout: 10m output: format: colored-line-number linters-settings: cyclop: max-complexity: 30 package-average: 10.0 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 funlen: # Checks the number of lines in a function. # If lower than 0, disable the check. # Default: 60 lines: 100 # Checks the number of statements in a function. # If lower than 0, disable the check. # Default: 40 statements: 50 gocognit: # Minimal code complexity to report # Default: 30 (but we recommend 10-20) min-complexity: 20 # https://go-critic.com/overview: gocritic: enabled-checks: #enable checks - appendAssign #Detects suspicious append result assignments - argOrder #Detects suspicious arguments order - badCall #Detects suspicious function calls - badCond #Detects suspicious condition expressions - caseOrder #Detects erroneous case order inside switch statements - codegenComment #Detects malformed 'code generated' file comments - deprecatedComment #Detects malformed 'deprecated' doc-comments - dupArg #Detects suspicious duplicated arguments - dupBranchBody #Detects duplicated branch bodies inside conditional statements - dupCase #Detects duplicated case clauses inside switch or select statements - dupSubExpr #Detects suspicious duplicated sub-expressions - exitAfterDefer #Detects calls to exit/fatal inside functions that use defer - flagDeref #Detects immediate dereferencing of `flag` package pointers - flagName #Detects suspicious flag names - mapKey #Detects suspicious map literal keys - offBy1 #Detects various off-by-one kind of errors - sloppyTypeAssert #Detects redundant type assertions - assignOp #Detects assignments that can be simplified by using assignment operators - captLocal #Detects capitalized names for local variables - commentedOutImport #Detects commented-out imports - defaultCaseOrder #Detects when default case in switch isn't on 1st or last position - elseif #Detects else with nested if statement that can be replaced with else-if - ifElseChain #Detects repeated if-else statements and suggests to replace them with switch statement - newDeref #Detects immediate dereferencing of `new` expressions - regexpMust #Detects `regexp.Compile*` that can be replaced with `regexp.MustCompile*` - singleCaseSwitch #Detects switch statements that could be better written as if statement - sloppyLen #Detects usage of `len` when result is obvious or doesn't make sense - switchTrue #Detects switch-over-bool statements that use explicit `true` tag value - typeSwitchVar #Detects type switches that can benefit from type guard clause with variable - underef #Detects dereference expressions that can be omitted - unlambda #Detects function literals that can be simplified - unslice #Detects slice expressions that can be simplified to sliced expression itself - valSwap #Detects value swapping code that are not using parallel assignment - wrapperFunc #Detects function calls that can be replaced with convenience wrappers - badLock # Detects suspicious mutex lock/unlock operations - badRegexp # Detects suspicious regexp patterns - emptyDecl # Detects suspicious empty declarations blocks - evalOrder # Detects unwanted dependencies on the evaluation order - nilValReturn # Detects return statements those results evaluate to nil - regexpPattern # Detects suspicious regexp patterns - returnAfterHttpError # Detects suspicious http.Error call without following return - boolExprSimplify # Detects bool expressions that can be simplified - unnamedResult # Detects unnamed results that may benefit from names - unnecessaryDefer # Detects unnamed results that may benefit from names - unnecessaryBlock # Detects unnecessary braced statement blocks - exposedSyncMutex # Detects exposed methods from sync.Mutex and sync.RWMutex. - whyNoLint # Ensures that `//nolint` comments include an explanation - yodaStyleExpr # Detects Yoda style expressions and suggests to replace them - equalFold # Detects unoptimal strings/bytes case-insensitive comparison - rangeExprCopy # Detects expensive copies of `for` loop range expressions - rangeValCopy # Detects loops that copy big objects during each iteration - stringXbytes # Detects redundant conversions between string and []byte - syncMapLoadAndDelete # Detects sync.Map load+delete operations that can be replaced with LoadAndDelete settings: captLocal: # Whether to restrict checker to params only. # Default: true paramsOnly: false underef: # Whether to skip (*x).method() calls where x is a pointer receiver. # Default: true skipRecvDeref: false gomnd: # List of function patterns to exclude from analysis. # Values always ignored: `time.Date` # Default: [] ignored-functions: - os.Chmod - os.Mkdir - os.MkdirAll - os.OpenFile - os.WriteFile - prometheus.ExponentialBuckets - prometheus.ExponentialBucketsRange - prometheus.LinearBuckets - strconv.FormatFloat - strconv.FormatInt - strconv.FormatUint - strconv.ParseFloat - strconv.ParseInt - strconv.ParseUint gomodguard: blocked: # List of blocked modules. # Default: [] modules: - github.com/golang/protobuf: recommendations: - google.golang.org/protobuf reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules" - github.com/satori/go.uuid: recommendations: - github.com/google/uuid reason: "satori's package is not maintained" - github.com/gofrs/uuid: recommendations: - github.com/google/uuid reason: "see recommendation from dev-infra team: https://confluence.gtforge.com/x/gQI6Aw" govet: # Enable all analyzers. # Default: false enable-all: true # Disable analyzers by name. # Run `go tool vet help` to see all analyzers. # Default: [] disable: - fieldalignment # Settings per analyzer. settings: shadow: # Whether to be strict about shadowing; can be noisy. # Default: false strict: true nakedret: # Make an issue if func has more lines of code than this setting, and it has naked returns. # Default: 30 max-func-lines: 0 tenv: # The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures. # Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked. # Default: false all: true linters: disable-all: true enable: ## enabled by default # https://golangci-lint.run/usage/linters/#enabled-by-default-linters - deadcode # Finds unused code - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - 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 - ineffassign # Detects when assignments to existing variables are not used - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - structcheck # Finds unused struct fields - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unused # Checks Go code for unused constants, variables, functions and types - varcheck # Finds unused global variables and constants ## disabled by default - 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 - cyclop # checks function and package cyclomatic complexity - dupl # Tool for code clone detection - durationcheck # check for two durations multiplied together - 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 - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gochecknoinits # Checks that no init functions are present in Go code - gocognit # Computes and checks the cognitive complexity of functions - goconst # Finds repeated strings that could be replaced by a constant - gocritic # Provides diagnostics that check for bugs, performance and style issues. - gocyclo # Computes and checks the cyclomatic complexity of functions - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. - 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 - lll # Reports long lines - makezero # Finds slice declarations with non-zero initial length - 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 - nonamedreturns # Reports all named returns - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. - predeclared # find code that shadows one of Go's predeclared identifiers - promlinter # Check Prometheus metrics naming via promlint - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - 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 - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - usestdlibvars # 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 ## you may want to enable #- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. #- gomnd # An analyzer to detect magic numbers. #- gochecknoglobals # check that no global variables exist #- godot # Check if comments end in a period #- decorder # check declaration order and count of types, constants, variables and functions #- testpackage # linter that makes you use a separate _test package, disabled since no private functions can be tested (black box testing not wanted) #- exhaustruct # Checks if all structure fields are initialized #- goheader # Checks is file header matches to pattern #- ireturn # Accept Interfaces, Return Concrete Types #- prealloc # [premature optimization, but can be used in some cases] Finds slice declarations that could potentially be preallocated #- varnamelen # [great idea, but too many false positives] checks that the length of a variable's name matches its scope #- wrapcheck # Checks that errors returned from external packages are wrapped ## disabled #- containedctx # containedctx is a linter that detects struct contained context.Context field #- depguard # [replaced by gomodguard] 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()) #- 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. #- forcetypeassert # [replaced by errcheck] finds forced type assertions #- gci # Gci controls golang package import order and makes it always deterministic. #- godox # Tool for detection of FIXME, TODO and other comment keywords #- goerr113 # [too strict] Golang linter to check the errors handling expressions #- gofmt # [replaced by goimports] Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification #- gofumpt # [replaced by goimports, gofumports is not available yet] Gofumpt checks whether code was gofumpt-ed. #- grouper # An analyzer to analyze expression groups. #- importas # Enforces consistent import aliases #- maintidx # maintidx measures the maintainability index of each function. #- misspell # [useless] Finds commonly misspelled English words in comments #- nlreturn # [too strict and mostly code is not more readable] nlreturn checks for a new line before return and branch statements to increase code clarity #- nosnakecase # Detects snake case of variable naming and function name. # TODO: maybe enable after https://github.com/sivchari/nosnakecase/issues/14 #- paralleltest # [too many false positives] paralleltest detects missing usage of t.Parallel() method in your Go test #- tagliatelle # Checks the struct tags. #- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers #- wsl # [too strict and mostly code is not more readable] Whitespace Linter - Forces you to use empty lines! issues: # Maximum count of issues with the same text. # Set to 0 to disable. # Default: 3 max-same-issues: 50 exclude-rules: - source: "^//\\s*go:generate\\s" linters: [ lll ] - source: "(noinspection|TODO)" linters: [ godot ] - source: "//noinspection" linters: [ gocritic ] - source: "^\\s+if _, ok := err\\.\\([^.]+\\.InternalError\\); ok {" linters: [ errorlint ] - path: "_test\\.go" linters: - bodyclose - dupl - funlen - goconst - gosec - noctx - wrapcheck ```

Go environment

```console $ go version go version go1.19.3 windows/amd64 $ go env PS C:\Users\xxxx> go env set GO111MODULE= set GOARCH=amd64 set GOBIN= set GOCACHE=C:\Users\xxxxxxx\AppData\Local\go-build set GOENV=C:\Users\xxxxxx\AppData\Roaming\go\env set GOEXE=.exe set GOEXPERIMENT= set GOFLAGS= set GOHOSTARCH=amd64 set GOHOSTOS=windows set GOINSECURE= set GOMODCACHE=C:\Users\xxxxx\go\pkg\mod set GONOPROXY=gitlab.corporate.de set GONOSUMDB=gitlab.corporate.de set GOOS=windows set GOPATH=C:\Users\xxxxxx\go set GOPRIVATE=gitlab.corporate.de set GOPROXY=https://proxy.golang.org,direct set GOROOT=C:\Users\xxxxx\scoop\apps\go\current set GOSUMDB=sum.golang.org set GOTMPDIR= set GOTOOLDIR=C:\Users\xxxxx\scoop\apps\go\current\pkg\tool\windows_amd64 set GOVCS= set GOVERSION=go1.19.3 set GCCGO=gccgo set GOAMD64=v1 set AR=ar set CC=gcc set CXX=g++ set CGO_ENABLED=1 set GOMOD=NUL set GOWORK= set CGO_CFLAGS=-g -O2 set CGO_CPPFLAGS= set CGO_CXXFLAGS=-g -O2 set CGO_FFLAGS=-g -O2 set CGO_LDFLAGS=-g -O2 set PKG_CONFIG=pkg-config set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -Wl,--no-gc-sections -fmessage-length=0 -fdebug-prefix-map=C:\Users\xxx~1\AppData\Local\Temp\go-build1954071009=/tmp/go-build -gno-record-gcc-switches ```

Verbose output of running

```console $ golangci-lint cache clean $ golangci-lint run -v level=info msg="[config_reader] Config search paths: [./root]" level=info msg="[lintersdb] Active 7 linters: [errcheck gosimple govet ineffassign staticcheck typecheck unused]" level=info msg="Memory: 602 samples, avg is 26.1MB, max is 26.1MB" level=info msg="Execution took 1m0.00219576s" level=info msg="[loader] Go packages loading at mode 575 (imports|types_sizes|deps|files|name|compiled_files|exports_file) took 59.997976036s" level=error msg="Running error: context loading failed: failed to load packages: failed to load with go/packages: err: context deadline exceeded: stderr: " level=error msg="Timeout exceeded: try increasing it by passing --timeout option" Cleaning up project directory and file based variables ```

Code example or link to a public repository

```go // add your code here ```
boring-cyborg[bot] commented 1 year ago

Hey, thank you for opening your first Issue ! 🙂 If you would like to contribute we have a guide for contributors.

ldez commented 1 year ago

Hello,

the 2 elements are the same option: --timeout is run.timeout.

ldez commented 1 year ago

CLI and YAML config about timeout have the exact same behavior with or without seconds.

It's just the result of time.ParseDuration() https://go.dev/play/p/e7yNAsQpFAY